mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-20 07:30:22 +01:00
27bbbc1cc4
## Summary Arguments of `preproc_call` nodes, like the `pack(push, 4)` in `#pragma pack(push, 4)` or the `FOO` in `#undef FOO`, had no highlight capture, so they always rendered as plain text. `#define` bodies are covered by the injection, and `#if` conditions are parsed as expressions, but nothing reached `preproc_call`'s `preproc_arg`. I added a `(preproc_call argument: (preproc_arg) @preproc)` rule to both the C and C++ highlight queries. I went with `@preproc` because every built-in theme already defines it, and it makes the whole directive line one color, like VS Code does. Happy to switch to `@constant.macro` or `@string` if you'd prefer. | Before | After | | --- | --- | | <img alt="preproc-before" src="https://github.com/user-attachments/assets/95fa0660-c41f-4433-98c7-887d9871fe1d" /> | <img alt="preproc-after" src="https://github.com/user-attachments/assets/7c4fa978-a6c1-4707-a627-6d7e32dd897a" /> | | <img alt="preproc-before-light" src="https://github.com/user-attachments/assets/3d2479ce-cd04-42ae-bfeb-e5c8c49fb9a6" /> | <img alt="preproc-after-light" src="https://github.com/user-attachments/assets/8d342f73-25e2-4dae-b984-72b88fd23287" /> | `#define FOO 1` and `#if defined(BAR)` look the same before and after. Closes #66675 ## Testing - Added a query test for C and one for C++, checking that `#pragma` and `#undef` arguments are captured as `preproc` and that a `#define` body isn't. Both fail without the query change. - `cargo test -p languages` passes (105 tests), and `./script/clippy -p languages` is clean. - Built the branch on macOS and compared it with Zed 1.28.1 on the same file, in One Dark and One Light (screenshots above). To try it: open a `.c` or `.cpp` file and type `#pragma pack(push, 4)` / `#undef FOO`. The arguments should now take the directive's color. I used Claude Code to help with this change and tested it myself. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - Improved syntax highlighting of `#pragma` and `#undef` arguments in C and C++. --------- Co-authored-by: imryanthedev <352313849+imryanthedev@users.noreply.github.com>
784 lines
26 KiB
Rust
784 lines
26 KiB
Rust
use anyhow::{Context as _, Result, bail};
|
|
use async_trait::async_trait;
|
|
use futures::StreamExt;
|
|
use github_releases::{
|
|
AssetKind, GitHubLspBinaryVersion, GithubBinaryMetadata, download_server_binary,
|
|
latest_github_release,
|
|
};
|
|
use gpui::{App, AsyncApp};
|
|
pub use language::*;
|
|
use lsp::{InitializeParams, LanguageServerBinary, LanguageServerName};
|
|
use project::lsp_store::clangd_ext;
|
|
use serde_json::json;
|
|
use smol::fs;
|
|
use std::{env::consts, future::Future, path::PathBuf, sync::Arc};
|
|
use util::{ResultExt, fs::remove_matching, maybe, merge_json_value_into};
|
|
|
|
pub struct CLspAdapter;
|
|
|
|
impl CLspAdapter {
|
|
const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("clangd");
|
|
}
|
|
|
|
impl LspInstaller for CLspAdapter {
|
|
type BinaryVersion = GitHubLspBinaryVersion;
|
|
|
|
async fn fetch_latest_server_version(
|
|
&self,
|
|
delegate: &Arc<dyn LspAdapterDelegate>,
|
|
pre_release: bool,
|
|
_: &mut AsyncApp,
|
|
) -> Result<GitHubLspBinaryVersion> {
|
|
ensure_arch_compatibility()?;
|
|
|
|
let release =
|
|
latest_github_release("clangd/clangd", true, pre_release, delegate.http_client())
|
|
.await?;
|
|
let os_suffix = match consts::OS {
|
|
"macos" => "mac",
|
|
"linux" => "linux",
|
|
"windows" => "windows",
|
|
other => bail!("Running on unsupported os: {other}"),
|
|
};
|
|
let asset_name = format!("clangd-{}-{}.zip", os_suffix, release.tag_name);
|
|
let asset = release
|
|
.assets
|
|
.iter()
|
|
.find(|asset| asset.name == asset_name)
|
|
.with_context(|| format!("no asset found matching {asset_name:?}"))?;
|
|
let version = GitHubLspBinaryVersion {
|
|
name: release.tag_name,
|
|
url: asset.browser_download_url.clone(),
|
|
digest: asset.digest.clone(),
|
|
};
|
|
Ok(version)
|
|
}
|
|
|
|
async fn check_if_user_installed(
|
|
&self,
|
|
delegate: &Arc<dyn LspAdapterDelegate>,
|
|
_: Option<Toolchain>,
|
|
_: &AsyncApp,
|
|
) -> Option<LanguageServerBinary> {
|
|
let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
|
|
Some(LanguageServerBinary {
|
|
path,
|
|
arguments: Vec::new(),
|
|
env: None,
|
|
})
|
|
}
|
|
|
|
fn fetch_server_binary(
|
|
&self,
|
|
version: GitHubLspBinaryVersion,
|
|
container_dir: PathBuf,
|
|
delegate: &Arc<dyn LspAdapterDelegate>,
|
|
) -> impl Send + Future<Output = Result<LanguageServerBinary>> + use<> {
|
|
let delegate = delegate.clone();
|
|
|
|
async move {
|
|
ensure_arch_compatibility()?;
|
|
|
|
let GitHubLspBinaryVersion {
|
|
name,
|
|
url,
|
|
digest: expected_digest,
|
|
} = version;
|
|
let version_dir = container_dir.join(format!("clangd_{name}"));
|
|
let binary_path = version_dir
|
|
.join("bin")
|
|
.join(format!("clangd{}", consts::EXE_SUFFIX));
|
|
|
|
let binary = LanguageServerBinary {
|
|
path: binary_path.clone(),
|
|
env: None,
|
|
arguments: Default::default(),
|
|
};
|
|
|
|
let metadata_path = version_dir.join("metadata");
|
|
let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
|
|
.await
|
|
.ok();
|
|
if let Some(metadata) = metadata {
|
|
let validity_check = async || {
|
|
delegate
|
|
.try_exec(LanguageServerBinary {
|
|
path: binary_path.clone(),
|
|
arguments: vec!["--version".into()],
|
|
env: None,
|
|
})
|
|
.await
|
|
.inspect_err(|err| {
|
|
log::warn!(
|
|
"Unable to run {binary_path:?} asset, redownloading: {err:#}",
|
|
)
|
|
})
|
|
};
|
|
if let (Some(actual_digest), Some(expected_digest)) =
|
|
(&metadata.digest, &expected_digest)
|
|
{
|
|
if actual_digest == expected_digest {
|
|
if validity_check().await.is_ok() {
|
|
return Ok(binary);
|
|
}
|
|
} else {
|
|
log::info!(
|
|
"SHA-256 mismatch for {binary_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
|
|
);
|
|
}
|
|
} else if validity_check().await.is_ok() {
|
|
return Ok(binary);
|
|
}
|
|
}
|
|
download_server_binary(
|
|
&delegate.background_executor(),
|
|
delegate.http_client(),
|
|
&url,
|
|
expected_digest.as_deref(),
|
|
&container_dir,
|
|
AssetKind::Zip,
|
|
)
|
|
.await?;
|
|
remove_matching(&container_dir, |entry| entry != version_dir).await;
|
|
GithubBinaryMetadata::write_to_file(
|
|
&GithubBinaryMetadata {
|
|
metadata_version: 1,
|
|
digest: expected_digest,
|
|
},
|
|
&metadata_path,
|
|
)
|
|
.await?;
|
|
|
|
Ok(binary)
|
|
}
|
|
}
|
|
|
|
async fn cached_server_binary(
|
|
&self,
|
|
container_dir: PathBuf,
|
|
_: &dyn LspAdapterDelegate,
|
|
) -> Option<LanguageServerBinary> {
|
|
get_cached_server_binary(container_dir).await
|
|
}
|
|
}
|
|
|
|
fn ensure_arch_compatibility() -> Result<()> {
|
|
let arch = consts::ARCH;
|
|
if consts::OS == "linux" && !["x86_64", "x86"].contains(&arch) {
|
|
anyhow::bail!(
|
|
"Clangd does not provide prebuilt binaries for {arch} to fetch from GitHub. Consider installing the binary manually."
|
|
)
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[async_trait(?Send)]
|
|
impl super::LspAdapter for CLspAdapter {
|
|
fn name(&self) -> LanguageServerName {
|
|
Self::SERVER_NAME
|
|
}
|
|
|
|
async fn label_for_completion(
|
|
&self,
|
|
completion: &lsp::CompletionItem,
|
|
language: &Arc<Language>,
|
|
) -> Option<CodeLabel> {
|
|
let label_detail = match &completion.label_details {
|
|
Some(label_detail) => match &label_detail.detail {
|
|
Some(detail) => detail.trim(),
|
|
None => "",
|
|
},
|
|
None => "",
|
|
};
|
|
|
|
let mut label = completion
|
|
.label
|
|
.strip_prefix('•')
|
|
.unwrap_or(&completion.label)
|
|
.trim()
|
|
.to_owned();
|
|
|
|
if !label_detail.is_empty() {
|
|
let should_add_space = match completion.kind {
|
|
Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD) => false,
|
|
_ => true,
|
|
};
|
|
|
|
if should_add_space && !label.ends_with(' ') && !label_detail.starts_with(' ') {
|
|
label.push(' ');
|
|
}
|
|
label.push_str(label_detail);
|
|
}
|
|
|
|
match completion.kind {
|
|
Some(lsp::CompletionItemKind::FIELD) if completion.detail.is_some() => {
|
|
let detail = completion.detail.as_ref().unwrap();
|
|
let text = format!("{} {}", detail, label);
|
|
let source = format!("struct S {{ {} }}", text);
|
|
let runs = language
|
|
.highlight_text(source.as_str(), 11..11 + text.len())
|
|
.collect();
|
|
let filter_range = completion
|
|
.filter_text
|
|
.as_deref()
|
|
.and_then(|filter_text| {
|
|
text.find(filter_text)
|
|
.map(|start| start..start + filter_text.len())
|
|
})
|
|
.unwrap_or(detail.len() + 1..text.len());
|
|
return Some(CodeLabel::new(text, filter_range, runs));
|
|
}
|
|
Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE)
|
|
if completion.detail.is_some() =>
|
|
{
|
|
let detail = completion.detail.as_ref().unwrap();
|
|
let text = format!("{} {}", detail, label);
|
|
let runs = language
|
|
.highlight_text(text.as_str(), 0..text.len())
|
|
.collect();
|
|
let filter_range = completion
|
|
.filter_text
|
|
.as_deref()
|
|
.and_then(|filter_text| {
|
|
text.find(filter_text)
|
|
.map(|start| start..start + filter_text.len())
|
|
})
|
|
.unwrap_or(detail.len() + 1..text.len());
|
|
return Some(CodeLabel::new(text, filter_range, runs));
|
|
}
|
|
Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD)
|
|
if completion.detail.is_some() =>
|
|
{
|
|
let detail = completion.detail.as_ref().unwrap();
|
|
let text = format!("{} {}", detail, label);
|
|
let runs = language
|
|
.highlight_text(text.as_str(), 0..text.len())
|
|
.collect();
|
|
let filter_range = completion
|
|
.filter_text
|
|
.as_deref()
|
|
.and_then(|filter_text| {
|
|
text.find(filter_text)
|
|
.map(|start| start..start + filter_text.len())
|
|
})
|
|
.unwrap_or_else(|| {
|
|
let filter_start = detail.len() + 1;
|
|
let filter_end = text
|
|
.rfind('(')
|
|
.filter(|end| *end > filter_start)
|
|
.unwrap_or(text.len());
|
|
filter_start..filter_end
|
|
});
|
|
|
|
return Some(CodeLabel::new(text, filter_range, runs));
|
|
}
|
|
Some(kind) => {
|
|
let highlight_name = match kind {
|
|
lsp::CompletionItemKind::STRUCT
|
|
| lsp::CompletionItemKind::INTERFACE
|
|
| lsp::CompletionItemKind::CLASS
|
|
| lsp::CompletionItemKind::ENUM => Some("type"),
|
|
lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
|
|
lsp::CompletionItemKind::KEYWORD => Some("keyword"),
|
|
lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
|
|
Some("constant")
|
|
}
|
|
_ => None,
|
|
};
|
|
if let Some(highlight_id) = language
|
|
.grammar()
|
|
.and_then(|g| g.highlight_id_for_name(highlight_name?))
|
|
{
|
|
let mut label = CodeLabel::plain(label, completion.filter_text.as_deref());
|
|
label.runs.push((
|
|
0..label.text.rfind('(').unwrap_or(label.text.len()),
|
|
highlight_id,
|
|
));
|
|
return Some(label);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
Some(CodeLabel::plain(label, completion.filter_text.as_deref()))
|
|
}
|
|
|
|
async fn label_for_symbol(
|
|
&self,
|
|
symbol: &language::Symbol,
|
|
language: &Arc<Language>,
|
|
) -> Option<CodeLabel> {
|
|
let name = &symbol.name;
|
|
let (text, filter_range, display_range) = match symbol.kind {
|
|
language::SymbolKind::Method | language::SymbolKind::Function => {
|
|
let text = format!("void {} () {{}}", name);
|
|
let filter_range = 0..name.len();
|
|
let display_range = 5..5 + name.len();
|
|
(text, filter_range, display_range)
|
|
}
|
|
language::SymbolKind::Struct => {
|
|
let text = format!("struct {} {{}}", name);
|
|
let filter_range = 7..7 + name.len();
|
|
let display_range = 0..filter_range.end;
|
|
(text, filter_range, display_range)
|
|
}
|
|
language::SymbolKind::Enum => {
|
|
let text = format!("enum {} {{}}", name);
|
|
let filter_range = 5..5 + name.len();
|
|
let display_range = 0..filter_range.end;
|
|
(text, filter_range, display_range)
|
|
}
|
|
language::SymbolKind::Interface | language::SymbolKind::Class => {
|
|
let text = format!("class {} {{}}", name);
|
|
let filter_range = 6..6 + name.len();
|
|
let display_range = 0..filter_range.end;
|
|
(text, filter_range, display_range)
|
|
}
|
|
language::SymbolKind::Constant => {
|
|
let text = format!("const int {} = 0;", name);
|
|
let filter_range = 10..10 + name.len();
|
|
let display_range = 0..filter_range.end;
|
|
(text, filter_range, display_range)
|
|
}
|
|
language::SymbolKind::Module => {
|
|
let text = format!("namespace {} {{}}", name);
|
|
let filter_range = 10..10 + name.len();
|
|
let display_range = 0..filter_range.end;
|
|
(text, filter_range, display_range)
|
|
}
|
|
language::SymbolKind::TypeParameter => {
|
|
let text = format!("typename {} {{}};", name);
|
|
let filter_range = 9..9 + name.len();
|
|
let display_range = 0..filter_range.end;
|
|
(text, filter_range, display_range)
|
|
}
|
|
_ => return None,
|
|
};
|
|
|
|
Some(CodeLabel::new(
|
|
text[display_range.clone()].to_string(),
|
|
filter_range,
|
|
language
|
|
.highlight_text(text.as_str(), display_range)
|
|
.collect(),
|
|
))
|
|
}
|
|
|
|
fn prepare_initialize_params(
|
|
&self,
|
|
mut original: InitializeParams,
|
|
_: &App,
|
|
) -> Result<InitializeParams> {
|
|
let experimental = json!({
|
|
"textDocument": {
|
|
"completion" : {
|
|
// enable clangd's dot-to-arrow feature.
|
|
"editsNearCursor": true
|
|
},
|
|
"inactiveRegionsCapabilities": {
|
|
"inactiveRegions": true,
|
|
}
|
|
}
|
|
});
|
|
if let Some(ref mut original_experimental) = original.capabilities.experimental {
|
|
merge_json_value_into(experimental, original_experimental);
|
|
} else {
|
|
original.capabilities.experimental = Some(experimental);
|
|
}
|
|
Ok(original)
|
|
}
|
|
|
|
fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic) -> bool {
|
|
clangd_ext::is_inactive_region(previous_diagnostic)
|
|
}
|
|
|
|
fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
|
|
!clangd_ext::is_lsp_inactive_region(diagnostic)
|
|
}
|
|
}
|
|
|
|
async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
|
|
maybe!(async {
|
|
let mut last_clangd_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_clangd_dir = Some(entry.path());
|
|
}
|
|
}
|
|
let clangd_dir = last_clangd_dir.context("no cached binary")?;
|
|
let clangd_bin = clangd_dir
|
|
.join("bin")
|
|
.join(format!("clangd{}", consts::EXE_SUFFIX));
|
|
anyhow::ensure!(
|
|
clangd_bin.exists(),
|
|
"missing clangd binary in directory {clangd_dir:?}"
|
|
);
|
|
Ok(LanguageServerBinary {
|
|
path: clangd_bin,
|
|
env: None,
|
|
arguments: Vec::new(),
|
|
})
|
|
})
|
|
.await
|
|
.log_err()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use gpui::{AppContext as _, BorrowAppContext, TestAppContext};
|
|
use indoc::indoc;
|
|
use language::{AutoindentMode, Buffer};
|
|
use settings::SettingsStore;
|
|
use std::num::NonZeroU32;
|
|
use tree_sitter::StreamingIterator;
|
|
use unindent::Unindent;
|
|
|
|
#[gpui::test]
|
|
async fn test_c_autoindent_basic(cx: &mut TestAppContext) {
|
|
cx.update(|cx| {
|
|
let test_settings = SettingsStore::test(cx);
|
|
cx.set_global(test_settings);
|
|
cx.update_global::<SettingsStore, _>(|store, cx| {
|
|
store.update_user_settings(cx, |s| {
|
|
s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
|
|
});
|
|
});
|
|
});
|
|
let language = crate::language("c", tree_sitter_c::LANGUAGE.into());
|
|
|
|
cx.new(|cx| {
|
|
let mut buffer = Buffer::local("", cx).with_language(language, cx);
|
|
|
|
buffer.edit([(0..0, "int main() {}")], None, cx);
|
|
|
|
let ix = buffer.len() - 1;
|
|
buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
"int main() {\n \n}",
|
|
"content inside braces should be indented"
|
|
);
|
|
|
|
buffer
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
async fn test_c_autoindent_switch_case(cx: &mut TestAppContext) {
|
|
cx.update(|cx| {
|
|
let test_settings = SettingsStore::test(cx);
|
|
cx.set_global(test_settings);
|
|
cx.update_global::<SettingsStore, _>(|store, cx| {
|
|
store.update_user_settings(cx, |s| {
|
|
s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
|
|
});
|
|
});
|
|
});
|
|
let language = crate::language("c", tree_sitter_c::LANGUAGE.into());
|
|
|
|
cx.new(|cx| {
|
|
let mut buffer = Buffer::local("", cx).with_language(language, cx);
|
|
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
switch (a) {
|
|
case 1:
|
|
b++;
|
|
break;
|
|
case 2:
|
|
case 3:
|
|
c++;
|
|
break;
|
|
default:
|
|
d++;
|
|
}
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
switch (a) {
|
|
case 1:
|
|
b++;
|
|
break;
|
|
case 2:
|
|
case 3:
|
|
c++;
|
|
break;
|
|
default:
|
|
d++;
|
|
}
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"statements under a case label should be indented, and the next label outdented"
|
|
);
|
|
|
|
buffer
|
|
});
|
|
}
|
|
|
|
#[gpui::test]
|
|
async fn test_c_autoindent_if_else(cx: &mut TestAppContext) {
|
|
cx.update(|cx| {
|
|
let test_settings = SettingsStore::test(cx);
|
|
cx.set_global(test_settings);
|
|
cx.update_global::<SettingsStore, _>(|store, cx| {
|
|
store.update_user_settings(cx, |s| {
|
|
s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
|
|
});
|
|
});
|
|
});
|
|
let language = crate::language("c", tree_sitter_c::LANGUAGE.into());
|
|
|
|
cx.new(|cx| {
|
|
let mut buffer = Buffer::local("", cx).with_language(language, cx);
|
|
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"body of if-statement without braces should be indented"
|
|
);
|
|
|
|
let ix = buffer.len() - 4;
|
|
buffer.edit([(ix..ix, "\n.c")], Some(AutoindentMode::EachLine), cx);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b
|
|
.c;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"field expression (.c) should be indented further than the statement body"
|
|
);
|
|
|
|
buffer.edit([(0..buffer.len(), "")], Some(AutoindentMode::EachLine), cx);
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
if (a) a++;
|
|
else b++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a) a++;
|
|
else b++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"single-line if/else without braces should align at the same level"
|
|
);
|
|
|
|
buffer.edit([(0..buffer.len(), "")], Some(AutoindentMode::EachLine), cx);
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b++;
|
|
else
|
|
c++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b++;
|
|
else
|
|
c++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"multi-line if/else without braces should indent statement bodies"
|
|
);
|
|
|
|
buffer.edit([(0..buffer.len(), "")], Some(AutoindentMode::EachLine), cx);
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
if (b)
|
|
c++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
if (b)
|
|
c++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"nested if statements without braces should indent properly"
|
|
);
|
|
|
|
buffer.edit([(0..buffer.len(), "")], Some(AutoindentMode::EachLine), cx);
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b++;
|
|
else if (c)
|
|
d++;
|
|
else
|
|
f++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a)
|
|
b++;
|
|
else if (c)
|
|
d++;
|
|
else
|
|
f++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"else-if chains should align all conditions at same level with indented bodies"
|
|
);
|
|
|
|
buffer.edit([(0..buffer.len(), "")], Some(AutoindentMode::EachLine), cx);
|
|
buffer.edit(
|
|
[(
|
|
0..0,
|
|
r#"
|
|
int main() {
|
|
if (a) {
|
|
b++;
|
|
} else
|
|
c++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
)],
|
|
Some(AutoindentMode::EachLine),
|
|
cx,
|
|
);
|
|
assert_eq!(
|
|
buffer.text(),
|
|
r#"
|
|
int main() {
|
|
if (a) {
|
|
b++;
|
|
} else
|
|
c++;
|
|
}
|
|
"#
|
|
.unindent(),
|
|
"mixed braces should indent properly"
|
|
);
|
|
|
|
buffer
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn test_c_highlights_query_captures_preproc_call_arguments() {
|
|
let language: tree_sitter::Language = tree_sitter_c::LANGUAGE.into();
|
|
let query_source = include_str!("../../grammars/src/c/highlights.scm");
|
|
|
|
let query = tree_sitter::Query::new(&language, query_source)
|
|
.expect("C highlights query should compile");
|
|
|
|
let source = indoc! {"
|
|
#pragma pack(push, 4)
|
|
#undef FOO
|
|
#define BAR 42
|
|
"};
|
|
|
|
let mut parser = tree_sitter::Parser::new();
|
|
parser.set_language(&language).unwrap();
|
|
|
|
let tree = parser.parse(source, None).expect("C source should parse");
|
|
|
|
let mut cursor = tree_sitter::QueryCursor::new();
|
|
let mut matches = cursor.matches(&query, tree.root_node(), source.as_bytes());
|
|
|
|
let mut captures = Vec::new();
|
|
|
|
while let Some(query_match) = matches.next() {
|
|
for capture in query_match.captures() {
|
|
let capture_name = query.capture_names()[capture.index as usize];
|
|
let captured_text = &source[capture.node.byte_range()];
|
|
|
|
captures.push((captured_text.to_owned(), capture_name.to_owned()));
|
|
}
|
|
}
|
|
|
|
assert!(captures.contains(&("#pragma".into(), "preproc".into())));
|
|
assert!(captures.contains(&("pack(push, 4)".into(), "preproc".into())));
|
|
assert!(captures.contains(&("FOO".into(), "preproc".into())));
|
|
assert!(!captures.contains(&("42".into(), "preproc".into())));
|
|
}
|
|
}
|