Skip to content

Visual Studio Code, rebuilt in Rust

Rust
25.4 KB
Raw Blame
//! debugEditorContribution.ts inline values: with `debug.inlineValues` on, the focused stack frame's values after the
//! lines of its file in the active editor, from the `InlineValuesProvider`s, else from the variables of the frame's
//! most specific scopes found as words of the lines (`createInlineValueDecoration`, its hover `formatHoverContent`).
// shortcut: only the active editor shows the values, where upstream decorates every editor on the frame's file; needs the state per editor.

use std::collections::{HashMap, HashSet};
use std::time::Duration;

use gpui::{AnyElement, AsyncApp, Context, Task, WeakEntity, div, prelude::*, px};
use serde_json::{Value, json};

use super::Workbench;
use super::content_hover::{Anchor, Part, PartContent, Participant};
use crate::debug::session::{StackFrame, Variable};
use crate::editor::in_place_replace::DEFAULT_WORD_REGEXP;
use crate::editor::injected_text::{InjectedText, InjectionOwner, WrapWidth};
use crate::editor::{OpenEditor, Position, TextDocument, char_column};
use crate::language_feature_debounce::FeatureDebounce;
use crate::language_features::Candidate;

#[cfg(test)]
mod tests;

const REGISTER: &str = "$registerInlineValuesProvider";
const MAX_NUM_INLINE_VALUES: usize = 100;
const MAX_TOKENIZATION_LINE_LEN: usize = 500;
/// `removeInlineValuesScheduler`.
const REMOVE_DELAY: Duration = Duration::from_millis(100);
const SPACER: char = '\u{a0}';

/// A 1-based (line, column) of `IRange`.
type At = (u64, u64);

#[derive(Default)]
pub(super) struct DebugInlineValues {
    /// The text of each shown value by its injection id, uncut, for its hover.
    texts: Vec<String>,
    /// `updateInlineValuesScheduler`.
    scheduled: Option<Task<()>>,
    /// The update in flight; dropping it cancels it (`displayedStore`).
    running: Option<Task<()>>,
    removing: Option<Task<()>>,
    /// `debounceInfo`: `{ min: 200 }`, so `max` is 200 ** 2.
    debounce: FeatureDebounce<200, 40000>,
}

impl Workbench {
    /// `updateInlineValuesScheduler.schedule()`: an edit, or a scroll with providers to ask about the new lines.
    pub(super) fn schedule_debug_inline_values(&mut self, cx: &mut Context<Self>) {
        let delay = match self.editors.active() {
            Some(editor) => {
                let key = self.inline_values_debounce_key(editor);
                self.debug_inline_values.debounce.get(&key)
            }
            None => Duration::from_millis(200),
        };
        self.debug_inline_values.scheduled = Some(cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(delay).await;
            let _ = workbench.update(cx, |workbench, cx| workbench.update_debug_inline_values(cx));
        }));
    }

    /// `onDidScrollChange`: only the providers' values depend on the visible lines.
    pub(super) fn debug_inline_values_scrolled(&mut self, cx: &mut Context<Self>) {
        if self.editors.active().is_some_and(|editor| !self.inline_values_handles(editor).is_empty()) {
            self.schedule_debug_inline_values(cx);
        }
    }

    /// `updateInlineValueDecorations` for the focused frame: off, or with the frame in another file, the values
    /// go 100ms later.
    pub(super) fn update_debug_inline_values(&mut self, cx: &mut Context<Self>) {
        self.debug_inline_values.scheduled = None;
        let Some((model_id, frame, handles)) = self.inline_values_target() else {
            if self.debug_inline_values.removing.is_none() {
                self.debug_inline_values.removing = Some(cx.spawn(async move |workbench, cx| {
                    cx.background_executor().timer(REMOVE_DELAY).await;
                    let _ = workbench.update(cx, |workbench, cx| {
                        workbench.debug_inline_values.removing = None;
                        workbench.debug_inline_values.running = None;
                        workbench.clear_debug_inline_values();
                        cx.notify();
                    });
                }));
            }
            return;
        };
        self.debug_inline_values.removing = None;
        let Some(session_id) = self.debug.focus.session.clone() else { return };
        let editor = self.editors.active().expect("found by the target");
        let lines = &editor.document().lines;
        let view_ranges: Vec<(At, At)> = super::semantic_tokens::visible_ranges_plus_viewport_above_below(editor, self.editors.viewport)
            .into_iter()
            .map(|(start, end)| ((start as u64 + 1, 1), (end as u64 + 1, lines[end].encode_utf16().count() as u64 + 1)))
            .collect();
        let uri = editor.document().uri();
        let debounce_key = self.inline_values_debounce_key(editor);
        self.debug_inline_values.running = Some(cx.spawn(async move |workbench, cx| {
            let values = match handles.is_empty() {
                true => scope_values(&workbench, cx, &session_id, &frame, model_id, &view_ranges).await,
                false => {
                    let started = cx.background_executor().now();
                    let values = provider_values(&workbench, cx, &session_id, &frame, model_id, uri, &handles, &view_ranges).await;
                    let elapsed = cx.background_executor().now() - started;
                    let _ = workbench.update(cx, |workbench, _| workbench.debug_inline_values.debounce.update(&debounce_key, elapsed));
                    values
                }
            };
            let _ = workbench.update(cx, |workbench, cx| workbench.show_debug_inline_values(model_id, values, cx));
        }));
    }

    /// The active editor's model, the focused frame and the editor's inline values providers when
    /// `debug.inlineValues` is `on` (or `auto` with a provider) and the frame is in the editor's file.
    fn inline_values_target(&self) -> Option<(u32, StackFrame, Vec<u64>)> {
        let editor = self.editors.active()?;
        let frame = self.debug.focused_frame()?;
        let handles = self.inline_values_handles(editor);
        let setting = self.setting("debug.inlineValues");
        let on = setting == true || setting == "on" || (setting == "auto" && !handles.is_empty());
        let document = editor.document();
        let same_file = document.scheme == "file" && frame.path() == Some(&*document.path.to_string_lossy());
        (on && same_file).then(|| (editor.model_id, frame.clone(), handles))
    }

    /// `inlineValuesProvider.ordered(model)`, best first.
    fn inline_values_handles(&self, editor: &OpenEditor) -> Vec<u64> {
        let uri = editor.document().uri();
        let language = editor.document().language_id.clone();
        let candidate = Candidate { uri: &uri, language: &language };
        self.language_features.ordered(REGISTER, &candidate).iter().map(|registration| registration.handle).collect()
    }

    fn inline_values_debounce_key(&self, editor: &OpenEditor) -> String {
        format!("{}{:?}", editor.document().uri(), self.inline_values_handles(editor))
    }

    /// `oldDecorations.set`: with word wrap the values can wrap lines, so the cursor keeps its top when visible.
    fn show_debug_inline_values(&mut self, model_id: u32, values: Vec<(usize, String)>, cx: &mut Context<Self>) {
        self.debug_inline_values.running = None;
        self.clear_debug_inline_values();
        let viewport = self.editors.viewport;
        // shortcut: the text area's width stands for `layoutInfo.width`, a left minimap's width short; needs the editor's width kept.
        let max_columns = ((self.text_area_bounds.get().size.width - 50.) / viewport.char_width).floor().max(0.) as usize;
        let Some(editor) = self.editors.editors.iter_mut().find(|editor| editor.model_id == model_id) else { return };
        let cursor_line = editor.head_view_line(0);
        let kept_top = (editor.wraps() && editor.visible_lines(viewport).contains(&cursor_line)).then(|| editor.line_top(cursor_line, viewport));
        let mut injections = Vec::new();
        let mut texts = Vec::new();
        for (line, text) in values {
            let content = inline_value_content(&text, max_columns);
            let position = Position::new(line, editor.document().lines[line].chars().count());
            injections.push(InjectedText { position, columns: content.chars().count() as f32, content, wrap: WrapWidth::Chars, owner: InjectionOwner::DebugInlineValue, id: texts.len(), at_range_start: false });
            texts.push(text);
        }
        editor.set_injected_text(InjectionOwner::DebugInlineValue, injections);
        if let Some(top) = kept_top {
            let cursor_line = editor.head_view_line(0);
            editor.scroll.top = (editor.scroll.top - (top - editor.line_top(cursor_line, viewport))).max(0.);
        }
        self.debug_inline_values.texts = texts;
        cx.notify();
    }

    fn clear_debug_inline_values(&mut self) {
        for editor in self.editors.all_editors_mut() {
            if editor.injected_text.iter().any(|injection| injection.owner == InjectionOwner::DebugInlineValue) {
                editor.set_injected_text(InjectionOwner::DebugInlineValue, Vec::new());
            }
        }
        self.debug_inline_values.texts.clear();
    }

    /// `.debug-inline-value` after its no-break space spacer.
    pub(super) fn debug_inline_value_element(&self, content: &str, left: f32, line_height: f32) -> AnyElement {
        let value = content.strip_prefix(SPACER).expect("made with the spacer").to_owned();
        let value = div().bg(self.color("editor.inlineValuesBackground")).text_color(self.color("editor.inlineValuesForeground")).child(value);
        div().absolute().top_0().left(px(left)).h(px(line_height)).flex().items_center().whitespace_nowrap().child(SPACER.to_string()).child(value).into_any_element()
    }

    /// markdownHoverParticipant.ts `computeSync`: the `hoverMessage` of a value whose line end the anchor touches.
    pub(super) fn debug_inline_value_hover_parts(&self, editor: &OpenEditor, anchor: Anchor) -> Vec<Part> {
        let mut parts = Vec::new();
        for injection in editor.injected_text_on(anchor.line).iter().filter(|injection| injection.owner == InjectionOwner::DebugInlineValue) {
            let column = injection.position.column;
            if column > anchor.start + 1 || anchor.end > column + 1 {
                continue;
            }
            let content = PartContent::Markdown(vec![json!({ "value": format_hover_content(&self.debug_inline_values.texts[injection.id]) })]);
            parts.push(Part { participant: Participant::Markdown, ordinal: parts.len(), start: injection.position, end: injection.position, content, source: None });
        }
        parts
    }
}

/// The providers' values, each value's line its segments by column joined with `, `.
#[allow(clippy::too_many_arguments)]
async fn provider_values(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame: &StackFrame, model_id: u32, uri: Value, handles: &[u64], view_ranges: &[(At, At)]) -> Vec<(usize, String)> {
    let range = |(start, end): (At, At)| json!({ "startLineNumber": start.0, "startColumn": start.1, "endLineNumber": end.0, "endColumn": end.1 });
    let stopped = range(((frame.line as u64, frame.column as u64 + 1), (frame.end_line as u64, frame.end_column as u64 + 1)));
    let context = json!({ "frameId": frame.id, "stoppedLocation": stopped });
    let Ok(calls) = workbench.update(cx, |workbench, _| {
        let mut calls = Vec::new();
        for &handle in handles.iter().rev() {
            for &view_range in view_ranges {
                calls.push(workbench.host.call_cancellable("ExtHostLanguageFeatures", "$provideInlineValues", vec![json!(handle), uri.clone(), range(view_range), context.clone()]));
            }
        }
        calls
    }) else {
        return Vec::new();
    };
    let mut segments: Vec<(usize, Vec<(u64, String)>)> = Vec::new();
    let mut scope_variables: Option<Vec<Variable>> = None;
    for call in calls {
        let Ok(Ok(values)) = call.await else { continue };
        for value in values.as_array().into_iter().flatten() {
            let start: At = (value["range"]["startLineNumber"].as_u64().unwrap_or(1), value["range"]["startColumn"].as_u64().unwrap_or(1));
            let end_column = value["range"]["endColumn"].as_u64().unwrap_or(1);
            let source_text = |cx: &mut AsyncApp| workbench.update(cx, |workbench, _| range_text(workbench, model_id, start, end_column)).unwrap_or_default();
            let text = match value["type"].as_str() {
                Some("text") => value["text"].as_str().map(str::to_owned),
                Some("variable") => {
                    let name = value["variableName"].as_str().map(str::to_owned).unwrap_or_else(|| source_text(cx));
                    if scope_variables.is_none() {
                        scope_variables = Some(most_specific_scope_variables(workbench, cx, session_id, frame).await.into_iter().flat_map(|(_, variables)| variables).collect());
                    }
                    let case_sensitive = value["caseSensitiveLookup"] == true;
                    let found = scope_variables.iter().flatten().find(|variable| if case_sensitive { variable.name == name } else { variable.name.to_lowercase() == name.to_lowercase() });
                    found.filter(|variable| !variable.value.is_empty()).map(|variable| format!("{name} = {}", variable.value))
                }
                Some("expression") => {
                    let expression = value["expression"].as_str().map(str::to_owned).unwrap_or_else(|| source_text(cx));
                    match expression.is_empty() {
                        true => None,
                        false => evaluate(workbench, cx, session_id, frame.id, &expression).await.map(|result| format!("{expression} = {result}")),
                    }
                }
                _ => None,
            };
            let Some(text) = text.filter(|text| !text.is_empty()) else { continue };
            let line = start.0.max(1) as usize - 1;
            let index = match segments.iter().position(|(shown, _)| *shown == line) {
                Some(index) => index,
                None => {
                    segments.push((line, Vec::new()));
                    segments.len() - 1
                }
            };
            if !segments[index].1.iter().any(|(_, shown)| *shown == text) {
                segments[index].1.push((start.1, text));
            }
        }
    }
    let mut values = Vec::new();
    for (line, mut line_segments) in segments {
        line_segments.sort_by_key(|(column, _)| *column);
        values.push((line, line_segments.into_iter().map(|(_, text)| text).collect::<Vec<_>>().join(", ")));
    }
    values
}

/// The old "one-size-fits-all" strategy: the scopes' values on the lines that name them.
async fn scope_values(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame: &StackFrame, model_id: u32, view_ranges: &[(At, At)]) -> Vec<(usize, String)> {
    let scopes = most_specific_scope_variables(workbench, cx, session_id, frame).await;
    let frame_start = (frame.line as u64, frame.column as u64);
    workbench
        .update(cx, |workbench, _| {
            let Some(editor) = workbench.editors.editors.iter().find(|editor| editor.model_id == model_id) else { return Vec::new() };
            words_inline_values(&editor.document(), &scopes, frame_start, view_ranges)
        })
        .unwrap_or_default()
}

/// The (start, end) of a scope's DAP range, when it has one.
type ScopeRange = Option<(At, At)>;

/// `getMostSpecificScopes(stackFrame.range)` and each scope's `getChildren`.
// shortcut: each update asks for the scopes and variables again, where upstream's frame caches them for the Variables view too; needs a shared cache.
async fn most_specific_scope_variables(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame: &StackFrame) -> Vec<(ScopeRange, Vec<Variable>)> {
    let Ok(reply) = workbench.update(cx, |workbench, _| workbench.dap_request(session_id, "scopes", json!({ "frameId": frame.id }))) else { return Vec::new() };
    let Ok(Ok(body)) = reply.await else { return Vec::new() };
    let scopes = most_specific_scopes(body["scopes"].as_array().map_or(&[], Vec::as_slice), frame);
    let mut result = Vec::new();
    for (range, reference) in scopes {
        let Ok(reply) = workbench.update(cx, |workbench, _| workbench.dap_request(session_id, "variables", json!({ "variablesReference": reference }))) else { break };
        let variables = match reply.await {
            Ok(Ok(body)) => body["variables"].as_array().into_iter().flatten().map(Variable::from_dap).collect(),
            _ => Vec::new(),
        };
        result.push((range, variables));
    }
    result
}

/// debugModel.ts `getMostSpecificScopes`: the scopes that are not expensive; with ranges, those around the frame's
/// range, narrowest first, unless none is. Each with its range and `variablesReference`.
fn most_specific_scopes(scopes: &[Value], frame: &StackFrame) -> Vec<(ScopeRange, i64)> {
    let cheap: Vec<(ScopeRange, i64)> = scopes.iter().filter(|scope| scope["expensive"] != true).map(|scope| (scope_range(scope), scope["variablesReference"].as_i64().unwrap_or(0))).collect();
    if cheap.iter().all(|(range, _)| range.is_none()) {
        return cheap;
    }
    let frame_range = ((frame.line as u64, frame.column as u64), (frame.end_line as u64, frame.end_column as u64));
    let mut around: Vec<(ScopeRange, i64)> = cheap.iter().copied().filter(|(range, _)| range.is_some_and(|(start, end)| start <= frame_range.0 && frame_range.1 <= end)).collect();
    around.sort_by_key(|(range, _)| range.map(|(start, end)| end.0 - start.0));
    if around.is_empty() { cheap } else { around }
}

/// debugModel.ts `new Scope(...)`: a range only with all four of `line`, `column`, `endLine` and `endColumn`.
fn scope_range(scope: &Value) -> ScopeRange {
    let number = |key: &str| scope[key].as_u64().filter(|value| *value != 0);
    Some(((number("line")?, number("column")?), (number("endLine")?, number("endColumn")?)))
}

/// The scopes from the narrowest out: in its part of the view ranges up to the frame's position, each line that has
/// a variable's name as a word shows it, a name keeping the value of its narrowest scope (#129770, #217326).
fn words_inline_values(document: &TextDocument, scopes: &[(ScopeRange, Vec<Variable>)], frame_start: At, view_ranges: &[(At, At)]) -> Vec<(usize, String)> {
    let mut words: HashMap<String, Vec<u64>> = HashMap::new();
    let mut parsed = HashSet::new();
    let mut values_per_line: Vec<(u64, Vec<(String, String)>)> = Vec::new();
    for (range, variables) in scopes {
        let scope_start = range.map_or((0, 0), |(start, _)| start);
        let own_ranges: Vec<(At, At)> = view_ranges.iter().map(|&(start, end)| (start.max(scope_start), end.min(frame_start))).filter(|(start, end)| start <= end).collect();
        for &(start, end) in &own_ranges {
            for line in start.0..=end.0 {
                if parsed.insert(line) {
                    line_words(document, line, &mut words);
                }
            }
        }
        for (line, names) in names_per_line(document, variables, &own_ranges, &words) {
            let index = match values_per_line.iter().position(|(shown, _)| *shown == line) {
                Some(index) => index,
                None => {
                    values_per_line.push((line, Vec::new()));
                    values_per_line.len() - 1
                }
            };
            let values = &mut values_per_line[index].1;
            for (name, value) in names {
                if !values.iter().any(|(shown, _)| *shown == name) {
                    values.push((name, value));
                }
            }
        }
    }
    let joined = |values: Vec<(String, String)>| values.into_iter().map(|(name, value)| format!("{name} = {value}")).collect::<Vec<_>>().join(", ");
    values_per_line.into_iter().map(|(line, values)| (line as usize - 1, joined(values))).collect()
}

/// `createInlineValueDecorationsInsideRange`: the first 100 names' values, on each line in `ranges` that has the
/// name as a word, in the order the line has them.
fn names_per_line(document: &TextDocument, variables: &[Variable], ranges: &[(At, At)], words: &HashMap<String, Vec<u64>>) -> Vec<(u64, Vec<(String, String)>)> {
    let mut name_values: Vec<(&str, &str)> = Vec::new();
    for variable in variables {
        match name_values.iter_mut().find(|(name, _)| *name == variable.name) {
            Some(entry) => entry.1 = &variable.value,
            None => name_values.push((&variable.name, &variable.value)),
        }
        if name_values.len() >= MAX_NUM_INLINE_VALUES {
            break;
        }
    }
    let mut line_names: Vec<(u64, Vec<&str>)> = Vec::new();
    for &(name, _) in &name_values {
        for &line in words.get(name).into_iter().flatten() {
            if !ranges.iter().any(|(start, end)| line >= start.0 && line <= end.0) {
                continue;
            }
            match line_names.iter_mut().find(|(shown, _)| *shown == line) {
                Some((_, names)) if names.contains(&name) => {}
                Some((_, names)) => names.push(name),
                None => line_names.push((line, vec![name])),
            }
        }
    }
    let mut result = Vec::new();
    for (line, mut names) in line_names {
        let text = &document.lines[line as usize - 1];
        names.sort_by_key(|name| text.find(name));
        let value = |name: &str| name_values.iter().find(|(shown, _)| *shown == name).expect("named above").1.to_owned();
        result.push((line, names.into_iter().map(|name| (name.to_owned(), value(name))).collect()));
    }
    result
}

/// `getWordToLineNumbersMap`: the first word of each `Other` token of the 1-based `line`; a line over 500 chars
/// is skipped.
fn line_words(document: &TextDocument, line: u64, words: &mut HashMap<String, Vec<u64>>) {
    let index = line as usize - 1;
    let text = &document.lines[index];
    if text.encode_utf16().count() > MAX_TOKENIZATION_LINE_LEN {
        return;
    }
    let mut start = 0;
    for (end, token_type, _) in document.tokens.line_tokens(&document.lines, index) {
        let token = &text[start..end];
        if token_type == textmate::StandardTokenType::Other
            && let Some((word_start, word_end)) = DEFAULT_WORD_REGEXP.find(token)
        {
            words.entry(token[word_start..word_end].to_owned()).or_default().push(line);
        }
        start = end;
    }
}

/// The model text of a value's range on its line, by UTF-16 columns.
fn range_text(workbench: &Workbench, model_id: u32, start: At, end_column: u64) -> String {
    let Some(editor) = workbench.editors.editors.iter().find(|editor| editor.model_id == model_id) else { return String::new() };
    let document = editor.document();
    let Some(text) = document.lines.get(start.0.max(1) as usize - 1) else { return String::new() };
    let (from, to) = (char_column(text, start.1.max(1) as usize - 1), char_column(text, end_column.max(1) as usize - 1));
    text.chars().skip(from).take(to.saturating_sub(from)).collect()
}

/// `Expression.evaluate(session, frame, 'watch')`: the result when the adapter answered with a body.
async fn evaluate(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame_id: i64, expression: &str) -> Option<String> {
    let reply = workbench.update(cx, |workbench, _| workbench.dap_request(session_id, "evaluate", json!({ "expression": expression, "frameId": frame_id, "context": "watch" }))).ok()?;
    let body = reply.await.ok()?.ok().filter(|body| !body.is_null())?;
    Some(body["result"].as_str().unwrap_or_default().to_owned())
}

/// `createInlineValueDecoration`: the spacer, then the text cut at `max_columns` UTF-16 units with `...`, its
/// spaces, tabs and newlines as no-break spaces.
fn inline_value_content(text: &str, max_columns: usize) -> String {
    let units: Vec<u16> = text.encode_utf16().collect();
    let shown = match units.len() > max_columns {
        true => String::from_utf16_lossy(&units[..max_columns]) + "...",
        false => text.to_owned(),
    };
    format!("{SPACER}{}", shown.replace([' ', '\t', '\n'], &SPACER.to_string()))
}

/// `formatHoverContent`: a code block of the text; `name = value` pairs split at the comma before each `=` after
/// the first, one per line, a pair's later lines indented past its `=`.
pub(super) fn format_hover_content(text: &str) -> String {
    let code = match text.contains(',') && text.contains('=') {
        true => hover_pairs(text).iter().map(|pair| indent_pair(pair)).collect::<Vec<_>>().join(",\n"),
        false => text.to_owned(),
    };
    format!("\n{}\n", crate::snippets::escaped_code_block_fence(&code, ""))
}

fn hover_pairs(text: &str) -> Vec<String> {
    let mut splits = Vec::new();
    let mut equals_found = 0;
    let mut start = 0;
    for (index, c) in text.char_indices() {
        if c != '=' {
            continue;
        }
        if equals_found > 0
            && let Some(comma) = text[..=index].rfind(',').filter(|comma| *comma >= start)
        {
            splits.push(comma);
            start = comma + 1;
        }
        equals_found += 1;
    }
    let mut pairs = Vec::new();
    let mut from = 0;
    for split in splits {
        pairs.push(text[from..split].trim().to_owned());
        from = split + 1;
    }
    if from < text.len() {
        pairs.push(text[from..].trim().to_owned());
    }
    pairs
}

fn indent_pair(pair: &str) -> String {
    let Some(equals) = pair.find('=') else { return pair.to_owned() };
    let indent = " ".repeat(pair[..equals].encode_utf16().count() + 2);
    let pair = pair.replace("\r\n", "\n");
    let mut lines = pair.split('\n');
    let first = lines.next().unwrap_or_default().to_owned();
    lines.fold(first, |text, line| format!("{text}\n{indent}{line}"))
}