Visual Studio Code, rebuilt in Rust
Rust
//! Language detection by file path, as `getLanguageIds` does (languagesAssociations.ts) over the
//! `contributes.languages` of the built-in extensions (languagesRegistry.ts `_mergeLanguage`).
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use exthost::scan::ScannedExtension;
use files::glob::{self, Glob};
use serde_json::Value;
use crate::brackets::LanguageBrackets;
use crate::editor::auto_indent::LanguageRules;
use crate::editor::folding::FoldingMarkers;
use crate::theme::strip_jsonc;
pub const PLAINTEXT: &str = "plaintext";
pub const BINARY_TEXT_FILE_MODE: &str = "code-text-binary";
struct Association {
id: String,
filename: Option<String>,
extension: Option<String>,
filepattern: Option<(String, Glob)>,
// Lowercased once here: guess_language runs per Explorer row on every draw.
filename_lowercase: Option<String>,
extension_lowercase: Option<String>,
}
/// `ICommentsConfiguration`: the line comment token, whether it goes in the first column, the block comment tokens.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Comments<'a> {
pub line: Option<&'a str>,
pub line_no_indent: bool,
pub block: Option<(&'a str, &'a str)>,
}
pub struct Languages {
/// In registration order: the core plaintext language first (modesRegistry.ts), then the extensions.
associations: Vec<Association>,
/// Language ids in the order they were first registered.
ids: Vec<String>,
names: HashMap<String, String>,
/// `_lowercaseNameMap`: each language's id and aliases, lower-cased.
lowercase_names: HashMap<String, String>,
off_side: HashMap<String, bool>,
folding_markers: HashMap<String, Arc<FoldingMarkers>>,
block_comments: HashMap<String, (String, String)>,
/// `comments.lineComment`: the token and `noIndent`.
line_comments: HashMap<String, (String, bool)>,
/// `firstLine` patterns in registration order, anchored at the line start (languagesRegistry.ts).
first_lines: Vec<(String, onig::Regex)>,
pub grammars: textmate::Registry,
pub brackets: HashMap<String, LanguageBrackets>,
rules: HashMap<String, LanguageRules>,
/// Each language's configuration file, the priority 0 entry of languageConfigurationRegistry.ts.
file_configurations: HashMap<String, Value>,
/// `setLanguageConfiguration`s by handle in registration order, priority 100: each wins over the file and
/// the ones before it.
api_configurations: Vec<(u64, String, Value)>,
}
impl Languages {
pub fn new(extensions: &[ScannedExtension]) -> Self {
let mut languages = Languages { associations: Vec::new(), ids: Vec::new(), names: HashMap::new(), lowercase_names: HashMap::new(), off_side: HashMap::new(), folding_markers: HashMap::new(), block_comments: HashMap::new(), line_comments: HashMap::new(), first_lines: Vec::new(), grammars: textmate::Registry::default(), brackets: HashMap::new(), rules: HashMap::new(), file_configurations: HashMap::new(), api_configurations: Vec::new() };
languages.register(&serde_json::json!({ "id": PLAINTEXT, "extensions": [".txt"], "aliases": ["Plain Text", "text"] }), None);
// files.contribution.ts: BINARY_TEXT_FILE_MODE, the language of a binary file opened as text anyway.
languages.register(&serde_json::json!({ "id": BINARY_TEXT_FILE_MODE, "aliases": ["Binary"], "mimetypes": ["text/x-code-binary"] }), None);
for extension in extensions {
let Some(contribution) = extension.description["contributes"].get("languages") else { continue };
let error = |message: String| crate::perf::extension_point_message(&extension.id, crate::notifications::Severity::Error, message);
let Some(contributed) = contribution.as_array() else {
error("Invalid `contributes.languages`. Expected an array.".into());
continue;
};
for language in contributed {
match language_reject(language) {
Some(reject) => error(reject),
None => languages.register(language, Some(&extension.location)),
}
}
}
for extension in extensions {
for grammar in extension.description["contributes"]["grammars"].as_array().into_iter().flatten() {
let report = |severity, message| crate::perf::extension_point_message(&extension.id, severity, message);
match languages.validate_grammar(&extension.location, grammar) {
Err(error) => report(crate::notifications::Severity::Error, error),
Ok(warning) => {
if let Some(warning) = warning {
report(crate::notifications::Severity::Warning, warning);
}
languages.grammars.register(&extension.location, grammar);
}
}
}
}
languages
}
/// textMateTokenizationFeatureImpl.ts `validateGrammarExtensionPoint`: the error that rejects the grammar, or
/// the warning of a grammar outside the extension's folder.
fn validate_grammar(&self, extension_location: &Path, grammar: &Value) -> Result<Option<String>, String> {
use crate::contextkey::{js_string, truthy};
let present = |key: &str| truthy(grammar.get(key));
let language = &grammar["language"];
if present("language") && !language.as_str().is_some_and(|language| self.ids.iter().any(|id| id == language)) {
return Err(format!("Unknown language in `contributes.grammars.language`. Provided value: {}", js_string(grammar.get("language"))));
}
if !present("scopeName") || !grammar["scopeName"].is_string() {
return Err(format!("Expected string in `contributes.grammars.scopeName`. Provided value: {}", js_string(grammar.get("scopeName"))));
}
let Some(path) = grammar["path"].as_str().filter(|path| !path.is_empty()) else {
return Err(format!("Expected string in `contributes.grammars.path`. Provided value: {}", js_string(grammar.get("path"))));
};
if present("injectTo") && !grammar["injectTo"].as_array().is_some_and(|scopes| scopes.iter().all(Value::is_string)) {
return Err(format!("Invalid value in `contributes.grammars.injectTo`. Must be an array of language scope names. Provided value: {}", grammar["injectTo"]));
}
if present("embeddedLanguages") && !grammar["embeddedLanguages"].is_object() {
return Err(format!("Invalid value in `contributes.grammars.embeddedLanguages`. Must be an object map from scope name to language. Provided value: {}", grammar["embeddedLanguages"]));
}
if present("tokenTypes") && !grammar["tokenTypes"].is_object() {
return Err(format!("Invalid value in `contributes.grammars.tokenTypes`. Must be an object map from scope name to token type. Provided value: {}", grammar["tokenTypes"]));
}
let location = crate::extension_point_messages::join_path(extension_location, path);
Ok((!location.starts_with(extension_location)).then(|| {
format!("Expected `contributes.grammars.path` ({}) to be included inside extension's folder ({}). This might make the extension non-portable.", crate::extension_point_messages::uri_path(&location), crate::extension_point_messages::uri_path(extension_location))
}))
}
fn register(&mut self, language: &Value, location: Option<&Path>) {
let Some(id) = language["id"].as_str() else { return };
let strings = |key: &str| language[key].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::<Vec<_>>();
let association = |filename: Option<String>, extension: Option<String>, filepattern| Association {
id: id.into(),
filename_lowercase: filename.as_deref().map(str::to_lowercase),
extension_lowercase: extension.as_deref().map(str::to_lowercase),
filename,
extension,
filepattern,
};
for extension in strings("extensions") {
self.associations.push(association(None, Some(extension), None));
}
for filename in strings("filenames") {
self.associations.push(association(Some(filename), None, None));
}
for pattern in strings("filenamePatterns") {
let parsed = glob::parse(&pattern, IGNORE_CASE);
self.associations.push(association(None, None, Some((pattern, parsed))));
}
if !self.ids.iter().any(|known| known == id) {
self.ids.push(id.into());
}
self.lowercase_names.insert(id.to_lowercase(), id.into());
for alias in strings("aliases").into_iter().filter(|alias| !alias.is_empty()) {
self.lowercase_names.insert(alias.to_lowercase(), id.into());
}
// The first alias names the language and a later contribution with aliases renames it; one without aliases
// keeps the name, and empty `aliases` leave the language without one.
match language["aliases"].as_array() {
Some(aliases) if aliases.is_empty() => {}
Some(aliases) => {
let name = aliases[0].as_str().filter(|alias| !alias.is_empty()).unwrap_or(id);
self.names.insert(id.into(), name.into());
}
None => {
self.names.entry(id.into()).or_insert_with(|| id.into());
}
}
if let Some(first_line) = language["firstLine"].as_str().filter(|pattern| !pattern.is_empty()) {
let anchored = if first_line.starts_with('^') { first_line.to_string() } else { format!("^{first_line}") };
match onig::Regex::new(&anchored) {
Ok(regex) => self.first_lines.push((id.into(), regex)),
Err(error) => eprintln!("[{id}]: Invalid regular expression `{anchored}`: {error}"),
}
}
if let (Some(location), Some(configuration)) = (location, language["configuration"].as_str()) {
let config = std::fs::read_to_string(location.join(configuration))
.ok()
.and_then(|text| serde_json::from_str::<Value>(&strip_jsonc(&text)).ok())
.unwrap_or_default();
self.configure(id, &config);
self.file_configurations.insert(id.into(), config);
}
}
/// `LanguageConfigurationFileHandler._handleConfig`: the language configuration file of a language.
pub(crate) fn configure(&mut self, id: &str, config: &Value) {
self.block_comments.remove(id);
self.line_comments.remove(id);
self.folding_markers.remove(id);
self.off_side.insert(id.into(), config["folding"]["offSide"].as_bool() == Some(true));
if let (Some(start), Some(end)) = (config["comments"]["blockComment"][0].as_str(), config["comments"]["blockComment"][1].as_str()) {
self.block_comments.insert(id.into(), (start.into(), end.into()));
}
// languageConfigurationRegistry.ts: an empty token is no line comment.
let line_comment = &config["comments"]["lineComment"];
let token = line_comment.as_str().or_else(|| line_comment["comment"].as_str()).filter(|token| !token.is_empty());
if let Some(token) = token {
self.line_comments.insert(id.into(), (token.into(), line_comment["noIndent"].as_bool() == Some(true)));
}
let markers = &config["folding"]["markers"];
if let (Some(start), Some(end)) = (marker_pattern(&markers["start"]), marker_pattern(&markers["end"])) {
match FoldingMarkers::new(start, end) {
Ok(markers) => {
self.folding_markers.insert(id.into(), Arc::new(markers));
}
Err(error) => eprintln!("[{id}]: Invalid regular expression in `folding.markers`: {error}"),
}
}
self.brackets.insert(id.into(), LanguageBrackets::new(id, config));
self.rules.insert(id.into(), LanguageRules::new(id, config));
}
/// mainThreadLanguageFeatures.ts `$setLanguageConfiguration`: an extension's configuration over the file's, false
/// for a language not registered.
pub fn set_extension_configuration(&mut self, handle: u64, id: &str, dto: &Value) -> bool {
if !self.ids.iter().any(|known| known == id) {
return false;
}
self.api_configurations.push((handle, id.into(), configuration_of_dto(dto)));
self.combine_configurations(id);
true
}
/// The registration's disposal: the language it configured, now back to the remaining configurations.
pub fn remove_extension_configuration(&mut self, handle: u64) -> Option<String> {
let index = self.api_configurations.iter().position(|(registered, _, _)| *registered == handle)?;
let (_, id, _) = self.api_configurations.remove(index);
self.combine_configurations(&id);
Some(id)
}
/// `combineLanguageConfigurations`: key by key, the last entry that sets it.
fn combine_configurations(&mut self, id: &str) {
let mut combined = self.file_configurations.get(id).filter(|config| config.is_object()).cloned().unwrap_or_else(|| serde_json::json!({}));
for (_, language, config) in &self.api_configurations {
if language != id {
continue;
}
for (key, value) in config.as_object().into_iter().flatten() {
if !value.is_null() {
combined[key] = value.clone();
}
}
}
self.configure(id, &combined);
}
/// The language of a file by its path, else by the `firstLine` pattern its first line matches. No
/// association falls back to plaintext, as the text file model does with "unknown".
pub fn language_of<'a>(&'a self, path: &Path, first_line: &str) -> &'a str {
self.guess_language(path, first_line).unwrap_or(PLAINTEXT)
}
/// `guessLanguageIdByFilepathOrFirstLine`: `None` when no association matches.
pub fn guess_language<'a>(&'a self, path: &Path, first_line: &str) -> Option<&'a str> {
let path = resource_path(path);
let filename = path.rsplit('/').next().unwrap_or(&path);
let mut pattern_match: Option<&Association> = None;
let mut extension_match: Option<&Association> = None;
// Later registrations win, so walk backwards; an exact filename ends the search.
for association in self.associations.iter().rev() {
if association.filename_lowercase.as_deref() == Some(filename) {
return Some(&association.id);
}
if let Some((pattern, parsed)) = &association.filepattern {
let longer = pattern_match.is_none_or(|best| pattern.len() > best.filepattern.as_ref().unwrap().0.len());
let target = if pattern.contains('/') { path.as_str() } else { filename };
if longer && parsed.matches(target, None, None).is_some() {
pattern_match = Some(association);
}
}
if let Some(extension) = &association.extension {
let longer = extension_match.is_none_or(|best| extension.len() > best.extension.as_ref().unwrap().len());
if longer && filename.ends_with(association.extension_lowercase.as_deref().unwrap()) {
extension_match = Some(association);
}
}
}
if let Some(association) = pattern_match.or(extension_match) {
return Some(&association.id);
}
// getAssociationByFirstline: the last registered pattern wins, over the first 1000 chars (FIRST_LINE_DETECTION_LENGTH_LIMIT).
let first_line: String = first_line.chars().take(1000).collect();
let first_line = first_line.strip_prefix('\u{FEFF}').unwrap_or(&first_line);
self.first_lines.iter().rev().find(|(_, regex)| !first_line.is_empty() && regex.find(first_line).is_some()).map(|(id, _)| id.as_str())
}
/// The `files.associations` language of a path (`userConfigured` associations): the longest pattern that
/// matches, against the whole path when the pattern has a `/`, else the file name, ignoring case.
pub fn configured_language(associations: &Value, path: &Path) -> Option<String> {
let path = resource_path(path);
let filename = path.rsplit('/').next().unwrap_or(&path);
let mut best: Option<(&str, &str)> = None;
for (pattern, id) in associations.as_object()? {
let Some(id) = id.as_str() else { continue };
let target = if pattern.contains('/') { path.as_str() } else { filename };
if best.is_none_or(|(longest, _)| pattern.len() > longest.len()) && glob::match_pattern(pattern, target, IGNORE_CASE) {
best = Some((pattern, id));
}
}
best.map(|(_, id)| id.to_string())
}
/// `getRegisteredLanguageIds`.
pub fn ids(&self) -> &[String] {
&self.ids
}
pub fn is_registered(&self, id: &str) -> bool {
self.ids.iter().any(|known| known == id)
}
/// `getLanguageIdByLanguageName`: the language one of its aliases or its id names, ignoring case.
pub fn id_by_name(&self, name: &str) -> Option<&str> {
self.lowercase_names.get(&name.to_lowercase()).map(String::as_str)
}
pub fn name<'a>(&'a self, id: &'a str) -> &'a str {
self.names.get(id).map_or(id, String::as_str)
}
/// textFileService.ts `suggestFilename`: an untitled name keeps an extension of the language, else takes the
/// language's first extension in place of its own, else its first file name; an unnamed language keeps it.
pub fn suggest_file_name(&self, id: &str, untitled_name: &str) -> String {
if !self.names.contains_key(id) {
return untitled_name.to_string();
}
let of_language = |pick: fn(&Association) -> Option<&String>| -> Vec<&str> {
let mut values: Vec<&str> = Vec::new();
for value in self.associations.iter().filter(|association| association.id == id).filter_map(pick) {
if !values.contains(&value.as_str()) {
values.push(value);
}
}
values
};
let extensions = of_language(|association| association.extension.as_ref());
// path.extname: from the last dot that does not start the name.
let extension = untitled_name.rfind('.').filter(|dot| *dot > 0).map_or("", |dot| &untitled_name[dot..]);
if extensions.contains(&extension) {
return untitled_name.to_string();
}
if let Some(primary) = extensions.first() {
let stem = if extension.is_empty() { untitled_name } else { &untitled_name[..untitled_name.find(extension).expect("found above")] };
return format!("{stem}{primary}");
}
let filenames = of_language(|association| association.filename.as_ref());
if filenames.contains(&untitled_name) {
return untitled_name.to_string();
}
filenames.first().map_or(untitled_name, |name| name).to_string()
}
/// `getExtensions`: the language's extensions with their dot, each once, in registration order.
pub fn extensions(&self, id: &str) -> Vec<&str> {
let mut extensions: Vec<&str> = Vec::new();
for extension in self.associations.iter().filter(|association| association.id == id).filter_map(|association| association.extension.as_deref()) {
if !extensions.contains(&extension) {
extensions.push(extension);
}
}
extensions
}
/// `getSortedRegisteredLanguageNames`: each name with its language, the last language registered under a name,
/// sorted ignoring case.
pub fn sorted_names(&self) -> Vec<(&str, &str)> {
let mut by_name: Vec<(&str, &str)> = Vec::new();
for id in &self.ids {
let Some(name) = self.names.get(id) else { continue };
by_name.retain(|(known, _)| known != name);
by_name.push((name, id));
}
by_name.sort_by_key(|(name, _)| name.to_lowercase());
by_name
}
/// `foldingRules.offSide` of the language configuration: blank lines take the indent of the block below.
pub fn off_side(&self, id: &str) -> bool {
self.off_side.get(id).copied().unwrap_or(false)
}
/// `foldingRules.markers` of the language configuration.
pub fn folding_markers(&self, id: &str) -> Option<Arc<FoldingMarkers>> {
self.folding_markers.get(id).cloned()
}
/// `comments.blockComment` start and end tokens of the language configuration.
pub fn block_comment(&self, id: &str) -> Option<(&str, &str)> {
self.block_comments.get(id).map(|(start, end)| (start.as_str(), end.as_str()))
}
/// The onEnter, indentation and electric character rules of the language configuration.
pub fn rules(&self, id: &str) -> Option<&LanguageRules> {
self.rules.get(id)
}
/// `getLanguageConfiguration(id).comments`.
pub fn comments(&self, id: &str) -> Comments<'_> {
let line = self.line_comments.get(id);
Comments { line: line.map(|(token, _)| token.as_str()), line_no_indent: line.is_some_and(|(_, no_indent)| *no_indent), block: self.block_comment(id) }
}
}
/// languagesAssociations.ts matches against the URI's path, lowercased: slashes on Windows too.
fn resource_path(path: &Path) -> String {
let path = path.to_string_lossy().to_lowercase();
if cfg!(windows) { path.replace('\\', "/") } else { path }
}
/// languageService.ts `isValidLanguageExtensionPoint`: why the contributed language is rejected.
fn language_reject(language: &Value) -> Option<String> {
if !crate::contextkey::truthy(Some(language)) {
return Some("Empty value for `contributes.languages`".into());
}
if !language["id"].is_string() {
return Some("property `id` is mandatory and must be of type `string`".into());
}
let optional = |key: &str, valid: fn(&Value) -> bool| language.get(key).is_none_or(valid);
let string_array = |value: &Value| value.as_array().is_some_and(|items| items.iter().all(Value::is_string));
for (key, valid, kind) in [("extensions", string_array as fn(&Value) -> bool, "string[]"), ("filenames", string_array, "string[]"), ("firstLine", Value::is_string, "string"), ("configuration", Value::is_string, "string"), ("aliases", string_array, "string[]"), ("mimetypes", string_array, "string[]")] {
if !optional(key, valid) {
return Some(format!("property `{key}` can be omitted and must be of type `{kind}`"));
}
}
if !optional("icon", |icon| icon["light"].is_string() && icon["dark"].is_string()) {
return Some("property `icon` can be omitted and must be of type `object` with properties `light` and `dark` of type `string`".into());
}
None
}
/// languageConfigurationExtensionPoint.ts `_parseRegex`: a pattern string, or `{ pattern, flags }`.
pub(crate) fn marker_pattern(value: &Value) -> Option<(&str, &str)> {
match value {
Value::String(pattern) => Some((pattern, "")),
Value::Object(object) => Some((object.get("pattern")?.as_str()?, object.get("flags").and_then(Value::as_str).unwrap_or(""))),
_ => None,
}
}
/// `$setLanguageConfiguration`'s revival into the language-configuration.json shape `configure` reads: the
/// regexes stay `{ pattern, flags }`, an onEnter action's `indentAction` enum becomes `indent`, and
/// `__characterPairSupport` stands in for missing `autoClosingPairs`.
fn configuration_of_dto(dto: &Value) -> Value {
let mut config = serde_json::json!({
"comments": dto["comments"],
"brackets": dto["brackets"],
"wordPattern": dto["wordPattern"],
"indentationRules": dto["indentationRules"],
"autoClosingPairs": if dto["autoClosingPairs"].is_null() { &dto["__characterPairSupport"]["autoClosingPairs"] } else { &dto["autoClosingPairs"] },
});
if let Some(rules) = dto["onEnterRules"].as_array() {
let mut on_enter_rules = Vec::new();
for rule in rules {
let mut rule = rule.clone();
// languageConfiguration.ts `IndentAction`: None, Indent, IndentOutdent, Outdent.
let indent = ["none", "indent", "indentOutdent", "outdent"].get(rule["action"]["indentAction"].as_u64().unwrap_or(u64::MAX) as usize);
rule["action"]["indent"] = indent.map_or(Value::Null, |indent| Value::from(*indent));
on_enter_rules.push(rule);
}
config["onEnterRules"] = Value::Array(on_enter_rules);
}
config
}
/// languagesAssociations.ts parses `filepattern` with `{ ignoreCase: true }`.
const IGNORE_CASE: glob::Options = glob::Options { trim_for_exclusions: false, ignore_case: true };
#[cfg(test)]
mod tests {
use super::*;
/// languageConfigurationRegistry.ts `combineLanguageConfigurations`: an extension's configuration replaces only
/// the keys it sets, the latest registration wins, and disposing one goes back to what remains.
#[test]
fn extension_configurations_combine_key_by_key_over_the_file() {
let mut languages = Languages::new(&[]);
let file = serde_json::json!({ "comments": { "lineComment": "#" }, "folding": { "offSide": true } });
languages.configure(PLAINTEXT, &file);
languages.file_configurations.insert(PLAINTEXT.into(), file);
let line = |languages: &Languages| languages.comments(PLAINTEXT).line.map(str::to_owned);
assert!(languages.set_extension_configuration(1, PLAINTEXT, &serde_json::json!({ "comments": { "lineComment": "//" } })));
assert!(languages.set_extension_configuration(2, PLAINTEXT, &serde_json::json!({ "comments": { "lineComment": "--" }, "brackets": null })));
assert_eq!((line(&languages), languages.off_side(PLAINTEXT)), (Some("--".into()), true));
assert_eq!(languages.remove_extension_configuration(2).as_deref(), Some(PLAINTEXT));
assert_eq!(line(&languages).as_deref(), Some("//"));
languages.remove_extension_configuration(1);
assert_eq!(line(&languages).as_deref(), Some("#"));
assert_eq!(languages.remove_extension_configuration(1), None);
}
/// languageService.ts `languagesExtPoint.setHandler`: an invalid contribution is an error message of the extension,
/// and its language stays unregistered.
#[test]
fn invalid_contributed_languages_are_extension_messages() {
let extension = |id: &str, languages: Value| ScannedExtension { id: id.into(), location: "/x".into(), description: serde_json::json!({ "contributes": { "languages": languages } }) };
let extensions = [extension("test.languages-object", serde_json::json!({ "id": "a" })), extension("test.languages-invalid", serde_json::json!([{ "id": "b", "extensions": ".b" }, { "id": "c", "icon": "c.svg" }, { "id": "d" }]))];
let languages = Languages::new(&extensions);
assert!(languages.ids.iter().any(|id| id == "d") && !languages.ids.iter().any(|id| ["a", "b", "c"].contains(&id.as_str())));
let messages = |id: &str| crate::perf::messages(id).into_iter().map(|(_, message)| message).collect::<Vec<_>>();
assert_eq!(messages("test.languages-object"), ["Invalid `contributes.languages`. Expected an array."]);
assert_eq!(messages("test.languages-invalid"), ["property `extensions` can be omitted and must be of type `string[]`", "property `icon` can be omitted and must be of type `object` with properties `light` and `dark` of type `string`"]);
}
/// textMateTokenizationFeatureImpl.ts `validateGrammarExtensionPoint`: an invalid grammar is an error message of the
/// extension and stays unregistered; one outside the extension's folder is a warning and registers.
#[test]
fn invalid_grammars_are_extension_messages() {
let grammars = serde_json::json!([
{ "language": "unknown", "scopeName": "source.a", "path": "a.json" },
{ "language": 1, "scopeName": "source.a", "path": "a.json" },
{ "scopeName": "", "path": "a.json" },
{ "scopeName": "source.b", "path": 2 },
{ "scopeName": "source.b", "path": "b.json", "injectTo": ["source.x", 3] },
{ "scopeName": "source.b", "path": "b.json", "embeddedLanguages": ["x"] },
{ "scopeName": "source.b", "path": "b.json", "tokenTypes": "string" },
{ "language": "g", "scopeName": "source.g", "path": "../g.json" },
]);
let extension = ScannedExtension { id: "test.grammars-invalid".into(), location: "/x/ext".into(), description: serde_json::json!({ "contributes": { "languages": [{ "id": "g" }], "grammars": grammars } }) };
let languages = Languages::new(&[extension]);
assert_eq!(languages.grammars.scope_name("g"), Some("source.g"));
let messages = crate::perf::messages("test.grammars-invalid").into_iter().map(|(_, message)| message).collect::<Vec<_>>();
assert_eq!(
messages,
[
"Unknown language in `contributes.grammars.language`. Provided value: unknown",
"Unknown language in `contributes.grammars.language`. Provided value: 1",
"Expected string in `contributes.grammars.scopeName`. Provided value: ",
"Expected string in `contributes.grammars.path`. Provided value: 2",
"Invalid value in `contributes.grammars.injectTo`. Must be an array of language scope names. Provided value: [\"source.x\",3]",
"Invalid value in `contributes.grammars.embeddedLanguages`. Must be an object map from scope name to language. Provided value: [\"x\"]",
"Invalid value in `contributes.grammars.tokenTypes`. Must be an object map from scope name to token type. Provided value: \"string\"",
"Expected `contributes.grammars.path` (/x/g.json) to be included inside extension's folder (/x/ext). This might make the extension non-portable.",
]
);
}
#[test]
fn detects_languages_like_the_reference() {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
let languages = Languages::new(&extensions);
let cases = [
("/w/notes.txt", "plaintext"),
("/w/README.md", "markdown"),
("/w/src/main.ts", "typescript"),
("/w/SRC/MAIN.TS", "typescript"),
("/w/DOCKERFILE", "dockerfile"),
("/w/package.json", "json"),
("/w/tsconfig.json", "jsonc"),
("/w/tsconfig.base.json", "jsonc"),
("/w/Dockerfile", "dockerfile"),
("/w/Dockerfile.dev", "dockerfile"),
("/w/.git/config", "properties"),
("/w/no-extension", "plaintext"),
];
for (path, id) in cases {
assert_eq!(languages.language_of(Path::new(path), ""), id, "{path}");
}
let first_lines = [
("/w/run", "#!/usr/bin/env python3", "python"),
("/w/run", "#!/bin/bash -e", "shellscript"),
("/w/run", "#!/usr/bin/env node", "javascript"),
("/w/run", "#!/usr/bin/env -S deno run", "typescript"),
("/w/run", "\u{FEFF}<?xml version=\"1.0\"?>", "xml"),
("/w/run", "my class Foo {}", "raku"),
("/w/run", "hello", "plaintext"),
("/w/notes.txt", "#!/bin/bash", "plaintext"),
];
for (path, first_line, id) in first_lines {
assert_eq!(languages.language_of(Path::new(path), first_line), id, "{first_line}");
}
assert_eq!(languages.name("plaintext"), "Plain Text");
assert_eq!(languages.name("typescript"), "TypeScript");
assert!(languages.off_side("python"));
assert!(!languages.off_side("typescript"));
let css = languages.folding_markers("css").expect("css has #region markers");
assert_eq!(css.classify("/* #region Colors */"), (true, false));
assert_eq!(css.classify(" /* #endregion */"), (false, true));
assert!(languages.folding_markers("plaintext").is_none());
assert_eq!(languages.block_comment("python"), Some(("\"\"\"", "\"\"\"")));
assert_eq!(languages.comments("typescript"), Comments { line: Some("//"), line_no_indent: false, block: Some(("/*", "*/")) });
assert_eq!(languages.comments("plaintext"), Comments::default());
}
#[test]
fn file_patterns_take_the_whole_glob_dialect() {
let associations = serde_json::json!({ "*docker*compose*.yml": "dockercompose", "**/user/snippets/*.json": "snippets", "build.{gradle,kts}": "groovy", "data?.[ct]sv": "csv" });
let language = |path: &str| Languages::configured_language(&associations, Path::new(path));
assert_eq!(language("/w/my-docker-compose.yml").as_deref(), Some("dockercompose"));
assert_eq!(language("/x/user/snippets/a.json").as_deref(), Some("snippets"));
assert_eq!(language("/x/user/snippets/a/b.json"), None);
assert_eq!(language("/w/Build.KTS").as_deref(), Some("groovy"));
assert_eq!(language("/w/data1.tsv").as_deref(), Some("csv"));
assert_eq!(language("/w/data12.tsv"), None);
}
}