Skip to content

Visual Studio Code, rebuilt in Rust

Rust
31.7 KB
Raw Blame
//! inspectEditorTokens.ts: Developer: Inspect Editor Tokens and Scopes, the `token-inspect-widget` below the
//! cursor with the semantic and TextMate tokens there, their decoded metadata, the TextMate scopes and the rules
//! that color them.

use std::cell::Cell;
use std::rc::Rc;

use gpui::{
    AnyElement, Bounds, Context, Div, FontStyle, FontWeight, HighlightStyle, KeyUpEvent, Size, StyledText, Task, TextRun, Window, canvas, deferred, div,
    prelude::*, px,
};
use serde::Serialize;
use serde_json::Value;
use textmate::StandardTokenType;

use super::Workbench;
use super::editor_message::horizontal_in_page;
use crate::commands::Outcome;
use crate::editor::{OpenEditor, Position, TextDocument, char_column, utf16_column};
use crate::semantic_tokens::{RuleScope, SemanticTheme, SemanticTokensLegend, TokenStyle, TokenStyleDefinition};
use crate::theme::{Theme, contrast_ratio, parse_hex};

const UI_FONT: &str = ".SystemUIFont";
const MONOSPACE_FONT: &str = "Menlo";
/// style.css `.monaco-workbench`: 13px text with a 1.4em line height, which the widget inherits.
const FONT_SIZE: f32 = 13.;
const LINE_HEIGHT: f32 = 18.2;
/// The user agent's `h2`: 1.5em, with 0.83em margins above and below.
const TOKEN_FONT_SIZE: f32 = FONT_SIZE * 1.5;
const TOKEN_MARGIN: f32 = TOKEN_FONT_SIZE * 0.83;
/// The user agent's `hr` margins of 0.5em.
const SEPARATOR_MARGIN: f32 = FONT_SIZE * 0.5;
/// `.tiw-metadata-key`: `min-width: 150px`.
const KEY_MIN_WIDTH: f32 = 150.;
/// contentWidgets.ts `_layoutBoxInPage`: the widget keeps 22px from the window's top and bottom.
const PAGE_PADDING: f32 = 22.;

#[derive(Default)]
pub(super) struct InspectTokens {
    /// The model and language the widget opened on; another one stops it.
    shown: Option<(u32, String)>,
    widget_bounds: Rc<Cell<Option<Bounds<f32>>>>,
    /// `_beginCompute`'s semantic tokens for a cursor position and coloring setting.
    semantic: Option<SemanticRequest>,
}

struct SemanticRequest {
    position: Position,
    enabled: bool,
    /// `None` while the provider has not answered ("Loading..."); then its tokens and the TextMate token at the
    /// position, both taken when it answered as `_compute` does.
    answer: Option<(Option<SemanticTokens>, Option<TextMateToken>)>,
    _task: Task<()>,
}

type SemanticTokens = (Vec<u32>, SemanticTokensLegend);
type TextMateToken = (std::ops::Range<usize>, Rc<textmate::ScopeStack>, StandardTokenType);

#[derive(Debug, PartialEq)]
struct TokenInspection {
    text: String,
    length: usize,
    /// The metadata table, then the semantic token's table and the TextMate token's, when there is such a token.
    tables: Vec<Vec<(String, Value_)>>,
}

/// A `td.tiw-metadata-value`.
#[derive(Clone, Debug, PartialEq)]
enum Value_ {
    /// Text runs, each in italics (`.tiw-metadata-semantic`) or not.
    Runs(Vec<(String, bool)>),
    /// `.tiw-metadata-scopes`: one scope per line.
    Scopes(Vec<String>),
    /// `_renderTokenStyleDefinition` of probed TextMate scopes: the scope that matched, the selectors of the rule
    /// that styles it (`ul.tiw-metadata-values`) and the rule's settings.
    ScopeRule { scope: String, selectors: Vec<String>, settings: String },
    /// `code.tiw-theme-selector`: the rule's selector over its settings, struck through when a semantic color wins.
    ThemeRule { selector: String, settings: String, struck: bool },
}

impl Value_ {
    fn text(text: impl Into<String>) -> Value_ {
        Value_::Runs(vec![(text.into(), false)])
    }
}

/// `IDecodedMetadata`: a semantic token's leaves the background and the flags it does not set out.
#[derive(Clone, Debug, Default, PartialEq)]
struct Decoded {
    foreground: Option<String>,
    background: Option<String>,
    bold: bool,
    italic: bool,
    underline: bool,
    strikethrough: bool,
}

/// `ISemanticTokenInfo`
struct SemanticTokenInfo<'a> {
    token_type: String,
    modifiers: Vec<String>,
    text: String,
    length: usize,
    style: TokenStyle,
    definitions: crate::semantic_tokens::TokenStyleDefinitions<'a>,
}

impl Workbench {
    pub(super) fn register_inspect_tokens_commands(&mut self) {
        self.commands.register("editor.action.inspectTMScopes", |workbench, _, _, cx| {
            let shown = match (&workbench.inspect_tokens.shown, workbench.editors.active()) {
                (None, Some(editor)) => Some((editor.model_id, editor.document().language_id.clone())),
                _ => None,
            };
            workbench.inspect_tokens.shown = shown;
            workbench.inspect_tokens.widget_bounds.set(None);
            workbench.inspect_tokens.semantic = None;
            cx.notify();
            Outcome::done()
        });
    }

    /// `onDidChangeModel` and `onDidChangeModelLanguage` stop the inspector.
    pub(super) fn stop_inspect_tokens_on_model_change(&mut self) {
        let Some((model_id, language)) = &self.inspect_tokens.shown else { return };
        if self.editors.active().is_none_or(|editor| editor.model_id != *model_id || editor.document().language_id != *language) {
            self.inspect_tokens.shown = None;
            self.inspect_tokens.semantic = None;
        }
    }

    /// `onDidChangeCursorPosition` and the `editor.semanticHighlighting` change: `_beginCompute` asks the provider again.
    pub(super) fn follow_inspect_tokens_cursor(&mut self, cx: &mut Context<Self>) {
        let Some(editor) = self.inspect_tokens.shown.as_ref().and(self.editors.active()) else { return };
        let (position, enabled) = (editor.selection().head, self.semantic_coloring_enabled(editor));
        if self.inspect_tokens.semantic.as_ref().is_some_and(|request| request.position == position && request.enabled == enabled) {
            return;
        }
        let tokens = self.inspector_semantic_tokens(editor, position.line);
        let task = cx.spawn(async move |workbench, cx| {
            let answer = tokens.await;
            let _ = workbench.update(cx, |workbench, cx| {
                match answer {
                    Ok(tokens) => {
                        let editor = workbench.editors.active().expect("the inspector closes with its editor");
                        let document = editor.document();
                        let line = &document.lines[position.line];
                        let offset = line.char_indices().nth(position.column).map_or(line.len(), |(offset, _)| offset);
                        let textmate = document.tokens.token_at(&document.lines, position.line, offset);
                        drop(document);
                        let request = workbench.inspect_tokens.semantic.as_mut().expect("a running request is the current one");
                        request.answer = Some((tokens, textmate));
                    }
                    // `notificationService.warn(err)`, then `stop`.
                    Err(error) => {
                        workbench.notify_warning(error["message"].as_str().unwrap_or_default());
                        workbench.inspect_tokens.shown = None;
                        workbench.inspect_tokens.semantic = None;
                    }
                }
                cx.notify();
            });
        });
        self.inspect_tokens.semantic = Some(SemanticRequest { position, enabled, answer: None, _task: task });
    }

    /// `onKeyUp` of Escape in the editor stops the inspector.
    pub(super) fn inspect_tokens_key_up(&mut self, event: &KeyUpEvent, _: &mut Window, cx: &mut Context<Self>) {
        if event.keystroke.key == "escape" && self.inspect_tokens.shown.take().is_some() {
            self.inspect_tokens.semantic = None;
            cx.notify();
        }
    }

    /// The widget at the primary cursor, recomputed on every render, so on every cursor move and theme change;
    /// below the line (`ContentWidgetPositionPreference.BELOW`), above it when only that fits in the window.
    pub(super) fn inspect_tokens_widget(&self, editor: &OpenEditor, content_left: f32, char_width: f32, window: &Window) -> Option<AnyElement> {
        let (model_id, _) = self.inspect_tokens.shown.as_ref()?;
        let position = editor.selection().head;
        if *model_id != editor.model_id || editor.folding.is_hidden(position.line) {
            return None;
        }
        let view_line = editor.position_view_line(position, false);
        let anchor_left = editor.segment_pixel_left(editor.segment(view_line), position.column, char_width);
        let anchor_top = editor.line_top(view_line, self.editors.viewport) - editor.scroll.top;
        let measured = self.inspect_tokens.widget_bounds.get().map(|bounds| bounds.size);
        let size = measured.unwrap_or(Size { width: 0., height: 0. });
        let editor_bounds = self.text_area_bounds.get();
        let window_size = window.viewport_size().map(f32::from);
        let left = horizontal_in_page(anchor_left - editor.scroll.left + content_left, size.width, editor_bounds, window_size);
        let below_top = anchor_top + self.editors.viewport.line_height;
        let fits_below = editor_bounds.origin.y + below_top + size.height <= window_size.height - PAGE_PADDING;
        let above_top = anchor_top - size.height;
        let fits_above = editor_bounds.origin.y + above_top >= PAGE_PADDING;
        let top = if fits_below || !fits_above { below_top } else { above_top };
        let widget_bounds = self.inspect_tokens.widget_bounds.clone();
        let measure = canvas(
            move |bounds, window, cx| {
                let bounds: Bounds<f32> = bounds.map(f32::from);
                if widget_bounds.get().map(|old| old.size) != Some(bounds.size) {
                    super::part_view::redraw_after_frame(window, cx);
                }
                widget_bounds.set(Some(bounds));
            },
            |_, _, _, _| (),
        )
        .absolute()
        .inset_0();
        let widget = div()
            .id("token-inspect-widget")
            .absolute()
            .left(px(left))
            .top(px(top))
            .max_w(px((editor_bounds.size.width * 0.66).max(500.)))
            .p(px(10.))
            .border_1()
            .border_color(self.color("editorHoverWidget.border"))
            .bg(self.color("editorHoverWidget.background"))
            .text_color(self.color("editor.foreground"))
            .font_family(UI_FONT)
            .text_size(px(FONT_SIZE))
            .line_height(px(LINE_HEIGHT))
            .cursor_default()
            .occlude()
            .when(measured.is_none(), |widget| widget.invisible())
            .on_any_mouse_down(|_, _, cx| cx.stop_propagation())
            .child(measure);
        let answer = self.inspect_tokens.semantic.as_ref().filter(|request| request.position == position).and_then(|request| request.answer.as_ref());
        let widget = match answer {
            None => widget.child("Loading..."),
            Some((semantic, textmate)) => match inspect(&editor.document(), position, &self.theme, semantic.as_ref(), textmate.clone()) {
                None => widget.child("No grammar or semantic tokens available."),
                Some(inspection) => widget.children(self.inspection_content(inspection, window)),
            },
        };
        Some(deferred(widget).with_priority(1).into_any_element())
    }

    fn inspection_content(&self, inspection: TokenInspection, window: &Window) -> Vec<AnyElement> {
        let separator = || div().h(px(1.)).bg(self.color("editorHoverWidget.border"));
        let length = format!("{} {}", inspection.length, if inspection.length == 1 { "char" } else { "chars" });
        let token = div()
            .flex()
            .justify_between()
            .items_start()
            .gap(px(4.))
            .my(px(TOKEN_MARGIN))
            .font_family(MONOSPACE_FONT)
            .text_size(px(TOKEN_FONT_SIZE))
            .font_weight(FontWeight::BOLD)
            .child(div().min_w_0().child(inspection.text))
            .child(div().flex_none().text_size(px(TOKEN_FONT_SIZE * 0.6)).font_weight(FontWeight::NORMAL).child(length));
        let mut content = vec![token.into_any_element()];
        for (index, table) in inspection.tables.into_iter().enumerate() {
            // The `h2`'s bottom margin collapses with the first `hr`'s top one.
            let separator = if index == 0 { separator().mb(px(SEPARATOR_MARGIN)) } else { separator().my(px(SEPARATOR_MARGIN)) };
            content.push(separator.into_any_element());
            let rows = table.into_iter().map(|(key, value)| (key, value_cell(value))).collect();
            content.push(metadata_table(rows, window).into_any_element());
        }
        content
    }
}

/// One value cell's contents.
fn value_cell(value: Value_) -> Div {
    // `.tiw-theme-selector` is a `code` element: the browser collapses the JSON's newlines and tabs to spaces.
    let collapsed = |text: String| text.split_whitespace().collect::<Vec<_>>().join(" ");
    match value {
        Value_::Runs(runs) => {
            let mut text = String::new();
            let mut highlights = Vec::new();
            for (run, semantic) in runs {
                if semantic {
                    highlights.push((text.len()..text.len() + run.len(), HighlightStyle { font_style: Some(FontStyle::Italic), ..Default::default() }));
                }
                text.push_str(&run);
            }
            div().child(StyledText::new(text).with_highlights(highlights))
        }
        Value_::Scopes(scopes) => div().line_height(px(15.)).children(scopes.into_iter().map(|scope| div().child(scope))),
        Value_::ScopeRule { scope, selectors, settings } => {
            // `ul.tiw-metadata-values`: the user agent's 1em margins, no bullets, at most 300px tall.
            let list = div().id("tiw-metadata-values").my(px(FONT_SIZE)).max_h(px(300.)).overflow_y_scroll().line_height(px(15.));
            div().child(scope).child(list.children(selectors.into_iter().map(|selector| div().child(selector)))).child(collapsed(settings))
        }
        Value_::ThemeRule { selector, settings, struck } => div().child(selector).child(collapsed(settings)).when(struck, |rule| rule.line_through()),
    }
}

/// `table.tiw-metadata-table`: the user agent's 2px border spacing and 1px cell padding, the keys' column as wide
/// as its widest key and at least 150px, the values in the monospace font, wrapping.
fn metadata_table(rows: Vec<(String, Div)>, window: &Window) -> Div {
    let key_width = rows.iter().map(|(key, _)| text_width(key, window)).fold(KEY_MIN_WIDTH, f32::max);
    div().flex().flex_col().gap(px(2.)).p(px(2.)).children(rows.into_iter().map(|(key, value)| {
        div()
            .flex()
            .gap(px(2.))
            .child(div().flex_none().w(px(key_width)).pl(px(1.)).pr(px(10.)).py(px(1.)).whitespace_nowrap().child(key))
            .child(value.flex_1().min_w_0().p(px(1.)).font_family(MONOSPACE_FONT))
    }))
}

fn text_width(text: &str, window: &Window) -> f32 {
    let run = TextRun { len: text.len(), font: gpui::font(UI_FONT), color: gpui::black(), background_color: None, underline: None, strikethrough: None };
    f32::from(window.text_system().shape_line(text.to_string().into(), px(FONT_SIZE), &[run], None).width)
}

/// `_compute`: the semantic token at `position` from `semantic` and the TextMate token there; none without either.
fn inspect(document: &TextDocument, position: Position, theme: &Theme, semantic: Option<&SemanticTokens>, textmate: Option<TextMateToken>) -> Option<TokenInspection> {
    let line = &document.lines[position.line];
    let semantic = semantic.and_then(|tokens| semantic_token_at(tokens, line, position, &theme.semantic, &document.language_id));
    if semantic.is_none() && textmate.is_none() {
        return None;
    }
    let semantic_metadata = semantic.as_ref().map(|info| Decoded {
        foreground: info.style.foreground.clone(),
        background: None,
        bold: info.style.bold == Some(true),
        italic: info.style.italic == Some(true),
        underline: info.style.underline == Some(true),
        strikethrough: info.style.strikethrough == Some(true),
    });
    let textmate_text = textmate.as_ref().map(|(range, _, _)| render_token_text(&line[range.clone()]));
    let (text, length) = match (&semantic, &textmate) {
        (Some(info), _) if !info.text.is_empty() => (render_token_text(&info.text), info.length),
        (_, Some((range, _, _))) => (textmate_text.clone().expect("a TextMate token"), line[range.clone()].encode_utf16().count()),
        _ => (String::new(), 0),
    };

    let mut textmate_metadata = None;
    let mut language = String::new();
    let mut token_type = StandardTokenType::Other;
    if let Some((_, scopes, standard_type)) = &textmate {
        let style = theme.tokens.style(scopes);
        let color_map = theme.tokens.color_map();
        language = scopes.language.as_deref().unwrap_or(&document.language_id).to_string();
        token_type = *standard_type;
        textmate_metadata = Some(Decoded {
            foreground: Some(color_map[style.foreground].clone()),
            background: Some(color_map[style.background].clone()),
            bold: style.font_style & textmate::BOLD != 0,
            italic: style.font_style & textmate::ITALIC != 0,
            underline: style.font_style & textmate::UNDERLINE != 0,
            strikethrough: style.font_style & textmate::STRIKETHROUGH != 0,
        });
    }
    let mut metadata = vec![("language".to_string(), Value_::text(language)), ("standard token type".to_string(), Value_::text(token_type_name(token_type)))];
    metadata.extend(format_metadata(semantic_metadata.as_ref(), textmate_metadata.as_ref()));
    let mut tables = vec![metadata];

    if let Some(info) = &semantic {
        tables.push(semantic_rows(info, &theme.semantic));
    }
    if let Some((_, scopes, _)) = &textmate {
        let mut rows = Vec::new();
        let textmate_text = textmate_text.expect("a TextMate token");
        if textmate_text != text {
            let length = textmate_text.encode_utf16().count();
            rows.push(("textmate token".to_string(), Value_::text(format!("{textmate_text} ({length})"))));
        }
        let names = scopes.names();
        rows.push(("textmate scopes".to_string(), Value_::Scopes(names.iter().rev().map(|name| name.to_string()).collect())));
        let semantic_foreground = semantic_metadata.and_then(|metadata| metadata.foreground);
        let textmate_foreground = textmate_metadata.and_then(|metadata| metadata.foreground);
        match find_matching_theme_rule(theme.tokens.rules(), &names) {
            Some((selector, settings)) if semantic_foreground != textmate_foreground => {
                rows.push(("foreground".to_string(), Value_::ThemeRule { selector, settings, struck: semantic_foreground.is_some() }));
            }
            Some(_) => {}
            None if semantic_foreground.is_none() => rows.push(("foreground".to_string(), Value_::text("No theme selector"))),
            None => {}
        }
        tables.push(rows);
    }
    Some(TokenInspection { text, length, tables })
}

/// `_getSemanticTokenAtPosition`: the token of `tokens` holding `position` on `line`, styled by `theme` with the
/// definitions of its properties.
fn semantic_token_at<'a>((data, legend): &SemanticTokens, line: &str, position: Position, theme: &'a SemanticTheme, language: &str) -> Option<SemanticTokenInfo<'a>> {
    let character = utf16_column(line, position.column) as u32;
    let (mut last_line, mut last_character) = (0, 0);
    for token in data.chunks_exact(5) {
        let [line_delta, character_delta, length, type_index, modifier_set] = [token[0], token[1], token[2], token[3], token[4]];
        let token_line = last_line + line_delta;
        let start = if line_delta == 0 { last_character + character_delta } else { character_delta };
        if token_line as usize == position.line && start <= character && character < start + length {
            const NOT_IN_LEGEND: &str = "not in legend (ignored)";
            let token_type = legend.token_types.get(type_index as usize).map_or(NOT_IN_LEGEND, String::as_str).to_string();
            let mut modifiers = Vec::new();
            let mut set = modifier_set;
            let mut index = 0;
            while set > 0 && index < legend.token_modifiers.len() {
                if set & 1 != 0 {
                    modifiers.push(legend.token_modifiers[index].clone());
                }
                set >>= 1;
                index += 1;
            }
            if set > 0 {
                modifiers.push(NOT_IN_LEGEND.to_string());
            }
            // `getValueInRange` clamps the range to the line.
            let (start_column, end_column) = (char_column(line, start as usize), char_column(line, (start + length) as usize));
            let text: String = line.chars().skip(start_column).take(end_column - start_column).collect();
            let mut definitions = Default::default();
            let modifier_names: Vec<&str> = modifiers.iter().map(String::as_str).collect();
            let style = theme.get_token_style_metadata_with_definitions(&token_type, &modifier_names, language, &mut definitions);
            let length = text.encode_utf16().count();
            return Some(SemanticTokenInfo { token_type, modifiers, text, length, style, definitions });
        }
        (last_line, last_character) = (token_line, start);
    }
    None
}

/// The semantic token's table: its type, modifiers, and per definition the properties it styles.
fn semantic_rows(info: &SemanticTokenInfo, theme: &SemanticTheme) -> Vec<(String, Value_)> {
    let mut rows = vec![("semantic token type".to_string(), Value_::text(info.token_type.clone()))];
    if !info.modifiers.is_empty() {
        rows.push(("modifiers".to_string(), Value_::text(info.modifiers.join(" "))));
    }
    let style = &info.style;
    // Each property with its index in `TokenStyleDefinitions`.
    let properties = [
        ("foreground", 0, style.foreground.is_some()),
        ("bold", 1, style.bold.is_some()),
        ("italic", 4, style.italic.is_some()),
        ("underline", 2, style.underline.is_some()),
        ("strikethrough", 3, style.strikethrough.is_some()),
    ];
    // The same definition for several properties shows once, keyed by all of them.
    let mut groups: Vec<(Vec<&str>, Value_)> = Vec::new();
    for (property, index, set) in properties {
        if !set {
            continue;
        }
        let value = render_token_style_definition(info.definitions[index], property, theme);
        match groups.iter_mut().find(|(_, group_value)| *group_value == value) {
            Some((group, _)) => group.push(property),
            None => groups.push((vec![property], value)),
        }
    }
    rows.extend(groups.into_iter().map(|(properties, value)| (properties.join(", "), value)));
    rows
}

/// `_renderTokenStyleDefinition`
fn render_token_style_definition(definition: Option<TokenStyleDefinition>, property: &str, theme: &SemanticTheme) -> Value_ {
    match definition {
        None => Value_::Runs(Vec::new()),
        Some(TokenStyleDefinition::Scopes(scopes)) => {
            let Some((scope, foreground_rule, font_style_rule)) = theme.resolve_scope_definitions(scopes) else { return Value_::Runs(Vec::new()) };
            let Some(rule) = (if property == "foreground" { foreground_rule } else { font_style_rule }) else { return Value_::Runs(Vec::new()) };
            let selectors = match &rule["scope"] {
                serde_json::Value::Array(scopes) => scopes.iter().map(|scope| scope.as_str().map_or_else(|| scope.to_string(), str::to_owned)).collect(),
                serde_json::Value::String(scope) => vec![scope.clone()],
                other => vec![other.to_string()],
            };
            Value_::ScopeRule { scope: scope.join(" "), selectors, settings: settings_json(&rule["settings"]) }
        }
        Some(TokenStyleDefinition::Rule(rule, scope)) => {
            let origin = match scope {
                RuleScope::Setting => "User settings",
                RuleScope::Theme => "Color theme",
            };
            let mut id = vec![rule.selector.token_type.clone()];
            let mut modifiers = rule.selector.modifiers.clone();
            modifiers.sort();
            id.extend(modifiers);
            let language = rule.selector.language.as_ref().map_or(String::new(), |language| format!(":{language}"));
            Value_::text(format!("{origin}: {}{language} - {}", id.join("."), render_style_property(&rule.style, property)))
        }
        Some(TokenStyleDefinition::Value(value)) => Value_::text(format!("Default: {}", render_style_property(&theme.resolve_token_style_value(value), property))),
    }
}

/// `_renderStyleProperty`: the foreground as `Color.Format.CSS.formatHexA(color, true)` writes it, in lower case.
fn render_style_property(style: &TokenStyle, property: &str) -> String {
    let flag = match property {
        "foreground" => return style.foreground.as_deref().map_or(String::new(), str::to_lowercase),
        "bold" => style.bold,
        "italic" => style.italic,
        "underline" => style.underline,
        _ => style.strikethrough,
    };
    flag.map_or(String::new(), |flag| flag.to_string())
}

/// `renderTokenText`: over 40 characters keeps the first and last 20 around an ellipsis; a tab shows as an arrow,
/// a space as a middle dot.
fn render_token_text(text: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let shown: Vec<char> = match chars.len() > 40 {
        true => chars[..20].iter().copied().chain(['…']).chain(chars[chars.len() - 20..].iter().copied()).collect(),
        false => chars,
    };
    shown
        .into_iter()
        .map(|c| match c {
            '\t' => '\u{2192}',
            ' ' => '\u{00B7}',
            c => c,
        })
        .collect()
}

/// `_tokenTypeToString`
fn token_type_name(token_type: StandardTokenType) -> &'static str {
    match token_type {
        StandardTokenType::Other => "Other",
        StandardTokenType::Comment => "Comment",
        StandardTokenType::String => "String",
        StandardTokenType::RegEx => "RegEx",
    }
}

/// `_formatMetadata`: each color from the semantic token, else the TextMate one, the contrast of the two, and the
/// font styles; what the semantic token sets is in italics.
fn format_metadata(semantic: Option<&Decoded>, textmate: Option<&Decoded>) -> Vec<(String, Value_)> {
    let mut rows = Vec::new();
    let mut render = |property: &str, value: fn(&Decoded) -> Option<String>| {
        let from_semantic = semantic.and_then(value);
        let color = from_semantic.clone().or_else(|| textmate.and_then(value))?;
        rows.push((property.to_string(), Value_::Runs(vec![(color.clone(), from_semantic.is_some())])));
        Some(color)
    };
    let foreground = render("foreground", |decoded| decoded.foreground.clone());
    let background = render("background", |decoded| decoded.background.clone());
    if let (Some(foreground), Some(background)) = (foreground, background) {
        let foreground = parse_hex(&foreground).expect("the token color map holds hex colors");
        let background = parse_hex(&background).expect("the token color map holds hex colors");
        match background.a == 1. {
            true => rows.push(("contrast ratio".to_string(), Value_::text(format!("{:.2}", contrast_ratio(make_opaque(foreground, background), background))))),
            false => rows.push(("Contrast ratio cannot be precise for background colors that use transparency".to_string(), Value_::Runs(Vec::new()))),
        }
    }
    let styles: [(&str, fn(&Decoded) -> bool); 4] =
        [("bold", |decoded| decoded.bold), ("italic", |decoded| decoded.italic), ("underline", |decoded| decoded.underline), ("strikethrough", |decoded| decoded.strikethrough)];
    let mut labels: Vec<(String, bool)> = Vec::new();
    for (key, set) in styles {
        let label = match (semantic.is_some_and(set), textmate.is_some_and(set)) {
            (true, _) => (key.to_string(), true),
            (false, true) => (key.to_string(), false),
            (false, false) => continue,
        };
        if !labels.is_empty() {
            labels.push((" ".to_string(), false));
        }
        labels.push(label);
    }
    if !labels.is_empty() {
        rows.push(("font style".to_string(), Value_::Runs(labels)));
    }
    rows
}

/// `Color.makeOpaque`: a translucent color blended onto the opaque background, channels truncated as `RGBA` does.
fn make_opaque(color: gpui::Rgba, background: gpui::Rgba) -> gpui::Rgba {
    if color.a == 1. {
        return color;
    }
    let alpha = (color.a * 1000.).round() / 1000.;
    let blend = |channel: f32, under: f32| {
        let (channel, under) = ((channel * 255.).round(), (under * 255.).round());
        (under - alpha * (under - channel)).clamp(0., 255.).trunc() / 255.
    };
    gpui::Rgba { r: blend(color.r, background.r), g: blend(color.g, background.g), b: blend(color.b, background.b), a: 1. }
}

/// TMHelper.ts `findMatchingThemeRule` with `onlyColorRules` false: from the innermost scope out, the most specific
/// selector matching the scope under its parents, a later rule winning a tie; its raw selector and settings JSON.
fn find_matching_theme_rule(rules: &[Value], scopes: &[&str]) -> Option<(String, String)> {
    for index in (0..scopes.len()).rev() {
        if let Some((selector, settings)) = matching_rule(rules, scopes[index], &scopes[..index]) {
            return Some((selector.to_string(), settings_json(settings)));
        }
    }
    None
}

/// `findMatchingThemeRule2`.
fn matching_rule<'a>(rules: &'a [Value], scope: &str, parents: &[&str]) -> Option<(&'a str, &'a Value)> {
    let mut result: Option<(&str, &Value)> = None;
    for rule in rules.iter().rev() {
        let selectors: Vec<&str> = match &rule["scope"] {
            Value::String(scope) => scope.split(',').map(str::trim).collect(),
            Value::Array(scopes) => scopes.iter().filter_map(Value::as_str).collect(),
            _ => continue,
        };
        for selector in selectors {
            if selector_matches(selector, scope, parents) && result.is_none_or(|(best, _)| more_specific(selector, best)) {
                result = Some((selector, &rule["settings"]));
            }
        }
    }
    result
}

/// `ThemeRule`: the last space-separated piece is the scope, the ones before it the parent scopes.
fn split_selector(selector: &str) -> (&str, Vec<&str>) {
    let mut pieces: Vec<&str> = selector.split(' ').collect();
    let scope = pieces.pop().expect("split yields a piece");
    (scope, pieces)
}

/// `ThemeRule._matches`: the scope matches, and the parent selectors match parent scopes in order, innermost last.
fn selector_matches(selector: &str, scope: &str, parents: &[&str]) -> bool {
    let (selector_scope, selector_parents) = split_selector(selector);
    if !matches_one(selector_scope, scope) {
        return false;
    }
    let mut remaining = selector_parents.iter().rev().peekable();
    for parent in parents.iter().rev() {
        if remaining.peek().is_some_and(|selector| matches_one(selector, parent)) {
            remaining.next();
        }
    }
    remaining.peek().is_none()
}

/// `ThemeRule._matchesOne`: the same scope or a scope under it.
fn matches_one(selector: &str, scope: &str) -> bool {
    scope.strip_prefix(selector).is_some_and(|rest| rest.is_empty() || rest.starts_with('.'))
}

/// `ThemeRule.isMoreSpecific`: a longer scope, then more parent scopes, then longer parent scopes in order.
fn more_specific(selector: &str, other: &str) -> bool {
    let ((scope, parents), (other_scope, other_parents)) = (split_selector(selector), split_selector(other));
    let order = scope.len().cmp(&other_scope.len()).then(parents.len().cmp(&other_parents.len())).then_with(|| parents.iter().map(|parent| parent.len()).cmp(other_parents.iter().map(|parent| parent.len())));
    order.is_gt()
}

/// `JSON.stringify(settings, null, '\t')`.
fn settings_json(settings: &Value) -> String {
    let mut json = Vec::new();
    settings.serialize(&mut serde_json::Serializer::with_formatter(&mut json, serde_json::ser::PrettyFormatter::with_indent(b"\t"))).expect("a JSON value serializes");
    String::from_utf8(json).expect("serde_json writes UTF-8")
}

#[cfg(test)]
mod tests;