Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(extensions): report invalid grammar contributions

rokartur7351902e2aa8
diff --git a/native/crates/app/src/extension_point_messages.rs b/native/crates/app/src/extension_point_messages.rs
index 6f6df3d11ae..a4858664c3f 100644
--- a/native/crates/app/src/extension_point_messages.rs
+++ b/native/crates/app/src/extension_point_messages.rs
@@ -6,6 +6,7 @@ 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.
@@ -59,7 +60,7 @@ fn semantic_token_scopes(extensions: &[ScannedExtension]) {
};
for contribution in contributions {
let language = &contribution["language"];
- if is_truthy(language) && !language.is_string() {
+ if truthy(Some(language)) && !language.is_string() {
report("'configuration.semanticTokenScopes.language' must be a string");
continue;
}
@@ -104,7 +105,7 @@ fn colors(extensions: &[ScannedExtension]) {
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 is_truthy(&defaults[key]) && !defaults[key].is_string() {
+ if truthy(Some(&defaults[key])) && !defaults[key].is_string() {
return report(&format!("If defined, '{name}' must be a string."));
}
}
@@ -159,16 +160,6 @@ fn icons(extensions: &[ScannedExtension]) {
}
}
-pub fn is_truthy(value: &Value) -> bool {
- match value {
- Value::Null => false,
- Value::Bool(value) => *value,
- Value::Number(number) => number.as_f64().is_some_and(|number| number != 0.0),
- Value::String(text) => !text.is_empty(),
- Value::Array(_) | Value::Object(_) => true,
- }
-}
-
/// jsonValidationExtensionPoint.ts `configurationExtPoint` handler; a value that is not an array ends the handler.
fn json_validation(extensions: &[ScannedExtension]) {
for extension in extensions {
diff --git a/native/crates/app/src/languages.rs b/native/crates/app/src/languages.rs
index a0339da8e77..714f7e6ee02 100644
--- a/native/crates/app/src/languages.rs
+++ b/native/crates/app/src/languages.rs
@@ -59,8 +59,7 @@ pub struct Languages {
impl Languages {
pub fn new(extensions: &[ScannedExtension]) -> Self {
- let grammars = textmate::Registry::new(extensions.iter().map(|extension| (extension.location.as_path(), &extension.description)));
- 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, brackets: HashMap::new(), rules: HashMap::new(), file_configurations: HashMap::new(), api_configurations: Vec::new() };
+ 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);
@@ -78,9 +77,53 @@ impl Languages {
}
}
}
+ 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.", location.display(), extension_location.display())
+ }))
+ }
+
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<_>>();
@@ -446,6 +489,39 @@ mod tests {
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();
diff --git a/native/crates/app/src/tasks/problem_matcher.rs b/native/crates/app/src/tasks/problem_matcher.rs
index 9e563999503..9611f24d25c 100644
--- a/native/crates/app/src/tasks/problem_matcher.rs
+++ b/native/crates/app/src/tasks/problem_matcher.rs
@@ -8,7 +8,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
-use crate::extension_point_messages::is_truthy;
+use crate::contextkey::truthy;
use crate::notifications::Severity;
/// What `ProblemPatternParser` and `ProblemMatcherParser` report, in order.
@@ -183,7 +183,7 @@ impl Registry {
messages.push((Severity::Error, format!("Error: the pattern property {name} is not a valid pattern variable name.")));
None
}
- pattern if is_truthy(pattern) => parse_problem_pattern(pattern, messages),
+ pattern if truthy(Some(pattern)) => parse_problem_pattern(pattern, messages),
_ => None,
};
let severity = description["severity"].as_str().filter(|severity| !severity.is_empty()).map(|severity| {
@@ -481,7 +481,7 @@ fn parse_watching(description: &Value, messages: &mut Messages) -> Option<Watchi
if let (Some(begins), Some(ends)) = (old_begins, old_ends) {
return Some(Watching { active_on_start: false, begins: WatchingPattern { regexp: begins, file: 1 }, ends: WatchingPattern { regexp: ends, file: 1 } });
}
- let monitor = if is_truthy(&description["background"]) { &description["background"] } else { &description["watching"] };
+ let monitor = if truthy(Some(&description["background"])) { &description["background"] } else { &description["watching"] };
if monitor.is_null() {
return None;
}
diff --git a/native/crates/textmate/src/registry.rs b/native/crates/textmate/src/registry.rs
index 38ad9bde37e..d75e7afc56b 100644
--- a/native/crates/textmate/src/registry.rs
+++ b/native/crates/textmate/src/registry.rs
@@ -41,7 +41,8 @@ impl Registry {
registry
}
- fn register(&mut self, location: &Path, grammar: &Value) {
+ /// One `contributes.grammars` entry of the extension in `location`.
+ pub fn register(&mut self, location: &Path, grammar: &Value) {
let (Some(scope_name), Some(path)) = (grammar["scopeName"].as_str(), grammar["path"].as_str()) else { return };
let pairs = |key: &str| grammar[key].as_object().into_iter().flatten().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect::<Vec<_>>();
let embedded_languages = pairs("embeddedLanguages");
diff --git a/port/ledger.md b/port/ledger.md
index 9fc53722049..ecd10f7936e 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -482,7 +482,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| workbench/contrib/emergencyAlert | workbench contribution | | removed | | no AI or Microsoft services by decision (port/notes.md); API stays inert |
| workbench/contrib/emmet | workbench contribution | M13 | verified | | workbench/emmet.rs: Emmet: Expand Abbreviation (`emmet.expandAbbreviation` with the language at the cursor and the emmet parent mode of its grammar's scope, emmetAction.test.ts cases), Tab with `emmet.triggerExpansionOnTab`, the Edit menu entry: cargo test -p app emmet menubar |
| workbench/contrib/encryption | workbench contribution | M10 | n/a | | encryption.contribution.ts only migrates Linux `password-store` argv values to gnome-libsecret; the port runs on macOS and keeps secrets in the Keychain |
-| workbench/contrib/extensions | workbench contribution | M18 | ported | [3 L] snippet_completions.rs:121: the Runtime Status Messages list the `collector` messages of the snippets, keybindings, languages, statusBarItems, viewsWelcome, debuggers, menus, submenus, commands, views, viewsContainers, configuration, configurationDefaults, jsonValidation, jsonValidationRegistry, colors, icons, semanticTokenTypes, semanticTokenModifiers, semanticTokenScopes, problemPatterns and problemMatchers points only; those of grammars, notebooks and authentication are not ported | Extensions view, queries, details editor, enablement, updates, badge, Help: Start/Continue/Stop Extension Bisect (services/extensionManagement/browser/extensionBisect.ts: state in the application storage across reloads, bisect-disabled extensions as DisabledByEnvironment in the window and out of the host, the urgent sticky prompt, the default-checked Keep this extension disabled; Report Issue & Continue is out with the removed contrib/issue): cargo test -p app extension_bisect, bisect_finds_the_extension_and_keeps_it_disabled; cargo test -p app extension (extensionsViews.test.ts, extensionQuery.test.ts, extensionEnablementService.test.ts cases); Features tab tables and markdown of extensionFeaturesTab.ts and the registered renderers: cargo test -p app extension_features; Runtime Status Uncaught Errors from `$onExtensionRuntimeError` and Messages: cargo test -p app the_runtime_status_lists_uncaught_errors_and_messages, invalid_contributed, static_entries_need_the_proposal, group_needs_the_proposal, debuggers_merge_by_type_and_keep_the_built_in_values, skipped_menu_contributions_are_extension_messages, contributed_command_messages, invalid_views_and_view_containers_are_extension_messages, invalid_configuration_is_an_extension_message, invalid_json_validation_is_an_extension_message, invalid_colors_and_icons_are_extension_messages, invalid_semantic_token_contributions_are_extension_messages, invalid_problem_patterns_and_matchers_are_extension_messages; ui-pair port/fixtures/extensions/ui-view.json (view, search, details) against the reference |
+| workbench/contrib/extensions | workbench contribution | M18 | ported | [3 L] snippet_completions.rs:121: the Runtime Status Messages list the `collector` messages of the snippets, keybindings, languages, statusBarItems, viewsWelcome, debuggers, menus, submenus, commands, views, viewsContainers, configuration, configurationDefaults, jsonValidation, jsonValidationRegistry, colors, icons, semanticTokenTypes, semanticTokenModifiers, semanticTokenScopes, problemPatterns, problemMatchers and grammars points only; those of notebooks and authentication are not ported | Extensions view, queries, details editor, enablement, updates, badge, Help: Start/Continue/Stop Extension Bisect (services/extensionManagement/browser/extensionBisect.ts: state in the application storage across reloads, bisect-disabled extensions as DisabledByEnvironment in the window and out of the host, the urgent sticky prompt, the default-checked Keep this extension disabled; Report Issue & Continue is out with the removed contrib/issue): cargo test -p app extension_bisect, bisect_finds_the_extension_and_keeps_it_disabled; cargo test -p app extension (extensionsViews.test.ts, extensionQuery.test.ts, extensionEnablementService.test.ts cases); Features tab tables and markdown of extensionFeaturesTab.ts and the registered renderers: cargo test -p app extension_features; Runtime Status Uncaught Errors from `$onExtensionRuntimeError` and Messages: cargo test -p app the_runtime_status_lists_uncaught_errors_and_messages, invalid_contributed, static_entries_need_the_proposal, group_needs_the_proposal, debuggers_merge_by_type_and_keep_the_built_in_values, skipped_menu_contributions_are_extension_messages, contributed_command_messages, invalid_views_and_view_containers_are_extension_messages, invalid_configuration_is_an_extension_message, invalid_json_validation_is_an_extension_message, invalid_colors_and_icons_are_extension_messages, invalid_semantic_token_contributions_are_extension_messages, invalid_problem_patterns_and_matchers_are_extension_messages, invalid_grammars_are_extension_messages; ui-pair port/fixtures/extensions/ui-view.json (view, search, details) against the reference |
| workbench/contrib/externalTerminal | workbench contribution | M15 | verified | | workbench/external_terminal.rs: Open New External Terminal (`workbench.action.terminal.openNativeConsole`, cmd+shift+c), with several workspace folders after the Select workspace folder pick (cargo test -p app open_native_console_picks_a_folder_in_a_multi_root_workspace); cargo test -p app external_terminal; ui-pair (port/results/terminal.md) |
| workbench/contrib/externalUriOpener | workbench contribution | M12 | verified | | workbench/opener.rs: externalUriOpenerService.ts getRequestedOpener (workbench.externalUriOpeners globs), chooseOpener, "How would you like to open: {0}" picker; no Simple Browser (out of scope); verified at port-m12b-verify: cargo test -p app opener 4/4; Simple Browser is out of scope by decision |
| workbench/contrib/files | workbench contribution | M12 | ported | [3 M] Files m12: non-file workspace folders | Cmd+V pastes the files another app copied after explorer.confirmPasteNative (explorerView.ts paste listener, fileActions.ts `pasteFileHandler`: cargo test -p app cmd_v_pastes_the_files_finder_copied); Dragged workspace roots reorder before or after a root by the pointer's half, or to the end, with the list.dropBetweenBackground line (explorerViewer.ts `doHandleRootDrop`: cargo test -p app dragging_a_root_reorders_the_workspace_folders; ui-pair dragShot of a three-root workspace, line over a root and below the rows matches); Compact folders off while optimized for a screen reader (explorerView.ts `isCompressionEnabled`: cargo test -p app compacts_single_child_folders_into_one_row); A workspace root that fails to resolve: the single folder's file item of its own resource, the "!" decoration in `list.invalidItemForeground` with "Unable to resolve workspace folder (...)" (explorerViewer.ts `getChildren`, explorerDecorationsProvider.ts: cargo test -p app a_workspace_root_that_fails_to_resolve_is_decorated_with_its_error; ui-pair of a two-root workspace with a missing folder, row and hover match); a copy soft-reverts the target's dirty model, which shows the copied file (workingCopyFileService.ts `doMoveOrCopy`: cargo test -p app a_copy_onto_a_dirty_model_reverts_it_to_the_copied_file); An unreadable folder expands to no children without an error (fileService.ts `toFileStat`: cargo test -p app an_unreadable_folder_expands_to_no_children); Explorer tree read from disk (explorer.rs): folders first, default excludes, click to expand, click opens a file as preview, double click pins, selection follows the active editor; Seti file icons and compareFileNamesDefault sort; workspace folders as roots, first five expanded (cargo test -p app); new file and folder, rename, delete, copy, cut, paste, drag and drop and undo through the working copy file operations (cargo test -p app explorer_actions, file_actions); "Do not ask me again" as the NSAlert suppression checkbox (dialog.rs); the context menu with the items whose commands the port has (port/results/contextmenu.md); tree view state in workspace storage (cargo test -p app view_state); file nesting with the explorerFileNestingTrie.test.ts cases (cargo test -p app nest); copyFilePath, copyRelativeFilePath and revealFileInOS (cargo test -p app copy_path, copied_path_labels); compact folders (cargo test -p app compact, get_context, compressed_navigation); Explorer find (cargo test -p app explorer_find find_filters); Finder drops through ExternalFileImport (cargo test -p app files_dropped_from_finder); explorer.sortOrder and sortOrderLexicographicOptions; explorer.autoReveal; list keyboard commands; the view title actions on hover or focus, revealInExplorer, showActiveFileInExplorer and the other file actions (cargo test -p app view_title_and_file_actions); workbench.action.files.newFile and showOpenedFileInNewWindow (cargo test -p app new_file_creates); Add Folder to Workspace and removeRootFolder (workbench/workspace_editing.rs, ui-pair port/fixtures/ui-pair/m12/workspace-folders.json); the compare commands compareFiles, selectForCompare, compareSelected, compareFileWith, compareWithSaved, compareWithClipboard, compareNewUntitledTextFiles (workbench/file_compare.rs: cargo test -p app file_compare); compare with saved by its chord: ui-pair port/fixtures/ui-pair/m12/compare-saved.json (the modified side has its own editor and cursor, at the first change: cargo test -p app file_compare; left the breadcrumbs editor type picker); Find in Folder..., Open in Integrated/External Terminal (cargo test -p app explorer_actions; ui-pair m12/find-in-folder.json and m12/folder-terminal.json), high contrast list outline (icons.json hc matches); rename, delete, new file and drag and drop with its move confirmation: ui-pair m12/explorer-ops.json matches; `<view id>.focus` of the Explorer panes (cargo test -p app focus_view_commands); the editor placeholders: binary, too large, not found and read errors with their actions (cargo test -p app files_that_do_not_resolve; ui-pair m12/editor-placeholders.json matches); the Open Editors view: pane size limits, group rows, unsaved badge, title actions, row close and dirty actions, drag to groups (cargo test -p app open_editors body_limits_clamp; ui-pair m12/open-editors.json); pinned (sticky) editors and scrolling tab bars, sticky shrink tabs in place with the `m…` label (cargo test -p app sticky pinned_editors tab_scroll; ui-pair m12/tab-scroll.json); Explorer indent guides at the reference x, row hover background, decoration badges at 11px 8px from the end, the Unpin Editor hover again after the tab menu closes (cargo test -p app tree_guides hover unpin_hover; ui-pair m12/explorer-guides.json and m12/pinned-tabs.json match). Differences left (port/notes.md milestone 12, session m12-files-done): a long tooltip breaks one path segment earlier (GPUI's line wrapper), the pin action loses its hover style after Cmd+W until the pointer moves (gpui keyboard modality), a shrink sticky tab with a badge and no room for its name; Open With... (`explorer.openWith`, `explorerResourceAvailableEditorIds`: cargo test -p app open_with_opens_the_resource the_context_menu_selects_the_row); Compare Active File With... from a file it opens itself: ui-pair m12/compare.json, the picker, the diff and the README.md menu match (port/notes.md session compare-fix); `explorerResourceReadonly` and `explorerResourceParentReadOnly` from `isReadonly` (cargo test -p app readonly_keys_follow_the_focused_item_and_its_parent); a failed create as an error notification with Retry, a dropped folder added to the workspace (cargo test -p app a_failed_create_offers a_folder_dropped_on_the_root) |