Visual Studio Code, rebuilt in Rust
Rust
//! The collector messages of the extension points whose workbench handler only validates: the port has no other
//! use for their values in the window, or reads them elsewhere.
use std::path::{Path, PathBuf};
use exthost::scan::ScannedExtension;
use serde_json::Value;
use crate::contextkey::truthy;
use crate::notifications::Severity;
/// Reports every point's messages for the running extensions.
pub fn report(extensions: &[ScannedExtension]) {
json_validation(extensions);
json_validation_registry(extensions);
colors(extensions);
icons(extensions);
semantic_token_types_and_modifiers(extensions, "semanticTokenTypes", "semanticTokenType");
semantic_token_types_and_modifiers(extensions, "semanticTokenModifiers", "semanticTokenModifier");
semantic_token_scopes(extensions);
notebooks(extensions);
}
/// notebookServiceImpl.ts: the `notebooks` handler of `_setupHandler` (the first contribution of a type wins), and
/// the `notebookRenderer` and `notebookPreload` handlers, the latter only with the `contribNotebookStaticPreloads` proposal.
fn notebooks(extensions: &[ScannedExtension]) {
let mut types = Vec::new();
for extension in extensions {
let report = |message: String| crate::perf::extension_point_message(&extension.id, Severity::Error, message);
let contributes = &extension.description["contributes"];
for notebook in contributes["notebooks"].as_array().into_iter().flatten() {
if !truthy(notebook.get("type")) {
report("Notebook does not specify type-property".into());
continue;
}
let view_type = crate::contextkey::js_string(notebook.get("type"));
if types.contains(&view_type) {
report(format!("Notebook type '{view_type}' already used"));
continue;
}
types.push(view_type);
}
for renderer in contributes["notebookRenderer"].as_array().into_iter().flatten() {
if !truthy(renderer.get("entrypoint")) {
report("Notebook renderer does not specify entry point".into());
} else if !truthy(renderer.get("id")) {
report("Notebook renderer does not specify id-property".into());
}
}
if !extension.description["enabledApiProposals"].as_array().is_some_and(|proposals| proposals.iter().any(|proposal| proposal == "contribNotebookStaticPreloads")) {
continue;
}
for preload in contributes["notebookPreload"].as_array().into_iter().flatten() {
if !truthy(preload.get("entrypoint")) {
report("Notebook preload does not specify entry point".into());
} else if !truthy(preload.get("type")) {
report("Notebook preload does not specify type-property".into());
}
}
}
}
/// tokenClassificationExtensionPoint.ts `tokenTypeExtPoint` and `tokenModifierExtPoint` handlers with `validateTypeOrModifier`.
fn semantic_token_types_and_modifiers(extensions: &[ScannedExtension], point: &str, name: &str) {
let id_pattern = regex::Regex::new("^[A-Za-z0-9_]+[-_A-Za-z0-9_+]*$").expect("valid");
for extension in extensions {
let Some(value) = extension.description["contributes"].get(point) else { continue };
let report = |message: String| crate::perf::extension_point_message(&extension.id, Severity::Error, message);
let Some(contributions) = value.as_array() else {
return report(format!("'configuration.{name}' must be an array"));
};
for contribution in contributions {
let Some(id) = contribution["id"].as_str().filter(|id| !id.is_empty()) else {
report(format!("'configuration.{name}.id' must be defined and can not be empty"));
continue;
};
if !id_pattern.is_match(id) {
report(format!("'configuration.{name}.id' must follow the pattern letterOrDigit[-_letterOrDigit]*"));
continue;
}
if contribution["superType"].as_str().is_some_and(|super_type| !super_type.is_empty() && !id_pattern.is_match(super_type)) {
report(format!("'configuration.{name}.superType' must follow the pattern letterOrDigit[-_letterOrDigit]*"));
continue;
}
if !contribution["description"].is_string() {
report(format!("'configuration.{name}.description' must be defined and can not be empty"));
}
}
}
}
/// tokenClassificationExtensionPoint.ts `tokenStyleDefaultsExtPoint` handler. Its selector message is unreachable:
/// `parseTokenSelector` does not throw.
fn semantic_token_scopes(extensions: &[ScannedExtension]) {
for extension in extensions {
let Some(value) = extension.description["contributes"].get("semanticTokenScopes") else { continue };
let report = |message: &str| crate::perf::extension_point_message(&extension.id, Severity::Error, message.into());
let Some(contributions) = value.as_array() else {
return report("'configuration.semanticTokenScopes' must be an array");
};
for contribution in contributions {
let language = &contribution["language"];
if truthy(Some(language)) && !language.is_string() {
report("'configuration.semanticTokenScopes.language' must be a string");
continue;
}
let scopes: Vec<&Value> = match &contribution["scopes"] {
Value::Object(map) => map.values().collect(),
Value::Array(items) => items.iter().collect(),
_ => {
report("'configuration.semanticTokenScopes.scopes' must be defined as an object");
continue;
}
};
for tm_scopes in scopes {
if !tm_scopes.as_array().is_some_and(|scopes| scopes.iter().all(Value::is_string)) {
report("'configuration.semanticTokenScopes.scopes' values must be an array of strings");
}
}
}
}
}
/// colorExtensionPoint.ts handler; its `return`s end the handler, not the contribution.
fn colors(extensions: &[ScannedExtension]) {
let id_pattern = regex::Regex::new(r"^[A-Za-z0-9_]+[.A-Za-z0-9_+]*$").expect("valid");
for extension in extensions {
let Some(value) = extension.description["contributes"].get("colors") else { continue };
let report = |message: &str| crate::perf::extension_point_message(&extension.id, Severity::Error, message.into());
let Some(contributions) = value.as_array() else {
return report("'configuration.colors' must be a array");
};
for contribution in contributions {
let Some(id) = contribution["id"].as_str().filter(|id| !id.is_empty()) else {
return report("'configuration.colors.id' must be defined and can not be empty");
};
if !id_pattern.is_match(id) {
return report("'configuration.colors.id' must only contain letters, digits and dots and can not start with a dot");
}
if !contribution["description"].is_string() {
return report("'configuration.colors.description' must be defined and can not be empty");
}
let defaults = &contribution["defaults"];
let (Some(light), Some(dark)) = (defaults["light"].as_str(), defaults["dark"].as_str()) else {
return report("'configuration.colors.defaults' must be defined and must contain 'light' and 'dark'");
};
for (key, name) in [("highContrast", "configuration.colors.defaults.highContrast"), ("highContrastLight", "configuration.colors.defaults.highContrastLight")] {
if truthy(Some(&defaults[key])) && !defaults[key].is_string() {
return report(&format!("If defined, '{name}' must be a string."));
}
}
let high_contrast = defaults["highContrast"].as_str().unwrap_or(dark);
let high_contrast_light = defaults["highContrastLight"].as_str().unwrap_or(light);
for (value, name) in [(light, "light"), (dark, "dark"), (high_contrast, "highContrast"), (high_contrast_light, "highContrastLight")] {
if value.is_empty() {
report(&format!("configuration.colors.defaults.{name} must be either a color value in hex (#RRGGBB[AA] or #RGB[A]) or the identifier of a themable color which provides the default."));
}
}
}
}
}
/// iconExtensionPoint.ts handler; its `return`s end the handler, not the contribution.
fn icons(extensions: &[ScannedExtension]) {
let id_pattern = regex::Regex::new("^[A-Za-z0-9]+(-[A-Za-z0-9]+)+$").expect("valid");
for extension in extensions {
let Some(value) = extension.description["contributes"].get("icons") else { continue };
let report = |severity, message: String| crate::perf::extension_point_message(&extension.id, severity, message);
// `for (const id in value)`: an array's keys are its indexes.
let contributions: Vec<(String, &Value)> = match value {
Value::Object(map) => map.iter().map(|(id, contribution)| (id.clone(), contribution)).collect(),
Value::Array(items) => items.iter().enumerate().map(|(index, contribution)| (index.to_string(), contribution)).collect(),
_ => return report(Severity::Error, "'configuration.icons' must be an object with the icon names as properties.".into()),
};
for (id, contribution) in contributions {
if !id_pattern.is_match(&id) {
return report(Severity::Error, "'configuration.icons' keys represent the icon id and can only contain letter, digits and minuses. They need to consist of at least two segments in the form `component-iconname`.".into());
}
if contribution["description"].as_str().is_none_or(str::is_empty) {
return report(Severity::Error, "'configuration.icons.description' must be defined and can not be empty".into());
}
let default = &contribution["default"];
if default.is_string() {
continue;
}
let (Some(font_path), true) = (default["fontPath"].as_str(), default["fontCharacter"].is_string()) else {
report(Severity::Error, "'configuration.icons.default' must be either a reference to the id of an other theme icon (string) or a icon definition (object) with properties `fontPath` and `fontCharacter`.".into());
continue;
};
let file_extension = Path::new(font_path).extension().map_or(String::new(), |extension| extension.to_string_lossy().into_owned());
if !["ttf", "woff", "woff2"].contains(&file_extension.as_str()) {
return report(Severity::Warning, format!("Expected `contributes.icons.default.fontPath` to have file extension 'woff', woff2' or 'ttf', is '{file_extension}'."));
}
let location = join_path(&extension.location, font_path);
if !location.starts_with(&extension.location) {
// Upstream's message uses `{0}` twice, so the font path stands in for the extension's folder.
return report(Severity::Warning, format!("Expected `contributes.icons.default.fontPath` ({0}) to be included inside extension's folder ({0}).", uri_path(&location)));
}
}
}
}
/// jsonValidationExtensionPoint.ts `configurationExtPoint` handler; a value that is not an array ends the handler.
fn json_validation(extensions: &[ScannedExtension]) {
for extension in extensions {
let Some(value) = extension.description["contributes"].get("jsonValidation") else { continue };
let report = |severity, message| crate::perf::extension_point_message(&extension.id, severity, message);
let Some(entries) = value.as_array() else {
report(Severity::Error, "'configuration.jsonValidation' must be a array".into());
return;
};
for entry in entries {
let file_match = &entry["fileMatch"];
if !file_match.is_string() && !file_match.as_array().is_some_and(|patterns| patterns.iter().all(Value::is_string)) {
report(Severity::Error, "'configuration.jsonValidation.fileMatch' must be defined as a string or an array of strings.".into());
continue;
}
let Some(url) = entry["url"].as_str() else {
report(Severity::Error, "'configuration.jsonValidation.url' must be a URL or relative path".into());
continue;
};
if url.starts_with("./") {
let location = join_path(&extension.location, url);
if !location.starts_with(&extension.location) {
report(Severity::Warning, outside_message("jsonValidation", &location, &extension.location));
}
} else if !has_scheme(url) {
report(Severity::Error, "'configuration.jsonValidation.url' must be an absolute URL or start with './' to reference schemas located in the extension.".into());
}
}
}
}
/// jsonValidationExtensionPoint.ts `registryExtPoint` handler.
fn json_validation_registry(extensions: &[ScannedExtension]) {
for extension in extensions {
let Some(value) = extension.description["contributes"].get("jsonValidationRegistry") else { continue };
let report = |severity, message| crate::perf::extension_point_message(&extension.id, severity, message);
let Some(catalogs) = value.as_array() else {
report(Severity::Error, "'configuration.jsonValidationRegistry' must be an array".into());
continue;
};
for catalog in catalogs {
let Some(url) = catalog["url"].as_str() else {
report(Severity::Error, "'configuration.jsonValidationRegistry.url' must be a URI or relative path".into());
continue;
};
if url.starts_with("./") {
let location = join_path(&extension.location, url);
if !location.starts_with(&extension.location) {
report(Severity::Warning, outside_message("jsonValidationRegistry", &location, &extension.location));
}
} else if !has_scheme(url) {
report(Severity::Error, "'configuration.jsonValidationRegistry.url' must be an absolute URI or start with './' to reference a registry located in the extension.".into());
}
}
}
}
fn outside_message(point: &str, location: &Path, extension_location: &Path) -> String {
let location = crate::editor_history::file_uri_string(location);
format!("Expected `contributes.{point}.url` ({location}) to be included inside extension's folder ({}). This might make the extension non-portable.", uri_path(extension_location))
}
/// A location as upstream's messages show `uri.path`: `/`-separated on Windows too.
pub fn uri_path(location: &Path) -> String {
crate::uri::Uri::file(&location.to_string_lossy()).path
}
/// `resources.joinPath`: the relative path's `.` and `..` segments resolved against the root.
pub fn join_path(root: &Path, relative: &str) -> PathBuf {
let mut location = root.to_path_buf();
for segment in relative.split('/') {
match segment {
"" | "." => {}
".." => {
location.pop();
}
segment => location.push(segment),
}
}
location
}
/// `/^[^:/?#]+:\/\//`.
fn has_scheme(url: &str) -> bool {
url.split_once("://").is_some_and(|(scheme, _)| !scheme.is_empty() && !scheme.contains([':', '/', '?', '#']))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn extension(id: &str, contributes: Value) -> ScannedExtension {
ScannedExtension { id: id.into(), location: "/ext/schemas".into(), description: json!({ "contributes": contributes }) }
}
#[test]
fn invalid_json_validation_is_an_extension_message() {
use Severity::{Error, Warning};
report(&[
extension("test.json-validation", json!({
"jsonValidation": [
{ "fileMatch": "a.json", "url": "./a.schema.json" },
{ "fileMatch": ["b.json", 2], "url": "./b.json" },
{ "fileMatch": "c.json" },
{ "fileMatch": "d.json", "url": "./../d.schema.json" },
{ "fileMatch": "e.json", "url": "e.schema.json" },
{ "fileMatch": "f.json", "url": "https://example.com/f.json" },
],
"jsonValidationRegistry": [{ "url": "catalog.json" }, null, { "url": "./../c d.json" }],
})),
extension("test.json-validation-2", json!({ "jsonValidation": {} })),
extension("test.json-validation-3", json!({ "jsonValidation": "x", "jsonValidationRegistry": {} })),
]);
let expected = |messages: &[(Severity, &str)]| messages.iter().map(|(severity, message)| (*severity, message.to_string())).collect::<Vec<_>>();
assert_eq!(crate::perf::messages("test.json-validation"), expected(&[
(Error, "'configuration.jsonValidation.fileMatch' must be defined as a string or an array of strings."),
(Error, "'configuration.jsonValidation.url' must be a URL or relative path"),
(Warning, "Expected `contributes.jsonValidation.url` (file:///ext/d.schema.json) to be included inside extension's folder (/ext/schemas). This might make the extension non-portable."),
(Error, "'configuration.jsonValidation.url' must be an absolute URL or start with './' to reference schemas located in the extension."),
(Error, "'configuration.jsonValidationRegistry.url' must be an absolute URI or start with './' to reference a registry located in the extension."),
(Error, "'configuration.jsonValidationRegistry.url' must be a URI or relative path"),
(Warning, "Expected `contributes.jsonValidationRegistry.url` (file:///ext/c%20d.json) to be included inside extension's folder (/ext/schemas). This might make the extension non-portable."),
]));
assert_eq!(crate::perf::messages("test.json-validation-2"), expected(&[(Error, "'configuration.jsonValidation' must be a array")]));
assert_eq!(crate::perf::messages("test.json-validation-3"), expected(&[(Error, "'configuration.jsonValidationRegistry' must be an array")]), "the first array error ends the jsonValidation handler");
}
#[test]
fn invalid_colors_and_icons_are_extension_messages() {
let cases = [
("colors", json!({}), "'configuration.colors' must be a array"),
("colors", json!([{ "id": "" }]), "'configuration.colors.id' must be defined and can not be empty"),
("colors", json!([{ "id": ".a" }]), "'configuration.colors.id' must only contain letters, digits and dots and can not start with a dot"),
("colors", json!([{ "id": "a.b" }]), "'configuration.colors.description' must be defined and can not be empty"),
("colors", json!([{ "id": "a.b", "description": "d", "defaults": { "light": "#fff" } }]), "'configuration.colors.defaults' must be defined and must contain 'light' and 'dark'"),
("colors", json!([{ "id": "a.b", "description": "d", "defaults": { "light": "#fff", "dark": "#000", "highContrast": 1 } }]), "If defined, 'configuration.colors.defaults.highContrast' must be a string."),
("colors", json!([{ "id": "a.b", "description": "d", "defaults": { "light": "", "dark": "#000", "highContrastLight": "#fff" } }]), "configuration.colors.defaults.light must be either a color value in hex (#RRGGBB[AA] or #RGB[A]) or the identifier of a themable color which provides the default."),
("icons", json!("x"), "'configuration.icons' must be an object with the icon names as properties."),
("icons", json!({ "single": {} }), "'configuration.icons' keys represent the icon id and can only contain letter, digits and minuses. They need to consist of at least two segments in the form `component-iconname`."),
("icons", json!({ "my-icon": { "description": "" } }), "'configuration.icons.description' must be defined and can not be empty"),
("icons", json!({ "my-icon": { "description": "d", "default": { "fontPath": "f.ttf" } } }), "'configuration.icons.default' must be either a reference to the id of an other theme icon (string) or a icon definition (object) with properties `fontPath` and `fontCharacter`."),
("icons", json!({ "my-icon": { "description": "d", "default": { "fontPath": "f.otf", "fontCharacter": "\\E001" } } }), "Expected `contributes.icons.default.fontPath` to have file extension 'woff', woff2' or 'ttf', is 'otf'."),
("icons", json!({ "my-icon": { "description": "d", "default": { "fontPath": "../f.woff", "fontCharacter": "\\E001" } } }), "Expected `contributes.icons.default.fontPath` (/ext/f.woff) to be included inside extension's folder (/ext/f.woff)."),
];
for (index, (point, value, message)) in cases.into_iter().enumerate() {
let id = format!("test.theme-point-{index}");
report(&[extension(&id, json!({ point: value }))]);
let messages: Vec<String> = crate::perf::messages(&id).into_iter().map(|(_, message)| message).collect();
assert_eq!(messages, [message]);
}
report(&[extension("test.theme-point-first", json!({ "colors": {}, "icons": 1 })), extension("test.theme-point-later", json!({ "colors": {}, "icons": 1 }))]);
assert_eq!(crate::perf::messages("test.theme-point-first").len(), 2);
assert!(crate::perf::messages("test.theme-point-later").is_empty(), "a message ends the handler before the next extension");
report(&[extension("test.theme-point-valid", json!({
"colors": [{ "id": "my.color_1", "description": "d", "defaults": { "light": "#fff", "dark": "editor.background", "highContrast": null } }],
"icons": { "my-icon": { "description": "d", "default": "gear" }, "my-font-icon": { "description": "d", "default": { "fontPath": "./f.woff2", "fontCharacter": "\\E001" } } },
}))]);
assert!(crate::perf::messages("test.theme-point-valid").is_empty());
}
#[test]
fn invalid_semantic_token_contributions_are_extension_messages() {
report(&[extension("test.semantic-tokens", json!({
"semanticTokenTypes": [
{ "description": "d" },
{ "id": "bad.id", "description": "d" },
{ "id": "type", "superType": "bad super", "description": "d" },
{ "id": "type" },
{ "id": "good-type_1", "superType": "base", "description": "d" },
],
"semanticTokenModifiers": [{ "id": "", "description": "d" }],
"semanticTokenScopes": [
{ "language": 1, "scopes": {} },
{ "scopes": "x" },
{ "language": "rust", "scopes": { "type": ["a b"], "type.mod": "c", "other": [1] } },
],
}))]);
report(&[extension("test.semantic-tokens-2", json!({ "semanticTokenModifiers": {}, "semanticTokenScopes": null }))]);
let messages = |id| crate::perf::messages(id).into_iter().map(|(_, message)| message).collect::<Vec<_>>();
assert_eq!(messages("test.semantic-tokens"), [
"'configuration.semanticTokenType.id' must be defined and can not be empty",
"'configuration.semanticTokenType.id' must follow the pattern letterOrDigit[-_letterOrDigit]*",
"'configuration.semanticTokenType.superType' must follow the pattern letterOrDigit[-_letterOrDigit]*",
"'configuration.semanticTokenType.description' must be defined and can not be empty",
"'configuration.semanticTokenModifier.id' must be defined and can not be empty",
"'configuration.semanticTokenScopes.language' must be a string",
"'configuration.semanticTokenScopes.scopes' must be defined as an object",
"'configuration.semanticTokenScopes.scopes' values must be an array of strings",
]);
assert_eq!(messages("test.semantic-tokens-2"), [
"'configuration.semanticTokenModifier' must be an array",
"'configuration.semanticTokenScopes' must be an array",
]);
}
#[test]
fn invalid_notebook_contributions_are_extension_messages() {
let mut preloads = extension("test.notebook-preloads", json!({ "notebookPreload": [{ "type": "a" }, { "entrypoint": "p.js" }, { "entrypoint": "p.js", "type": "a" }] }));
preloads.description["enabledApiProposals"] = json!(["contribNotebookStaticPreloads"]);
report(&[
extension("test.notebooks-first", json!({ "notebooks": [{ "type": "nb" }] })),
extension("test.notebooks", json!({
"notebooks": [{ "displayName": "x" }, { "type": "" }, { "type": "nb" }, { "type": "other" }],
"notebookRenderer": [{ "id": "r" }, { "entrypoint": "r.js" }, { "entrypoint": { "path": "r.js" }, "id": "r" }],
"notebookPreload": [{ "type": "a" }],
})),
preloads,
]);
let messages = |id: &str| crate::perf::messages(id).into_iter().map(|(_, message)| message).collect::<Vec<_>>();
assert_eq!(messages("test.notebooks-first"), Vec::<String>::new());
assert_eq!(messages("test.notebooks"), [
"Notebook does not specify type-property",
"Notebook type 'nb' already used",
"Notebook renderer does not specify entry point",
"Notebook renderer does not specify id-property",
]);
assert_eq!(messages("test.notebook-preloads"), ["Notebook preload does not specify entry point", "Notebook preload does not specify type-property"]);
}
}