Visual Studio Code, rebuilt in Rust
Rust
//! ast.ts, concat23Trees.ts, nodeReader.ts, tokenizer.ts and parser.ts: the bracket pairs of a document as a
//! (2,3) tree, which the parse after an edit builds from the unchanged nodes of the tree before it.
use std::sync::Arc;
use super::edits::{BeforeEditPositionMapper, TextEditInfo};
use super::ids::BracketIds;
use super::length::Length;
use super::{BracketToken, LineBracket};
/// `AstNode`, immutable: a parse shares the nodes it reuses with the tree before it.
pub enum Node {
Text(Length),
Bracket { length: Length, token: Arc<BracketToken> },
/// `InvalidBracketAstNode`: a closing bracket that closes none of the brackets open around it.
Unexpected { length: Length, closes: BracketIds },
/// `PairAstNode`: `missing` are the opening brackets the closing brackets inside it lack.
Pair { length: Length, open: Arc<Node>, child: Option<Arc<Node>>, close: Option<Arc<Node>>, missing: BracketIds },
List { length: Length, height: usize, children: Vec<Arc<Node>>, missing: BracketIds },
}
impl Node {
pub fn length(&self) -> Length {
match self {
Node::Text(length) => *length,
Node::Bracket { length, .. } | Node::Unexpected { length, .. } | Node::Pair { length, .. } | Node::List { length, .. } => *length,
}
}
/// `listHeight`.
fn height(&self) -> usize {
match self {
Node::List { height, .. } => *height,
_ => 0,
}
}
/// `missingOpeningBracketIds`.
fn missing(&self) -> &BracketIds {
static NONE: BracketIds = BracketIds::EMPTY;
match self {
Node::Text(_) | Node::Bracket { .. } => &NONE,
Node::Unexpected { closes, .. } => closes,
Node::Pair { missing, .. } | Node::List { missing, .. } => missing,
}
}
/// `childrenLength`: a pair has three, the middle and the last of them maybe none.
fn child_count(&self) -> usize {
match self {
Node::Pair { .. } => 3,
Node::List { children, .. } => children.len(),
_ => 0,
}
}
fn child(&self, index: usize) -> Option<&Arc<Node>> {
match self {
Node::Pair { open, child, close, .. } => [Some(open), child.as_ref(), close.as_ref()][index],
Node::List { children, .. } => children.get(index),
_ => None,
}
}
pub fn children(&self) -> impl Iterator<Item = &Arc<Node>> {
(0..self.child_count()).filter_map(|index| self.child(index))
}
/// `canBeReused` inside the opening brackets `opened`.
fn can_be_reused(&self, opened: &BracketIds) -> bool {
match self {
Node::Text(_) => true,
Node::Bracket { .. } => false,
Node::Unexpected { closes, .. } => !opened.intersects(closes),
Node::Pair { close, missing, .. } => close.is_some() && !opened.intersects(missing),
Node::List { children, missing, .. } => {
if opened.intersects(missing) || children.is_empty() {
return false;
}
let mut last = self;
while let Node::List { children, .. } = last {
last = children.last().expect("a list in a tree holds children");
}
last.can_be_reused(opened)
}
}
}
}
/// `PairAstNode.create`.
fn pair(open: Arc<Node>, child: Option<Arc<Node>>, close: Option<Arc<Node>>) -> Arc<Node> {
let mut length = open.length();
for part in child.iter().chain(&close) {
length = length + part.length();
}
let missing = child.as_ref().map_or(BracketIds::EMPTY, |child| child.missing().clone());
Arc::new(Node::Pair { length, open, child, close, missing })
}
/// `ListAstNode.create` and `create23`: children of one height.
/// bracketPairsTree.ts `hasUnmatchedClosingBracketAfter`: a closing bracket at or after `position` that closes one of
/// `ids` and none of the brackets open around it.
pub fn has_unmatched_closing_after(root: &Arc<Node>, position: Length, ids: &BracketIds) -> bool {
if !root.missing().intersects(ids) {
return false;
}
let mut to_visit = vec![(root, Length::ZERO)];
while let Some((node, offset)) = to_visit.pop() {
if let Node::Unexpected { .. } = **node {
if offset >= position {
return true;
}
continue;
}
let mut child_offset = offset;
for child in node.children() {
let child_end = child_offset + child.length();
if child_end >= position && child.missing().intersects(ids) {
to_visit.push((child, child_offset));
}
child_offset = child_end;
}
}
false
}
pub fn list(children: Vec<Arc<Node>>) -> Arc<Node> {
let mut length = Length::ZERO;
let mut missing = BracketIds::EMPTY;
for child in &children {
length = length + child.length();
missing = missing.merge(child.missing());
}
let height = children.first().map_or(0, |first| first.height() + 1);
Arc::new(Node::List { length, height, children, missing })
}
/// `concat23Trees`: the items in order in one balanced tree, whatever their heights.
pub fn concat23_trees(items: Vec<Arc<Node>>) -> Option<Arc<Node>> {
let mut runs = Vec::new();
let mut items = items.into_iter().peekable();
while let Some(first) = items.next() {
let mut run = vec![first];
while let Some(item) = items.next_if(|item| item.height() == run[0].height()) {
run.push(item);
}
runs.extend(concat23_trees_of_same_height(run));
}
let mut runs = runs.into_iter();
let mut first = runs.next()?;
let Some(mut second) = runs.next() else { return Some(first) };
for item in runs {
if first.height().abs_diff(second.height()) <= second.height().abs_diff(item.height()) {
first = concat(&first, second);
second = item;
} else {
second = concat(&second, item);
}
}
Some(concat(&first, second))
}
/// `concat23TreesOfSameHeight`: pairs of items, the last three together when odd, until three or fewer are left.
pub fn concat23_trees_of_same_height(mut items: Vec<Arc<Node>>) -> Option<Arc<Node>> {
if items.len() <= 1 {
return items.pop();
}
while items.len() > 3 {
let count = items.len();
let mut parents = Vec::with_capacity(count / 2);
let mut items_left = items.into_iter();
for index in 0..count / 2 {
let third = if 2 * index + 3 == count { 3 } else { 2 };
parents.push(list(items_left.by_ref().take(third).collect()));
}
items = parents;
}
Some(list(items))
}
fn concat(first: &Arc<Node>, second: Arc<Node>) -> Arc<Node> {
if first.height() == second.height() {
list(vec![first.clone(), second])
} else if first.height() > second.height() {
match insert(first, second, End::Last) {
(list, None) => list,
(list, Some(sibling)) => self::list(vec![list, sibling]),
}
} else {
match insert(&second, first.clone(), End::First) {
(list, None) => list,
(list, Some(sibling)) => self::list(vec![sibling, list]),
}
}
}
#[derive(Clone, Copy)]
enum End {
First,
Last,
}
/// `append` and `prepend`: `node` added at `end` of `list` among the nodes of its height, and the sibling of `list`
/// split off from it when its level there was full.
fn insert(list: &Arc<Node>, node: Arc<Node>, end: End) -> (Arc<Node>, Option<Arc<Node>>) {
let Node::List { children, height, .. } = &**list else { unreachable!("only a list is higher than another node") };
let mut children = children.clone();
let edge = match end {
End::First => 0,
End::Last => children.len() - 1,
};
let node = if *height == node.height() + 1 {
Some(node)
} else {
let (child, sibling) = insert(&children[edge], node, end);
children[edge] = child;
sibling
};
let Some(node) = node else { return (self::list(children), None) };
if children.len() < 3 {
match end {
End::First => children.insert(0, node),
End::Last => children.push(node),
}
return (self::list(children), None);
}
let sibling = match end {
End::First => self::list(vec![node, children.remove(0)]),
End::Last => self::list(vec![children.pop().expect("a full list"), node]),
};
(self::list(children), Some(sibling))
}
/// `NodeReader`: the nodes of a tree at increasing offsets.
struct NodeReader {
next_nodes: Vec<Arc<Node>>,
offsets: Vec<Length>,
indexes: Vec<usize>,
last_offset: Length,
}
impl NodeReader {
fn new(root: Arc<Node>) -> Self {
NodeReader { next_nodes: vec![root], offsets: vec![Length::ZERO], indexes: Vec::new(), last_offset: Length::ZERO }
}
/// `readLongestNodeAt`: the longest node starting at `offset` that `predicate` accepts.
fn read_longest_node_at(&mut self, offset: Length, predicate: impl Fn(&Node) -> bool) -> Option<Arc<Node>> {
assert!(offset >= self.last_offset, "the reader reads at increasing offsets");
self.last_offset = offset;
loop {
let node = self.next_nodes.last()?.clone();
let node_offset = *self.offsets.last().expect("an offset per node");
if offset < node_offset {
return None;
}
if node_offset < offset {
if node_offset + node.length() <= offset {
self.next_node_after_current();
} else {
match next_child_index(&node, None) {
Some(index) => self.push_child(&node, index, node_offset),
None => self.next_node_after_current(),
}
}
continue;
}
if predicate(&node) {
self.next_node_after_current();
return Some(node);
}
match next_child_index(&node, None) {
Some(index) => self.push_child(&node, index, node_offset),
None => {
self.next_node_after_current();
return None;
}
}
}
}
fn push_child(&mut self, node: &Arc<Node>, index: usize, offset: Length) {
self.next_nodes.push(node.child(index).expect("a present child").clone());
self.offsets.push(offset);
self.indexes.push(index);
}
fn next_node_after_current(&mut self) {
loop {
let (Some(node), Some(offset)) = (self.next_nodes.pop(), self.offsets.pop()) else { return };
let Some(&index) = self.indexes.last() else { return };
let parent = self.next_nodes.last().expect("a parent per index");
match next_child_index(parent, Some(index)) {
Some(next) => {
let child = parent.child(next).expect("a present child").clone();
self.next_nodes.push(child);
self.offsets.push(offset + node.length());
*self.indexes.last_mut().expect("checked above") = next;
return;
}
None => {
self.indexes.pop();
}
}
}
}
}
fn next_child_index(node: &Node, after: Option<usize>) -> Option<usize> {
let start = after.map_or(0, |after| after + 1);
(start..node.child_count()).find(|&index| node.child(index).is_some())
}
/// A token of `TextBufferTokenizer`: text, or a bracket.
struct Token {
length: Length,
bracket: Option<Arc<BracketToken>>,
}
/// `TextBufferTokenizer` over each line's brackets, read from the tokens before.
struct Tokenizer<'a> {
lines: &'a [&'a [LineBracket]],
lengths: &'a [usize],
offset: Length,
peeked: Option<Token>,
}
impl Tokenizer<'_> {
fn peek(&mut self) -> Option<&Token> {
if self.peeked.is_none() {
self.peeked = self.token_at_offset();
}
self.peeked.as_ref()
}
fn read(&mut self) -> Option<Token> {
let token = self.peeked.take().or_else(|| self.token_at_offset())?;
self.offset = self.offset + token.length;
Some(token)
}
fn skip(&mut self, length: Length) {
self.peeked = None;
self.offset = self.offset + length;
}
/// A bracket, or the text up to the next one: about 30 lines or 1500 bytes at most, so edits keep the text
/// around them (`lengthHeuristic`); the length of a split never changes the pairs.
fn token_at_offset(&self) -> Option<Token> {
let last = self.lengths.len().checked_sub(1)?;
let Length { lines: mut line, columns: mut column } = self.offset;
if line > last || (line == last && column >= self.lengths[last]) {
return None;
}
let next_bracket = |line: usize, column: usize| {
let brackets = self.lines[line];
brackets.get(brackets.partition_point(|bracket| bracket.range.start < column))
};
if let Some(bracket) = next_bracket(line, column).filter(|bracket| bracket.range.start == column) {
return Some(Token { length: Length::new(0, bracket.range.len()), bracket: Some(bracket.token.clone()) });
}
let mut heuristic = 0;
loop {
if let Some(bracket) = next_bracket(line, column) {
column = bracket.range.start;
break;
}
heuristic += self.lengths[line] - column;
column = self.lengths[line];
if line == last || heuristic > 1500 {
break;
}
line += 1;
column = 0;
heuristic += 33;
if heuristic > 1000 {
break;
}
}
Some(Token { length: self.offset.until(Length::new(line, column)), bracket: None })
}
}
/// `parseDocument`: the tree of the brackets of `lines` (each line's length in `lengths`), reusing the nodes of
/// `previous` that `edits` since it left unchanged.
pub fn parse_document(lines: &[&[LineBracket]], lengths: &[usize], edits: &[TextEditInfo], previous: Option<Arc<Node>>) -> Arc<Node> {
let mut parser = Parser {
tokenizer: Tokenizer { lines, lengths, offset: Length::ZERO, peeked: None },
reader: previous.map(NodeReader::new),
mapper: BeforeEditPositionMapper::new(edits),
};
parser.parse_list(&BracketIds::EMPTY, 0).unwrap_or_else(|| list(Vec::new()))
}
struct Parser<'a> {
tokenizer: Tokenizer<'a>,
reader: Option<NodeReader>,
mapper: BeforeEditPositionMapper<'a>,
}
impl Parser<'_> {
/// The nodes up to a closing bracket of `opened`.
fn parse_list(&mut self, opened: &BracketIds, level: usize) -> Option<Arc<Node>> {
let mut items = Vec::new();
loop {
let child = match self.child_from_previous_tree(opened) {
Some(child) => child,
None => {
let Some(token) = self.tokenizer.peek() else { break };
if token.bracket.as_ref().is_some_and(|bracket| !bracket.opening && bracket.ids.intersects(opened)) {
break;
}
self.parse_child(opened, level + 1)
}
};
if matches!(&*child, Node::List { children, .. } if children.is_empty()) {
continue;
}
items.push(child);
}
match self.reader {
Some(_) => concat23_trees(items),
None => concat23_trees_of_same_height(items),
}
}
/// `tryReadChildFromCache`: the longest node of the tree before at the offset that ends before the next edit.
fn child_from_previous_tree(&mut self, opened: &BracketIds) -> Option<Arc<Node>> {
let reader = self.reader.as_mut()?;
let max_length = self.mapper.distance_to_next_change(self.tokenizer.offset);
if max_length.is_some_and(Length::is_zero) {
return None;
}
let offset = self.mapper.offset_before_change(self.tokenizer.offset);
let node = reader.read_longest_node_at(offset, |node| max_length.is_none_or(|max| node.length() < max) && node.can_be_reused(opened))?;
self.tokenizer.skip(node.length());
Some(node)
}
fn parse_child(&mut self, opened: &BracketIds, level: usize) -> Arc<Node> {
let token = self.tokenizer.read().expect("parse_list peeked a token");
let Some(bracket) = token.bracket else { return Arc::new(Node::Text(token.length)) };
if !bracket.opening {
return Arc::new(Node::Unexpected { length: token.length, closes: bracket.ids.clone() });
}
if level > 300 {
return Arc::new(Node::Text(token.length));
}
let child = self.parse_list(&opened.merge(&bracket.ids), level + 1);
let closes = self.tokenizer.peek().and_then(|next| next.bracket.as_ref()).is_some_and(|next| !next.opening && next.ids.intersects(&bracket.ids));
let close = closes.then(|| self.tokenizer.read().expect("peeked")).map(|close| Arc::new(Node::Bracket { length: close.length, token: close.bracket.expect("a bracket") }));
pair(Arc::new(Node::Bracket { length: token.length, token: bracket }), child, close)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn text(columns: usize) -> Arc<Node> {
Arc::new(Node::Text(Length::new(1, columns)))
}
/// `flattenLists`: lists of lists as one list of the other nodes.
fn flatten(node: &Arc<Node>) -> Vec<Length> {
match &**node {
Node::List { children, .. } => children.iter().flat_map(flatten).collect(),
_ => vec![node.length()],
}
}
/// The (2,3) tree invariant: each list holds two or three children of one height.
fn assert_balanced(node: &Arc<Node>) {
if let Node::List { children, height, .. } = &**node {
assert!((2..=3).contains(&children.len()), "{} children", children.len());
for child in children {
assert_eq!(child.height() + 1, *height);
assert_balanced(child);
}
}
}
/// concat23Trees.test.ts `testMerge`: the merged tree holds the leaves of the lists in order.
fn test_merge(lists: Vec<Arc<Node>>) {
let expected: Vec<Length> = lists.iter().flat_map(flatten).collect();
let Some(merged) = concat23_trees(lists) else { return assert!(expected.is_empty()) };
assert_eq!(flatten(&merged), expected);
assert_balanced(&merged);
assert_eq!(merged.length(), expected.iter().fold(Length::ZERO, |sum, length| sum + *length));
}
/// Numbered leaves, so a merge out of order fails.
fn tree(height: usize, first: &mut usize) -> Arc<Node> {
if height == 0 {
*first += 1;
return text(*first);
}
list(vec![tree(height - 1, first), tree(height - 1, first)])
}
#[test]
fn empty_list() {
test_merge(Vec::new());
}
#[test]
fn same_height_lists() {
let mut leaf = 0;
test_merge((0..5).map(|_| tree(1, &mut leaf)).collect());
}
#[test]
fn different_height_lists_1() {
let mut leaf = 0;
test_merge(vec![tree(1, &mut leaf), tree(2, &mut leaf)]);
}
#[test]
fn different_height_lists_2() {
let mut leaf = 0;
test_merge(vec![tree(2, &mut leaf), tree(1, &mut leaf)]);
}
#[test]
fn different_height_lists_3() {
let mut leaf = 0;
test_merge(vec![tree(2, &mut leaf), tree(1, &mut leaf), tree(1, &mut leaf), tree(2, &mut leaf), tree(2, &mut leaf)]);
}
#[test]
fn appending_to_full_levels_splits_them() {
let mut leaf = 0;
let mut items = vec![tree(3, &mut leaf)];
items.extend((0..7).map(|_| tree(0, &mut leaf)));
items.push(tree(2, &mut leaf));
items.extend((0..5).map(|_| tree(0, &mut leaf)));
test_merge(items);
}
}