Visual Studio Code, rebuilt in Rust
Rust
//! `getCompressedContent` of base/common/jsonSchema.ts and the settings schemas of the JSON contribution registry
//! (platform/jsonschemas/common/jsonContributionRegistry.ts) that configurationRegistry.ts and
//! configurationService.ts `registerConfigurationSchemas` register.
use std::collections::HashMap;
use serde_json::{Map, Value, json};
use crate::model::is_override_key;
use crate::registry::{Registry, Scope};
/// The schemas the settings schemas `$ref`, as the reference serves them (compressed), dumped by port/tools/dump-settings
/// with its built-in extensions; `referenced_schema` adds the installed extensions' contributions.
pub const REFERENCED_SCHEMAS: [(&str, &str); 9] = [
("vscode://schemas/workbench-colors", include_str!("../schemas/workbench-colors.json")),
("vscode://schemas/token-styling", include_str!("../schemas/token-styling.json")),
("vscode://schemas/textmate-colors", include_str!("../schemas/textmate-colors.json")),
("vscode://schemas/size-customizations", include_str!("../schemas/size-customizations.json")),
("vscode://schemas/launch", include_str!("../schemas/launch.json")),
// extensionsRegistry.ts `schemaId`, the package.json schema extension-editing's jsonValidation names.
("vscode://schemas/vscode-extensions", include_str!("../schemas/vscode-extensions.json")),
// languageModelToolsParametersSchema.ts: the package.json schema's `languageModelTools` input schemas `$ref` it.
("vscode://schemas/toolsParameters", include_str!("../schemas/toolsParameters.json")),
// snippets.contribution.ts: configuration-editing's jsonValidation names them for snippets files.
("vscode://schemas/snippets", include_str!("../schemas/snippets.json")),
("vscode://schemas/global-snippets", include_str!("../schemas/global-snippets.json")),
];
/// The `REFERENCED_SCHEMAS` schema at `uri`. Its colors, token types and modifiers and debuggers include the ones
/// the registry's extensions contribute.
pub fn referenced_schema(registry: &Registry, uri: &str) -> Option<String> {
let content = REFERENCED_SCHEMAS.iter().find(|(id, _)| *id == uri)?.1;
let add_contributions = match uri {
"vscode://schemas/workbench-colors" => add_colors,
"vscode://schemas/token-styling" => add_token_types_and_modifiers,
"vscode://schemas/launch" => set_debuggers,
_ => return Some(content.to_owned()),
};
let mut schema: Value = serde_json::from_str(content).expect("a dumped schema is JSON");
let definitions = schema.as_object_mut().and_then(|schema| schema.shift_remove("$defs")).unwrap_or_default();
inline_definitions(&mut schema, &definitions);
add_contributions(&mut schema, registry);
Some(compressed_content(&schema))
}
/// Undoes `compressed_content`: each `#/$defs/` reference replaced by its definition.
fn inline_definitions(node: &mut Value, definitions: &Value) {
if let Some(name) = node.get("$ref").and_then(Value::as_str).and_then(|reference| reference.strip_prefix("#/$defs/")) {
*node = definitions[name].clone();
}
match node {
Value::Object(map) => map.values_mut().for_each(|value| inline_definitions(value, definitions)),
Value::Array(items) => items.iter_mut().for_each(|item| inline_definitions(item, definitions)),
_ => {}
}
}
/// colorExtensionPoint.ts: a contributed color the dump lacks is registered as colorUtils.ts `registerColor` does.
fn add_colors(schema: &mut Value, registry: &Registry) {
let default_color = schema["properties"]["editor.background"]["oneOf"][1].clone();
for color in ®istry.colors {
let (Some(id), Some(description)) = (color["id"].as_str(), color["description"].as_str()) else { continue };
if !matches_id(id, '.') || !color["defaults"].is_object() || !schema["properties"][id].is_null() {
continue;
}
// shortcut: the snippet shows the dark default when it is a hex color, not the active theme's color (the dumped
// colors show the reference's Dark Modern ones); upgrade when the schema follows the theme.
let hex = color["defaults"]["dark"].as_str().and_then(snippet_hex).unwrap_or_else(|| "#ff0000".to_owned());
schema["properties"][id] = json!({
"description": description,
"oneOf": [{ "type": "string", "format": "color-hex", "defaultSnippets": [{ "body": format!("${{1:{hex}}}") }] }, default_color],
});
}
}
/// color.ts `Color.Format.CSS.formatHexA(color, true)` of a `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` value.
fn snippet_hex(value: &str) -> Option<String> {
let digits = value.strip_prefix('#')?;
if !digits.chars().all(|digit| digit.is_ascii_hexdigit()) {
return None;
}
let mut hex = match digits.len() {
3 | 4 => digits.chars().flat_map(|digit| [digit, digit]).collect(),
6 | 8 => digits.to_owned(),
_ => return None,
};
hex.make_ascii_lowercase();
if hex.ends_with("ff") && hex.len() == 8 {
hex.truncate(6);
}
Some(format!("#{hex}"))
}
/// tokenClassificationExtensionPoint.ts: tokenClassificationRegistry.ts `registerTokenType` sets `<id>` and
/// `registerTokenModifier` sets `*.<id>` to `getStylingSchemeEntry`.
fn add_token_types_and_modifiers(schema: &mut Value, registry: &Registry) {
let selector_entry = schema["patternProperties"].as_object().and_then(|patterns| patterns.values().next()).cloned().expect("token-styling has a selector pattern");
let contributions = registry.semantic_token_types.iter().map(|token_type| (token_type, "")).chain(registry.semantic_token_modifiers.iter().map(|modifier| (modifier, "*.")));
for (contribution, prefix) in contributions {
let (Some(id), Some(description)) = (contribution["id"].as_str(), contribution["description"].as_str()) else { continue };
if !matches_id(id, '-') {
continue;
}
let mut entry = Map::from_iter([("description".to_owned(), json!(description))]);
entry.extend(selector_entry.as_object().expect("an entry is an object").clone());
schema["properties"][format!("{prefix}{id}")] = Value::Object(entry);
}
}
/// colorUtils.ts `colorIdPattern` (`^\w+[.\w+]*$`) with `.`, tokenClassificationRegistry.ts
/// `typeAndModifierIdPattern` (`^\w+[-_\w+]*$`) with `-`.
fn matches_id(id: &str, separator: char) -> bool {
let is_word = |character: char| character.is_ascii_alphanumeric() || character == '_';
id.starts_with(is_word) && id.chars().all(|character| is_word(character) || character == separator || character == '+')
}
/// debugAdapterManager.ts `updateDebugAdapterSchema` with debugger.ts `getSchemaAttributes` for each debugger.
// shortcut: a debugger whose `when` is false gets no "disabled" deprecationMessage; upgrade when the schema is
// rebuilt on context key changes.
fn set_debuggers(schema: &mut Value, registry: &Registry) {
let common = schema["definitions"]["common"].clone();
let common_properties: Vec<String> = common["properties"].as_object().map(|properties| properties.keys().cloned().collect()).unwrap_or_default();
let mut definitions = Map::from_iter([("common".to_owned(), common)]);
let mut one_of = Vec::new();
let mut snippets = Vec::new();
for debugger in ®istry.debuggers {
let contribution = &debugger.contribution;
for (request, attributes) in contribution["configurationAttributes"].as_object().into_iter().flatten() {
let Value::Object(mut attributes) = attributes.clone() else { continue };
let required = attributes.get("required").and_then(Value::as_array).cloned().unwrap_or_default();
attributes.insert("required".to_owned(), Value::Array([json!("name"), json!("type"), json!("request")].into_iter().chain(required).collect()));
attributes.insert("additionalProperties".to_owned(), json!(false));
attributes.insert("type".to_owned(), json!("object"));
let mut properties = attributes.get("properties").and_then(Value::as_object).cloned().unwrap_or_default();
let mut type_property = Map::from_iter([
("enum".to_owned(), json!([debugger.debug_type])),
("enumDescriptions".to_owned(), json!([debugger.label()])),
("description".to_owned(), json!("Type of configuration.")),
("pattern".to_owned(), json!("^(?!node2)")),
]);
if let Some(deprecated) = contribution["deprecated"].as_str().filter(|deprecated| !deprecated.is_empty()) {
type_property.insert("deprecationMessage".to_owned(), json!(deprecated));
}
type_property.insert("doNotSuggest".to_owned(), json!(contribution["deprecated"].as_str().is_some_and(|deprecated| !deprecated.is_empty())));
type_property.insert("errorMessage".to_owned(), json!("The debug type is not recognized. Make sure that you have a corresponding debug extension installed and that it is enabled."));
type_property.insert("patternErrorMessage".to_owned(), json!("\"node2\" is no longer supported, use \"node\" instead and set the \"protocol\" attribute to \"inspector\"."));
properties.insert("type".to_owned(), Value::Object(type_property));
properties.insert("request".to_owned(), json!({ "enum": [request], "description": "Request type of configuration. Can be \"launch\" or \"attach\"." }));
for name in &common_properties {
properties.insert(name.clone(), json!({ "$ref": format!("#/definitions/common/properties/{name}") }));
}
for property in properties.values_mut().filter_map(Value::as_object_mut) {
// configurationResolverUtils.ts `applyDeprecatedVariableMessage`.
property.entry("pattern").or_insert(json!("^(?!.*\\$\\{(env|config|command)\\.)"));
property.entry("patternErrorMessage").or_insert(json!("'env.', 'config.' and 'command.' are deprecated, use 'env:', 'config:' and 'command:' instead."));
}
let definition_id = format!("{}:{request}", debugger.debug_type);
let platform_definition_id = format!("{definition_id}:platform");
attributes.insert("properties".to_owned(), Value::Object(properties.clone()));
definitions.insert(definition_id, Value::Object(attributes.clone()));
let platform_properties: Map<String, Value> = properties.iter().filter(|(name, _)| !["type", "request", "name"].contains(&name.as_str())).map(|(name, value)| (name.clone(), value.clone())).collect();
definitions.insert(platform_definition_id.clone(), json!({ "type": "object", "additionalProperties": false, "properties": platform_properties }));
let platform_ref = format!("#/definitions/{platform_definition_id}");
properties.insert("windows".to_owned(), json!({ "$ref": platform_ref, "description": "Windows specific launch configuration attributes." }));
properties.insert("osx".to_owned(), json!({ "$ref": platform_ref, "description": "OS X specific launch configuration attributes." }));
properties.insert("linux".to_owned(), json!({ "$ref": platform_ref, "description": "Linux specific launch configuration attributes." }));
attributes.insert("properties".to_owned(), Value::Object(properties));
one_of.push(Value::Object(attributes));
}
snippets.extend(contribution["configurationSnippets"].as_array().into_iter().flatten().cloned());
}
schema["definitions"] = Value::Object(definitions);
let items = &mut schema["properties"]["configurations"]["items"];
items["oneOf"] = Value::Array(one_of);
items["defaultSnippets"] = Value::Array(snippets);
}
/// `getCompressedContent`: the schema as JSON with each subschema that occurs more than once, and is 30 characters or
/// longer, moved to `$defs` and replaced by a `$ref`. Subschemas are found by `traverseNodes`, and the first one
/// found, in its stack order, is the one kept.
pub fn compressed_content(schema: &Value) -> String {
let mut groups: Vec<Vec<String>> = Vec::new();
let mut group_by_text: HashMap<String, usize> = HashMap::new();
let mut group_of: HashMap<String, usize> = HashMap::new();
let mut has_dups = false;
let mut to_walk = vec![String::new()];
while let Some(pointer) = to_walk.pop() {
let node = schema.pointer(&pointer).expect("a walked pointer");
if !pointer.is_empty() {
let text = node.to_string();
if text.encode_utf16().count() >= 30 {
if let Some(&group) = group_by_text.get(&text) {
groups[group].push(pointer.clone());
group_of.insert(pointer, group);
has_dups = true;
continue;
}
group_by_text.insert(text, groups.len());
group_of.insert(pointer.clone(), groups.len());
groups.push(vec![pointer.clone()]);
}
}
collect_subschemas(node, &pointer, &mut to_walk);
}
if !has_dups {
return schema.to_string();
}
let mut def_node_name = "$defs".to_string();
while schema.get(&def_node_name).is_some() {
def_node_name.push('_');
}
let mut writer = Writer { schema, group_of: &group_of, groups: &groups, def_node_name: &def_node_name, ids: HashMap::new(), definitions: Vec::new() };
let mut out = String::new();
writer.write(&mut out, "", true);
let mut def_strings = Vec::new();
let mut index = 0;
while index < writer.definitions.len() {
let mut definition = format!("\"_{index}\":");
let pointer = writer.definitions[index].clone();
writer.write(&mut definition, &pointer, true);
def_strings.push(definition);
index += 1;
}
out.pop();
format!("{out},\"{def_node_name}\":{{{}}}}}", def_strings.join(","))
}
/// `traverseNodes`: the subschemas of `node` pushed in upstream's order, so the walk pops them last first.
fn collect_subschemas(node: &Value, pointer: &str, to_walk: &mut Vec<String>) {
let child = |key: &str| format!("{pointer}/{}", escape(key));
for key in ["additionalItems", "additionalProperties", "not", "contains", "propertyNames", "if", "then", "else", "unevaluatedItems", "unevaluatedProperties"] {
if node[key].is_object() {
to_walk.push(child(key));
}
}
for key in ["definitions", "$defs", "properties", "patternProperties", "dependencies", "dependentSchemas"] {
for (name, entry) in node[key].as_object().into_iter().flatten() {
if entry.is_object() {
to_walk.push(format!("{}/{}", child(key), escape(name)));
}
}
}
for key in ["anyOf", "allOf", "oneOf", "prefixItems", "items"] {
match &node[key] {
Value::Array(entries) => {
for (index, entry) in entries.iter().enumerate() {
if entry.is_object() {
to_walk.push(format!("{}/{index}", child(key)));
}
}
}
Value::Object(_) if key == "items" => to_walk.push(child(key)),
_ => {}
}
}
}
/// A JSON pointer reference token (RFC 6901).
fn escape(key: &str) -> String {
key.replace('~', "~0").replace('/', "~1")
}
/// The `stringify` of `getCompressedContent`: `JSON.stringify` with a replacer that turns a duplicated subschema into
/// a `$ref` to its definition, numbering definitions as it meets them.
struct Writer<'a> {
schema: &'a Value,
group_of: &'a HashMap<String, usize>,
groups: &'a [Vec<String>],
def_node_name: &'a str,
ids: HashMap<usize, usize>,
definitions: Vec<String>,
}
impl Writer<'_> {
fn write(&mut self, out: &mut String, pointer: &str, is_root: bool) {
if !is_root && let Some(&group) = self.group_of.get(pointer).filter(|&&group| self.groups[group].len() > 1) {
let id = match self.ids.get(&group) {
Some(&id) => id,
None => {
let id = self.definitions.len();
self.ids.insert(group, id);
self.definitions.push(self.groups[group][0].clone());
id
}
};
out.push_str(&format!("{{\"$ref\":\"#/{}/_{id}\"}}", self.def_node_name));
return;
}
match self.schema.pointer(pointer).expect("a written pointer") {
Value::Object(entries) => {
out.push('{');
for (index, key) in entries.keys().enumerate() {
if index > 0 {
out.push(',');
}
out.push_str(&Value::from(key.as_str()).to_string());
out.push(':');
self.write(out, &format!("{pointer}/{}", escape(key)), false);
}
out.push('}');
}
Value::Array(entries) => {
out.push('[');
for index in 0..entries.len() {
if index > 0 {
out.push(',');
}
self.write(out, &format!("{pointer}/{index}"), false);
}
out.push(']');
}
leaf => out.push_str(&leaf.to_string()),
}
}
}
pub const RESOURCE_LANGUAGE_SETTINGS_SCHEMA_ID: &str = "vscode://schemas/settings/resourceLanguage";
const OVERRIDE_PROPERTY_PATTERN: &str = r"^(\[([^\]]+)\])+$";
/// The settings schemas by id, as `registerConfigurationSchemas` and configurationRegistry.ts register them.
/// `in_workspace` is a multi-root workspace (`WorkbenchState.WORKSPACE`), whose folders take resource settings only.
// The port has no workspace trust, so `checkAndFilterPropertiesRequiringTrust` keeps every property.
pub const KEYBINDINGS_SCHEMA_ID: &str = "vscode://schemas/keybindings";
/// commands.ts `providerIdSchemaUri`, which the keybindings schema references for `providerId` args.
pub const INLINE_COMPLETION_PROVIDERS_SCHEMA_ID: &str = "vscode://schemas/inlineCompletionProviderIdArgs";
/// keybindingService.ts `KeybindingsJsonSchema.updateSchema`: the reference's schema for its core commands, dumped by
/// port/tools/dump-settings, with the extensions' commands added to the command names and
/// codeActionsContribution.ts `getKeybindingSchemaAdditions` built from the provided code action kinds.
pub fn keybindings_schema(registry: &Registry) -> Value {
let mut schema: Value = serde_json::from_str(include_str!("../schemas/keybindings.json")).expect("keybindings.json is JSON");
let definitions = &mut schema["definitions"];
for (id, title) in ®istry.extension_commands {
let names = definitions["commandNames"]["enum"].as_array_mut().expect("commandNames has an enum");
if id.starts_with('_') || names.iter().any(|name| name == id) {
continue;
}
names.push(json!(id));
if let Some(descriptions) = definitions["commandNames"]["enumDescriptions"].as_array_mut() {
descriptions.push(json!(title));
}
if let Some(removals) = definitions["commandType"]["anyOf"][1]["enum"].as_array_mut() {
removals.push(json!(format!("-{id}")));
}
}
let kind_commands = [("editor.action.codeAction", ""), ("editor.action.refactor", "refactor"), ("editor.action.sourceAction", "source")];
// The dump has no additions: the contribution reports its kinds once code action providers register.
let all_of = definitions["commandsSchemas"]["allOf"].as_array_mut().expect("commandsSchemas has allOf");
for (command, of_kind) in kind_commands {
let kinds: Vec<&String> = registry.code_action_kinds.iter().filter(|kind| of_kind.is_empty() || *kind == of_kind || kind.starts_with(&format!("{of_kind}."))).collect();
all_of.push(json!({
"if": { "required": ["command"], "properties": { "command": { "const": command } } },
"then": { "properties": { "args": { "required": ["kind"], "properties": { "kind": { "anyOf": [{ "enum": kinds }, { "type": "string" }] } } } } },
}));
}
schema
}
pub fn settings_schemas(registry: &Registry, in_workspace: bool) -> Vec<(&'static str, Value)> {
let language_override = json!({
"type": "object",
"description": "Configure editor settings to be overridden for a language.",
"errorMessage": "This setting does not support per-language configuration.",
"$ref": RESOURCE_LANGUAGE_SETTINGS_SCHEMA_ID,
});
let pattern_properties = json!({ OVERRIDE_PROPERTY_PATTERN: language_override });
let mut all = Map::new();
let mut by_scope: HashMap<Scope, Map<String, Value>> = HashMap::new();
let mut resource_language = Map::new();
for key in registry.keys() {
let property = registry.property(key).expect("a registered key");
if is_override_key(key) {
insert_language_override(&mut all, &mut by_scope, key, &language_override, property.default.clone());
continue;
}
let mut schema = property.schema.clone();
schema["default"] = property.default.clone();
all.insert(key.clone(), schema.clone());
if property.scope == Scope::LanguageOverridable {
resource_language.insert(key.clone(), schema.clone());
by_scope.entry(Scope::Resource).or_default().insert(key.clone(), schema);
} else {
by_scope.entry(property.scope).or_default().insert(key.clone(), schema);
}
}
for id in ®istry.override_identifiers {
let key = format!("[{id}]");
if !all.contains_key(&key) {
// `updatePropertyDefaultValue` without a configurationDefaults value: the default of type object.
insert_language_override(&mut all, &mut by_scope, &key, &language_override, json!({}));
}
}
let properties = |scopes: &[Scope]| {
let mut properties = Map::new();
for scope in scopes {
properties.extend(by_scope.get(scope).cloned().unwrap_or_default());
}
Value::Object(properties)
};
let settings_schema = |properties: Value| json!({ "properties": properties, "patternProperties": pattern_properties, "additionalProperties": true, "allowTrailingCommas": true, "allowComments": true });
let workspace = settings_schema(properties(&[Scope::MachineOverridable, Scope::Window, Scope::Resource]));
let folder = match in_workspace {
true => settings_schema(properties(&[Scope::MachineOverridable, Scope::Resource])),
false => workspace.clone(),
};
let default_properties = |properties: &Map<String, Value>| {
let mut defaults = Map::new();
for (key, schema) in properties {
// `Object.assign({ deprecationMessage: undefined }, schema)` moves a deprecation message first.
let mut ordered = Map::new();
if let Some(message) = schema.get("deprecationMessage") {
ordered.insert("deprecationMessage".into(), message.clone());
}
ordered.extend(schema.as_object().expect("a schema object").clone());
defaults.insert(key.clone(), Value::Object(ordered));
}
Value::Object(defaults)
};
let defaults_schema = json!({
"properties": default_properties(&all),
"patternProperties": default_properties(pattern_properties.as_object().expect("an object")),
"additionalProperties": true,
"allowTrailingCommas": true,
"allowComments": true,
});
let overridable = |scopes: &[Scope]| {
let mut properties = Map::new();
for scope in scopes {
for (key, schema) in by_scope.get(scope).into_iter().flatten() {
if schema["disallowConfigurationDefault"] != json!(true) {
properties.insert(key.clone(), schema.clone());
}
}
}
Value::Object(properties)
};
let config_defaults = json!({
"type": "object",
"description": "Contribute defaults for configurations",
"properties": overridable(&[Scope::MachineOverridable, Scope::Window, Scope::Resource]),
"patternProperties": { OVERRIDE_PROPERTY_PATTERN: { "type": "object", "default": {}, "$ref": RESOURCE_LANGUAGE_SETTINGS_SCHEMA_ID } },
"additionalProperties": false,
});
vec![
(RESOURCE_LANGUAGE_SETTINGS_SCHEMA_ID, json!({ "properties": resource_language, "patternProperties": {}, "additionalProperties": true, "allowTrailingCommas": true, "allowComments": true })),
("vscode://schemas/settings/default", defaults_schema),
("vscode://schemas/settings/user", settings_schema(Value::Object(all))),
("vscode://schemas/settings/profile", settings_schema(properties(&[Scope::Machine, Scope::MachineOverridable, Scope::Window, Scope::Resource]))),
("vscode://schemas/settings/machine", settings_schema(properties(&[Scope::ApplicationMachine, Scope::Machine, Scope::MachineOverridable, Scope::Window, Scope::Resource]))),
("vscode://schemas/settings/workspace", workspace),
("vscode://schemas/settings/folder", folder),
("vscode://schemas/settings/configurationDefaults", config_defaults),
]
}
/// `updateOverridePropertyPatternKey`: a `[lang]` key takes the override schema in every scope but language-overridable.
fn insert_language_override(all: &mut Map<String, Value>, by_scope: &mut HashMap<Scope, Map<String, Value>>, key: &str, language_override: &Value, default: Value) {
let mut schema = language_override.clone();
schema["default"] = default;
all.insert(key.to_string(), schema.clone());
for scope in [Scope::Application, Scope::ApplicationMachine, Scope::Machine, Scope::MachineOverridable, Scope::Window, Scope::Resource] {
by_scope.entry(scope).or_default().insert(key.to_string(), schema.clone());
}
}
#[cfg(test)]
mod tests;