fix(cpp): recognise extensionless standard library headers (#7547)

Extensionless files inside libstdc++, libc++ and MSVC include trees open as C++; an ordinary file named like a header elsewhere stays plain text, and explicit associations and first-line detection keep precedence.

Fixes #7503
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-02 21:17:04 +08:00
1 джерело a68ebc1293
коміт e6c8d6d9ac
1 file changed
+36 -1
+36 -1
Переглянути файл
@@ -398,7 +398,7 @@ impl LanguageRegistry {
/// Detects by Override File Type, exact file name, then file-name pattern
/// (`Dockerfile.*`), then extension (longest compound first, e.g. `d.ts`),
/// then hashbang / first line; falls back to plaintext. The user's patterns
/// then hashbang / first line and toolchain headers; falls back to plaintext. The user's patterns
/// win over the definitions'.
pub fn detect(&self, path: &Path, first_line: Option<&str>) -> LanguageId {
let state = self.state();
@@ -441,10 +441,29 @@ impl LanguageRegistry {
return languages[*i].id.clone();
}
}
if is_cpp_toolchain_header(path, file_name)
&& let Some(cpp) = languages.iter().find(|l| l.id.as_str() == "cpp")
{
return cpp.id.clone();
}
LanguageId::plain_text()
}
}
fn is_cpp_toolchain_header(path: &Path, name: &str) -> bool {
if name.is_empty() || !name.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_') {
return false;
}
let named = |dir: &Path, expected: &str| {
dir.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.eq_ignore_ascii_case(expected))
};
path.ancestors().skip(1).any(|dir| {
// libstdc++ and libc++ use include/c++; MSVC uses MSVC/<version>/include.
(named(dir, "c++") && dir.parent().is_some_and(|parent| named(parent, "include")))
|| (named(dir, "include") && dir.parent().and_then(Path::parent).is_some_and(|p| named(p, "MSVC")))
})
}
/// `path` has a listed extension and lies under a matching folder with a root marker.
fn is_framework_file(files: &crate::FrameworkFiles, path: &Path) -> bool {
let Some(ext) = path.extension().and_then(|e| e.to_str()) else { return false };
@@ -694,6 +713,22 @@ mod tests {
assert_eq!(rust.language_servers[0].name, "rust-analyzer");
}
#[test]
fn detects_extensionless_cpp_toolchain_headers() {
let reg = reg();
for path in [
"/usr/include/c++/13/vector",
"/sdk/usr/include/c++/v1/__algorithm/copy",
"C:/Program Files/LLVM/include/c++/v1/iostream",
"C:/Program Files/Microsoft Visual Studio/VC/Tools/MSVC/14.40.33807/include/vector",
] {
assert_eq!(detect(&reg, path), "cpp", "{path}");
}
assert_eq!(detect(&reg, "/project/vector"), "plaintext");
assert_eq!(detect(&reg, "/project/include/vector"), "plaintext");
assert_eq!(detect(&reg, "/usr/include/c++/13/README"), "plaintext");
}
#[test]
fn razor_shares_the_csharp_roslyn_server() {
let reg = reg();