Skip to content

Visual Studio Code, rebuilt in Rust

Rust
4.8 KB
Raw Blame
//! Debuggers contributed by extensions (debugger.ts `Debugger` and its `merge`).

use serde_json::{Value, json};

/// A debug type with its merged contribution.
#[derive(Clone, Debug, PartialEq)]
pub struct Debugger {
    pub debug_type: String,
    pub contribution: Value,
    /// The extension of the main contribution (`label`, `program` or `runtime`).
    pub extension_id: String,
}

impl Debugger {
    pub fn label(&self) -> &str {
        self.contribution["label"].as_str().unwrap_or(&self.debug_type)
    }

    /// `interestedInLanguage`.
    pub fn interested_in_language(&self, language_id: &str) -> bool {
        self.contribution["languages"].as_array().is_some_and(|languages| languages.iter().any(|language| language == language_id))
    }

    pub fn when(&self) -> Option<&str> {
        self.contribution["when"].as_str()
    }

    pub fn hidden_when(&self) -> Option<&str> {
        self.contribution["hiddenWhen"].as_str()
    }

    pub fn has_initial_configuration(&self) -> bool {
        !self.contribution["initialConfigurations"].is_null()
    }
}

/// debugger.ts `isDebuggerMainContribution`.
fn is_main_contribution(contribution: &Value) -> bool {
    contribution["type"].is_string() && (contribution["label"].is_string() || !contribution["program"].is_null() || !contribution["runtime"].is_null())
}

/// The debuggers of `contributes.debuggers` of `(extension id, description)` pairs, merged by type as the adapter
/// manager does: built-in contributions keep their values, later ones only add keys, and a `*` contribution merges
/// into every debugger after all types are known.
pub fn debuggers(extensions: &[(&str, &Value)]) -> Vec<Debugger> {
    let mut debuggers: Vec<Debugger> = Vec::new();
    let contributions = || extensions.iter().flat_map(|(extension_id, description)| description["contributes"]["debuggers"].as_array().into_iter().flatten().map(move |contribution| (*extension_id, *description, contribution)));
    for (extension_id, description, contribution) in contributions() {
        let Some(debug_type) = contribution["type"].as_str().filter(|debug_type| *debug_type != "*") else { continue };
        let index = match debuggers.iter().position(|debugger| debugger.debug_type == debug_type) {
            Some(index) => index,
            None => {
                debuggers.push(Debugger { debug_type: debug_type.to_owned(), contribution: json!({}), extension_id: extension_id.to_owned() });
                debuggers.len() - 1
            }
        };
        merge(&mut debuggers[index], contribution, extension_id, description);
    }
    for (extension_id, description, contribution) in contributions().filter(|(_, _, contribution)| contribution["type"] == "*") {
        for debugger in &mut debuggers {
            merge(debugger, contribution, extension_id, description);
        }
    }
    debuggers
}

/// debugger.ts `Debugger.merge`.
fn merge(debugger: &mut Debugger, contribution: &Value, extension_id: &str, description: &Value) {
    mixin(&mut debugger.contribution, contribution, description["isBuiltin"] == true, 0);
    if is_main_contribution(contribution) {
        debugger.extension_id = extension_id.to_owned();
    }
}

/// debugger.ts `mixin`: objects merge deeply, other values overwrite only with `overwrite`; `type` stays.
fn mixin(destination: &mut Value, source: &Value, overwrite: bool, level: usize) {
    let (Value::Object(destination), Value::Object(source)) = (destination, source) else { return };
    for (key, value) in source {
        match destination.get_mut(key) {
            Some(existing) if existing.is_object() && value.is_object() => mixin(existing, value, overwrite, level + 1),
            Some(existing) => {
                if overwrite && !(level == 0 && key == "type") {
                    *existing = value.clone();
                }
            }
            None => {
                destination.insert(key.clone(), value.clone());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::debuggers;

    /// debugAdapterManager.ts: a `*` contribution is no debug type; it merges into every debugger, also later ones.
    #[test]
    fn a_wildcard_contribution_merges_into_every_debugger() {
        let wildcard = json!({ "contributes": { "debuggers": [{ "type": "*", "configurationAttributes": { "launch": { "properties": { "serverReadyAction": {} } } } }] } });
        let node = json!({ "contributes": { "debuggers": [{ "type": "node", "label": "Node", "configurationAttributes": { "launch": { "properties": { "program": {} } } } }] } });
        let debuggers = debuggers(&[("server-ready", &wildcard), ("js-debug", &node)]);
        assert_eq!(debuggers.len(), 1);
        assert_eq!(debuggers[0].debug_type, "node");
        assert_eq!(debuggers[0].contribution["configurationAttributes"]["launch"]["properties"], json!({ "program": {}, "serverReadyAction": {} }));
    }
}