Skip to content

Visual Studio Code, rebuilt in Rust

Rust
18.5 KB
Raw Blame
//! The text a snippet inserts and its first tab stop (snippetParser.ts, snippetSession.ts `adjustWhitespace`),
//! for snippet_session.rs.

use std::collections::HashMap;
use std::ops::Range;

use super::Indentation;

mod transform;

pub use transform::Transform;

#[derive(Clone, Debug, PartialEq)]
enum Marker {
    Text(String),
    /// A choice's options: the first is inserted as is, never re-indented.
    Choice(Vec<String>),
    Placeholder { index: u32, children: Vec<Marker>, transform: Option<Transform> },
    /// `source`: the char range of the variable in the template.
    Variable { name: String, children: Vec<Marker>, transform: Option<Transform>, source: Range<usize> },
}

/// What inserting a snippet writes, the char range in it the cursor selects, every placeholder's index and char
/// range (nested ones before the ones around them), and the options of the choice placeholders.
#[derive(Debug, PartialEq)]
pub struct SnippetText {
    pub text: String,
    pub selection: Range<usize>,
    pub stops: Vec<(u32, Range<usize>)>,
    pub choices: Vec<(u32, Vec<String>)>,
    /// The transforms of placeholders, by their position in `stops`, applied when a move leaves them.
    pub transforms: Vec<(usize, Transform)>,
    /// The insert line's leading whitespace, which the lines of a transformed value take.
    pub line_indent: String,
}

/// `SnippetParser.parse(template, true)` then `adjustWhitespace` and `resolveVariables`: unknown variables insert their
/// default. `line_indent` is the leading whitespace before the insert position, applied to every following line
/// when `adjust_indentation`.
pub fn expand(template: &str, line_indent: &str, adjust_indentation: bool, indentation: Indentation, variable: impl Fn(&str) -> Option<String>) -> SnippetText {
    let chars: Vec<char> = template.chars().collect();
    let mut position = 0;
    let mut markers = parse(&chars, &mut position, false);
    fill_in_placeholders(&mut markers);
    if has_placeholders(&markers) && !has_final_tabstop(&markers) {
        markers.push(Marker::Placeholder { index: 0, children: Vec::new(), transform: None });
    }
    let mut out = Output { text: String::new(), length: 0, stops: Vec::new(), choices: Vec::new(), transforms: Vec::new(), line_indent, adjust_indentation, indentation, variable: &variable };
    out.write(&markers);
    // snippetSession.ts `_move(true)`: the lowest index first, the final tab stop last; none puts the cursor at the end.
    let first = out.stops.iter().min_by_key(|(index, _)| if *index == 0 { u32::MAX } else { *index });
    let selection = first.map_or(out.length..out.length, |(_, range)| range.clone());
    SnippetText { text: out.text, selection, stops: out.stops, choices: out.choices, transforms: out.transforms, line_indent: line_indent.to_owned() }
}

fn parse(chars: &[char], position: &mut usize, nested: bool) -> Vec<Marker> {
    let mut markers = Vec::new();
    let mut text = String::new();
    while *position < chars.len() {
        let c = chars[*position];
        if nested && c == '}' {
            break;
        }
        if c == '\\' && matches!(chars.get(*position + 1), Some('$' | '}' | '\\')) {
            text.push(chars[*position + 1]);
            *position += 2;
            continue;
        }
        if c == '$' {
            let start = *position;
            if let Some(mut marker) = parse_dollar(chars, position) {
                if let Marker::Variable { source, .. } = &mut marker {
                    *source = start..*position;
                }
                if !text.is_empty() {
                    markers.push(Marker::Text(std::mem::take(&mut text)));
                }
                markers.push(marker);
                continue;
            }
            *position = start;
        }
        text.push(c);
        *position += 1;
    }
    if !text.is_empty() {
        markers.push(Marker::Text(text));
    }
    markers
}

/// `$1`, `$name`, `${1}`, `${1:default}`, `${1|one,two|}`, `${name}`, `${name:default}`, `${1/regex/format/}`,
/// `${name/regex/format/}`; `None` leaves the `$` as text.
fn parse_dollar(chars: &[char], position: &mut usize) -> Option<Marker> {
    *position += 1;
    let braced = chars.get(*position) == Some(&'{');
    if braced {
        *position += 1;
    }
    let index = take_while(chars, position, |c| c.is_ascii_digit());
    let name = match index.is_empty() {
        true => take_while(chars, position, |c| c == '_' || c.is_ascii_alphanumeric()),
        false => String::new(),
    };
    if index.is_empty() && !name.starts_with(|c: char| c == '_' || c.is_ascii_alphabetic()) {
        return None;
    }
    let new_marker = |children, transform| match index.parse() {
        Ok(index) => Marker::Placeholder { index, children, transform },
        Err(_) => Marker::Variable { name: name.clone(), children, transform, source: 0..0 },
    };
    if !braced {
        return Some(new_marker(Vec::new(), None));
    }
    match chars.get(*position)? {
        '}' => {
            *position += 1;
            Some(new_marker(Vec::new(), None))
        }
        '/' => {
            *position += 1;
            let transform = transform::parse(chars, position)?;
            Some(new_marker(Vec::new(), Some(transform)))
        }
        ':' => {
            *position += 1;
            let children = parse(chars, position, true);
            (chars.get(*position) == Some(&'}')).then(|| {
                *position += 1;
                new_marker(children, None)
            })
        }
        '|' if !index.is_empty() => {
            *position += 1;
            let options = parse_choice(chars, position)?;
            Some(new_marker(vec![Marker::Choice(options)], None))
        }
        _ => None,
    }
}

/// The options of `${1|one,two|}` after the first `|`, with `\,` `\|` and `\\` unescaped.
fn parse_choice(chars: &[char], position: &mut usize) -> Option<Vec<String>> {
    let mut options = vec![String::new()];
    loop {
        match (chars.get(*position)?, chars.get(*position + 1)) {
            ('\\', Some(&next @ (',' | '|' | '\\'))) => {
                options.last_mut()?.push(next);
                *position += 2;
            }
            ('|', Some('}')) => {
                *position += 2;
                return Some(options);
            }
            (',', _) => {
                options.push(String::new());
                *position += 1;
            }
            (&c, _) => {
                options.last_mut()?.push(c);
                *position += 1;
            }
        }
    }
}

fn take_while(chars: &[char], position: &mut usize, accept: impl Fn(char) -> bool) -> String {
    let start = *position;
    while chars.get(*position).is_some_and(|c| accept(*c)) {
        *position += 1;
    }
    chars[start..*position].iter().collect()
}

/// `parseFragment`: the first placeholder of an index with a value gives it to the empty ones of that index.
fn fill_in_placeholders(markers: &mut [Marker]) {
    let mut values = HashMap::new();
    collect_values(markers, &mut values);
    fill(markers, &values);
}

fn collect_values(markers: &[Marker], values: &mut HashMap<u32, Vec<Marker>>) {
    for marker in markers {
        match marker {
            Marker::Placeholder { index, children, .. } => {
                if *index != 0 && !children.is_empty() {
                    values.entry(*index).or_insert_with(|| children.clone());
                }
                collect_values(children, values);
            }
            Marker::Variable { children, .. } => collect_values(children, values),
            Marker::Text(_) | Marker::Choice(_) => {}
        }
    }
}

fn fill(markers: &mut [Marker], values: &HashMap<u32, Vec<Marker>>) {
    for marker in markers {
        match marker {
            Marker::Placeholder { index, children, .. } if children.is_empty() => {
                if let Some(value) = values.get(index) {
                    *children = value.clone();
                }
            }
            Marker::Placeholder { children, .. } | Marker::Variable { children, .. } => fill(children, values),
            Marker::Text(_) | Marker::Choice(_) => {}
        }
    }
}

/// The variables of a template, for snippetsFile.ts `SnippetBodyInsights`: like upstream, a variable's default is
/// not searched.
pub fn variable_names(template: &str) -> Vec<String> {
    let chars: Vec<char> = template.chars().collect();
    let mut position = 0;
    let mut names = Vec::new();
    let mut stack = parse(&chars, &mut position, false);
    while let Some(marker) = stack.pop() {
        match marker {
            Marker::Variable { name, .. } => names.push(name),
            Marker::Placeholder { children, .. } => stack.extend(children),
            Marker::Text(_) | Marker::Choice(_) => {}
        }
    }
    names
}

/// snippetVariables.ts `KnownSnippetVariableNames`.
const KNOWN_VARIABLE_NAMES: [&str; 39] = [
    "CURRENT_YEAR", "CURRENT_YEAR_SHORT", "CURRENT_MONTH", "CURRENT_DATE", "CURRENT_HOUR", "CURRENT_MINUTE", "CURRENT_SECOND",
    "CURRENT_MILLISECOND", "CURRENT_DAY_NAME", "CURRENT_DAY_NAME_SHORT", "CURRENT_MONTH_NAME", "CURRENT_MONTH_NAME_SHORT",
    "CURRENT_SECONDS_UNIX", "CURRENT_MILLISECONDS_UNIX", "CURRENT_TIMEZONE_OFFSET", "CURRENT_TIMEZONE_NAME", "SELECTION", "CLIPBOARD",
    "TM_SELECTED_TEXT", "TM_CURRENT_LINE", "TM_CURRENT_WORD", "TM_LINE_INDEX", "TM_LINE_NUMBER", "TM_FILENAME", "TM_FILENAME_BASE",
    "TM_DIRECTORY", "TM_DIRECTORY_BASE", "TM_FILEPATH", "CURSOR_INDEX", "CURSOR_NUMBER", "RELATIVE_FILEPATH", "BLOCK_COMMENT_START",
    "BLOCK_COMMENT_END", "LINE_COMMENT", "WORKSPACE_NAME", "WORKSPACE_FOLDER", "RANDOM", "RANDOM_HEX", "UUID",
];

/// snippetsFile.ts `SnippetBodyInsights.codeSnippet`: a variable without a default that is no known variable becomes
/// a placeholder with its name, `${foo}` as `${N:foo}`, N counting on from the highest index; `None` when there is none.
/// Rewrites the variables in the template where upstream re-serializes the whole tree: both parse the same.
pub fn code_snippet(template: &str) -> Option<String> {
    let chars: Vec<char> = template.chars().collect();
    let mut position = 0;
    let markers = parse(&chars, &mut position, false);
    let mut max_index = max_placeholder_index(&markers);
    let mut indices: HashMap<&str, u32> = HashMap::new();
    let mut replacements = Vec::new();
    // Breadth first, as upstream's `stack.shift()`, so the indices come in the same order.
    let mut queue: std::collections::VecDeque<&Marker> = markers.iter().collect();
    while let Some(marker) = queue.pop_front() {
        match marker {
            Marker::Variable { name, children, source, .. } => {
                if children.is_empty() && !KNOWN_VARIABLE_NAMES.contains(&name.as_str()) {
                    let index = *indices.entry(name).or_insert_with(|| {
                        max_index += 1;
                        max_index
                    });
                    replacements.push((source.clone(), format!("${{{index}:{name}}}")));
                }
            }
            Marker::Placeholder { children, .. } => queue.extend(children),
            Marker::Text(_) | Marker::Choice(_) => {}
        }
    }
    if replacements.is_empty() {
        return None;
    }
    replacements.sort_by_key(|(source, _)| source.start);
    let mut rewritten = String::new();
    let mut copied = 0;
    for (source, replacement) in replacements {
        rewritten.extend(&chars[copied..source.start]);
        rewritten.push_str(&replacement);
        copied = source.end;
    }
    rewritten.extend(&chars[copied..]);
    Some(rewritten)
}

/// `TextmateSnippet.placeholders`: every placeholder, variable defaults included.
fn max_placeholder_index(markers: &[Marker]) -> u32 {
    let mut max = 0;
    for marker in markers {
        match marker {
            Marker::Placeholder { index, children, .. } => max = max.max(*index).max(max_placeholder_index(children)),
            Marker::Variable { children, .. } => max = max.max(max_placeholder_index(children)),
            Marker::Text(_) | Marker::Choice(_) => {}
        }
    }
    max
}

fn has_placeholders(markers: &[Marker]) -> bool {
    markers.iter().any(|marker| match marker {
        Marker::Placeholder { .. } => true,
        Marker::Variable { children, .. } => has_placeholders(children),
        Marker::Text(_) | Marker::Choice(_) => false,
    })
}

fn has_final_tabstop(markers: &[Marker]) -> bool {
    markers.iter().any(|marker| match marker {
        Marker::Placeholder { index: 0, .. } => true,
        Marker::Placeholder { children, .. } | Marker::Variable { children, .. } => has_final_tabstop(children),
        Marker::Text(_) | Marker::Choice(_) => false,
    })
}

struct Output<'a> {
    text: String,
    /// The length of `text` in chars.
    length: usize,
    stops: Vec<(u32, Range<usize>)>,
    choices: Vec<(u32, Vec<String>)>,
    transforms: Vec<(usize, Transform)>,
    line_indent: &'a str,
    adjust_indentation: bool,
    indentation: Indentation,
    variable: &'a dyn Fn(&str) -> Option<String>,
}

impl Output<'_> {
    fn write(&mut self, markers: &[Marker]) {
        for marker in markers {
            match marker {
                Marker::Text(text) => {
                    let text = self.adjust_whitespace(text);
                    self.push(&text);
                }
                Marker::Choice(options) => self.push(&options[0]),
                Marker::Placeholder { index, children, transform } => {
                    let start = self.length;
                    if let [Marker::Choice(options)] = children.as_slice() {
                        self.choices.push((*index, options.clone()));
                    }
                    self.write(children);
                    if let Some(transform) = transform {
                        self.transforms.push((self.stops.len(), transform.clone()));
                    }
                    self.stops.push((*index, start..self.length));
                }
                // `Variable.resolve`: a transform also turns an unknown variable's empty value into text.
                Marker::Variable { name, children, transform, .. } => match (transform, (self.variable)(name)) {
                    (Some(transform), value) => self.push(&transform.resolve(&value.unwrap_or_default())),
                    (None, Some(value)) => self.push(&value),
                    (None, None) => self.write(children),
                },
            }
        }
    }

    fn push(&mut self, text: &str) {
        self.text.push_str(text);
        self.length += text.chars().count();
    }

    /// `adjustWhitespace`: every line after the first of a text marker takes the insert line's indentation in front
    /// of its own, normalized to the model's tabs or spaces. Line breaks become "\n".
    fn adjust_whitespace(&self, text: &str) -> String {
        let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
        if !self.adjust_indentation {
            return normalized;
        }
        let mut lines = normalized.split('\n');
        let mut adjusted = lines.next().unwrap_or_default().to_string();
        for line in lines {
            let own_indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
            adjusted.push('\n');
            adjusted.push_str(&normalize_indentation(&format!("{}{own_indent}", self.line_indent), self.indentation));
            adjusted.push_str(&line[own_indent.len()..]);
        }
        adjusted
    }
}

/// textModel.ts `normalizeIndentation`: leading whitespace as its visible width in tabs or spaces.
pub fn normalize_indentation(whitespace: &str, indentation: Indentation) -> String {
    let tab_size = indentation.tab_size;
    let width = whitespace.chars().fold(0, |width, c| if c == '\t' { width + tab_size - width % tab_size } else { width + 1 });
    match indentation.insert_spaces {
        true => " ".repeat(width),
        false => "\t".repeat(width / tab_size) + &" ".repeat(width % tab_size),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SPACES: Indentation = Indentation { tab_size: 4, indent_size: None, insert_spaces: true };

    fn expanded(template: &str) -> SnippetText {
        expand(template, "", true, SPACES, |name| (name == "CLIPBOARD").then(|| "clip".to_string()))
    }

    fn plain(template: &str) -> (String, Range<usize>) {
        let snippet = expanded(template);
        (snippet.text, snippet.selection)
    }

    #[test]
    fn placeholders_insert_their_text_and_the_lowest_index_is_selected() {
        assert_eq!(plain("This is a $1${2:placeholder} snippet"), ("This is a placeholder snippet".into(), 10..10));
        assert_eq!(plain("a ${2:two} ${1:one}"), ("a two one".into(), 6..9));
        assert_eq!(plain("${1:x} and $1"), ("x and x".into(), 0..1));
        assert_eq!(plain("${1|yes,no|}!"), ("yes!".into(), 0..3));
    }

    #[test]
    fn every_placeholder_and_choice_is_kept() {
        let snippet = expanded("${1:x} ${2|yes,no|} $1");
        assert_eq!(snippet.stops, [(1, 0..1), (2, 2..5), (1, 6..7), (0, 7..7)]);
        assert_eq!(snippet.choices, [(2, vec!["yes".to_string(), "no".to_string()])]);
    }

    #[test]
    fn plain_text_puts_the_cursor_at_its_end_and_escapes_unescape() {
        assert_eq!(plain("has been"), ("has been".into(), 8..8));
        assert_eq!(plain(r"cost \$5 \} \\ $"), (r"cost $5 } \ $".into(), 13..13));
        assert_eq!(plain("a$0b"), ("ab".into(), 1..1));
    }

    #[test]
    fn variables_resolve_or_insert_their_default() {
        assert_eq!(plain("running: $CLIPBOARD").0, "running: clip");
        assert_eq!(plain("${UNKNOWN:fallback} ${NOPE}").0, "fallback ");
    }

    #[test]
    fn variable_transforms_resolve_and_placeholder_transforms_wait_for_the_move() {
        let snippet = expand("${TM_FILENAME/(.*)\\..+$/$1/} ${1:a} ${1/(.*)/${1:/upcase}/} ${NOPE/^$/empty/}", "  ", true, SPACES, |name| (name == "TM_FILENAME").then(|| "main.test.ts".into()));
        assert_eq!(snippet.text, "main.test a a empty");
        assert_eq!(snippet.stops[1], (1, 12..13));
        assert_eq!(snippet.transforms.iter().map(|(stop, transform)| (*stop, transform.resolve("ab"))).collect::<Vec<_>>(), [(1, "AB".to_owned())]);
        assert_eq!(snippet.line_indent, "  ");
    }

    #[test]
    fn following_lines_take_the_insert_lines_indentation_unless_whitespace_is_kept() {
        let template = "This is line 2\n  This is line 3";
        assert_eq!(expand(template, "  ", false, SPACES, |_| None).text, template);
        assert_eq!(expand(template, "  ", true, SPACES, |_| None).text, "This is line 2\n    This is line 3");
        let tabs = Indentation { tab_size: 4, indent_size: None, insert_spaces: false };
        assert_eq!(expand("a\n\tb", "\t", true, tabs, |_| None).text, "a\n\t\tb");
    }
}