Visual Studio Code, rebuilt in Rust
Rust
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Receiver;
use exthost::session::ForwardedRequest;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::{Value, json};
use super::*;
use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::workbench::debug_service::{DebugFocus, Reveal};
#[test]
fn hover_content_puts_each_pair_on_its_line_indented_past_its_equals() {
assert_eq!(format_hover_content("plain"), "\n```\nplain\n```\n");
assert_eq!(format_hover_content("a = f(1, 2), b = 3"), "\n```\na = f(1, 2),\nb = 3\n```\n");
assert_eq!(format_hover_content("x = {\r\n y: 1\n}, z = 2"), "\n```\nx = {\n y: 1\n },\nz = 2\n```\n");
}
#[test]
fn a_long_value_is_cut_and_its_spaces_do_not_break() {
assert_eq!(inline_value_content("a = 1", 150), "\u{a0}a\u{a0}=\u{a0}1");
assert_eq!(inline_value_content("abcdef", 3), "\u{a0}abc...");
}
#[test]
fn the_most_specific_scopes_are_the_cheap_ones_around_the_frame_narrowest_first() {
let frame = StackFrame { line: 5, column: 3, end_line: 5, end_column: 3, ..Default::default() };
let scope = |reference: i64, range: Option<(u64, u64)>, expensive: bool| {
let mut scope = json!({ "variablesReference": reference, "expensive": expensive });
if let Some((start, end)) = range {
scope.as_object_mut().unwrap().extend([("line".into(), json!(start)), ("column".into(), json!(1)), ("endLine".into(), json!(end)), ("endColumn".into(), json!(1))]);
}
scope
};
let references = |scopes: &[Value]| most_specific_scopes(scopes, &frame).into_iter().map(|(_, reference)| reference).collect::<Vec<_>>();
assert_eq!(references(&[scope(1, None, false), scope(2, None, true), scope(3, None, false)]), [1, 3]);
assert_eq!(references(&[scope(1, Some((1, 20)), false), scope(2, Some((4, 6)), false), scope(3, Some((6, 9)), false), scope(4, None, false)]), [2, 1]);
assert_eq!(references(&[scope(1, Some((7, 9)), false), scope(2, None, false)]), [1, 2], "no scope around the frame keeps them all");
}
fn workbench<'a>(cx: &'a mut TestAppContext, file: &Path) -> (gpui::Entity<Workbench>, Receiver<HostMessage>, &'a mut VisualTestContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let javascript = exthost::scan::scan_extension(&app_root.join("extensions/javascript"), true).unwrap();
let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
let (sender, host) = std::sync::mpsc::channel();
let file = file.to_path_buf();
let user = file.parent().unwrap().join("User");
let (workbench, cx) = cx.add_window_view(|window, cx| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[javascript]), Arc::new(Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user, None))), HostSync::new(sender), cx);
workbench.open_file(file.clone(), true, window, cx);
let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));
session.set_threads(&[json!({ "id": 1, "name": "main" })]);
let frame = StackFrame { id: 9, name: "f".into(), source: json!({ "path": file.to_string_lossy() }), line: 3, column: 3, end_line: 3, end_column: 3, ..Default::default() };
session.thread_mut(1).unwrap().frames = vec![frame];
workbench.debug.sessions.push(session);
workbench
});
cx.run_until_parked();
(workbench, host, cx)
}
/// Answers the adapter requests sent so far by their command; the rest stay unanswered.
fn respond(workbench: &gpui::Entity<Workbench>, host: &Receiver<HostMessage>, bodies: &[(&str, Value)], cx: &mut VisualTestContext) {
let requests: Vec<Value> = host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).collect();
for request in requests {
let Some((_, body)) = bodies.iter().find(|(command, _)| request["command"] == *command) else { continue };
let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": request["command"], "body": body });
let accept = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), response] };
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept, window, cx)));
cx.run_until_parked();
}
}
fn shown(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<(usize, String)> {
workbench.read_with(cx, |workbench, _| {
let editor = workbench.editors.active().unwrap();
editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::DebugInlineValue).map(|injection| (injection.position.line, injection.content.replace('\u{a0}', " "))).collect()
})
}
/// debugEditorContribution.ts old strategy: with `debug.inlineValues` on, each line up to the stop shows the scope's
/// variables it names, in the order it names them; a continue takes them away 100ms later.
#[gpui::test]
fn the_focused_frame_shows_its_variables_after_the_lines_naming_them(cx: &mut TestAppContext) {
let dir = std::env::temp_dir().join(format!("vsrustium-inline-values-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("a.js");
std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();
let (workbench, host, cx) = workbench(cx, &file);
workbench.update(cx, |workbench, _| drop(workbench.settings.lock().unwrap().update_value("debug.inlineValues", Some(&json!("on")), config::service::Target::User, None, &[]).unwrap()));
let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };
workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, Reveal::No, window, cx));
cx.run_until_parked();
respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4, "expensive": false }] }))], cx);
let variables = json!({ "variables": [{ "name": "a", "value": "1", "variablesReference": 0 }, { "name": "b", "value": "2", "variablesReference": 0 }] });
respond(&workbench, &host, &[("variables", variables)], cx);
assert_eq!(shown(&workbench, cx), [(0, " a = 1".into()), (1, " b = 2, a = 1".into()), (2, " b = 2".into())]);
let hover = workbench.read_with(cx, |workbench, _| {
let editor = workbench.editors.active().unwrap();
let anchor = Anchor { model_id: editor.model_id, line: 1, start: 16, end: 16 };
workbench.debug_inline_value_hover_parts(editor, anchor).into_iter().map(|part| part.content).collect::<Vec<_>>()
});
assert!(matches!(&hover[..], [PartContent::Markdown(contents)] if contents[0]["value"] == "\n```\nb = 2,\na = 1\n```\n"), "{hover:?}");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.debug.continue", Vec::new(), window, cx)));
cx.run_until_parked();
assert_eq!(shown(&workbench, cx).len(), 3, "the values stay 100ms");
cx.executor().advance_clock(REMOVE_DELAY);
cx.run_until_parked();
assert!(shown(&workbench, cx).is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
/// The values of a file that leaves the active group go with the rest when the frame's file is no longer active,
/// instead of staying stale in the other group's editor.
#[gpui::test]
fn the_values_of_a_file_moved_to_another_group_are_removed(cx: &mut TestAppContext) {
let dir = std::env::temp_dir().join(format!("vsrustium-inline-values-other-group-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("a.js");
std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();
let (workbench, host, cx) = workbench(cx, &file);
workbench.update(cx, |workbench, _| drop(workbench.settings.lock().unwrap().update_value("debug.inlineValues", Some(&json!("on")), config::service::Target::User, None, &[]).unwrap()));
let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };
workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, Reveal::No, window, cx));
cx.run_until_parked();
respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4, "expensive": false }] }))], cx);
respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "a", "value": "1", "variablesReference": 0 }] }))], cx);
assert!(!shown(&workbench, cx).is_empty());
crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);
workbench.update(cx, |workbench, cx| workbench.update_debug_inline_values(cx));
cx.executor().advance_clock(REMOVE_DELAY);
cx.run_until_parked();
let left = workbench.read_with(cx, |workbench, _| {
let editor = workbench.editors.model("file", &file).unwrap();
editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::DebugInlineValue).count()
});
assert_eq!(left, 0);
std::fs::remove_dir_all(dir).unwrap();
}
/// `debug.inlineValues: auto` asks the providers only; a variable lookup takes the value from the scopes.
#[gpui::test]
fn auto_shows_the_providers_values_in_column_order(cx: &mut TestAppContext) {
let dir = std::env::temp_dir().join(format!("vsrustium-inline-providers-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("a.js");
std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();
let (workbench, host, cx) = workbench(cx, &file);
let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };
workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus.clone(), Reveal::No, window, cx));
cx.run_until_parked();
assert!(host.try_iter().all(|message| message.method != "$provideInlineValues"), "auto without a provider shows nothing");
workbench.update_in(cx, |workbench, window, cx| {
workbench.language_features.register(REGISTER, vec![json!(3), json!("*")]);
workbench.set_debug_focus(focus, Reveal::No, window, cx);
});
cx.run_until_parked();
let range = |line: u64, start: u64, end: u64| json!({ "startLineNumber": line, "startColumn": start, "endLineNumber": line, "endColumn": end });
let values = json!([
{ "type": "variable", "range": range(2, 11, 12) },
{ "type": "text", "range": range(2, 3, 4), "text": "first" },
{ "type": "variable", "range": range(2, 7, 8), "variableName": "B", "caseSensitiveLookup": false },
{ "type": "text", "range": range(2, 9, 9), "text": "first" },
]);
let mut provided = 0;
for mut message in host.try_iter().collect::<Vec<_>>() {
if message.method == "$provideInlineValues" {
provided += 1;
assert_eq!(message.args[3], json!({ "frameId": 9, "stoppedLocation": range(3, 4, 4) }));
drop(message.reply.take().unwrap().send(Ok(values.clone())));
}
}
assert_eq!(provided, 1);
cx.run_until_parked();
respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4 }] }))], cx);
respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "a", "value": "1" }, { "name": "b", "value": "2" }] }))], cx);
assert_eq!(shown(&workbench, cx), [(1, " first, B = 2, a = 1".into())]);
std::fs::remove_dir_all(dir).unwrap();
}
/// variablesView.ts: a stop before the Variables view first shows leaves `Local` collapsed, as `renderBody` sets the
/// input it finds; once the view exists, a focus change expands the first cheap scope.
#[gpui::test]
fn the_first_scope_expands_only_once_the_variables_view_exists(cx: &mut TestAppContext) {
let dir = std::env::temp_dir().join(format!("vsrustium-first-scope-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("a.js");
std::fs::write(&file, "function f(a) {\n return a;\n}\n").unwrap();
let (workbench, host, cx) = workbench(cx, &file);
let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };
let variables_requests_at_stop = |cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus.clone(), Reveal::No, window, cx));
cx.run_until_parked();
respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4 }, { "name": "Global", "variablesReference": 5 }] }))], cx);
let requests: Vec<Value> = host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).collect();
requests.iter().filter(|request| request["command"] == "variables").map(|request| request["arguments"]["variablesReference"].clone()).collect::<Vec<_>>()
};
assert_eq!(variables_requests_at_stop(cx), Vec::<Value>::new(), "the view has not shown yet");
workbench.update(cx, |workbench, cx| workbench.show_debug_view(cx));
cx.update(|window, cx| drop(window.draw(cx)));
assert_eq!(variables_requests_at_stop(cx), [json!(4)]);
workbench.update(cx, |workbench, cx| workbench.show_view_container(crate::workbench::view_locations::EXPLORER_CONTAINER, cx));
assert_eq!(variables_requests_at_stop(cx), [json!(4)], "a hidden view that showed once still expands");
std::fs::remove_dir_all(dir).unwrap();
}