rust/crates/ra_syntax/src/algo.rs

241 lines
8.9 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
2019-07-20 12:04:34 -05:00
use std::ops::RangeInclusive;
use itertools::Itertools;
2019-09-30 01:27:26 -05:00
use ra_text_edit::TextEditBuilder;
use rustc_hash::FxHashMap;
2019-07-20 12:04:34 -05:00
use crate::{
2019-07-21 05:28:58 -05:00
AstNode, Direction, NodeOrToken, SyntaxElement, SyntaxNode, SyntaxNodePtr, TextRange, TextUnit,
2019-07-20 12:04:34 -05:00
};
2019-01-07 07:15:47 -06:00
/// Returns ancestors of the node at the offset, sorted by length. This should
/// do the right thing at an edge, e.g. when searching for expressions at `{
/// <|>foo }` we will get the name reference instead of the whole block, which
/// we would get if we just did `find_token_at_offset(...).flat_map(|t|
/// t.parent().ancestors())`.
pub fn ancestors_at_offset(
node: &SyntaxNode,
offset: TextUnit,
2019-07-18 11:23:05 -05:00
) -> impl Iterator<Item = SyntaxNode> {
2019-07-21 05:28:58 -05:00
node.token_at_offset(offset)
.map(|token| token.parent().ancestors())
2019-07-20 04:58:27 -05:00
.kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
}
2019-01-08 11:47:37 -06:00
/// Finds a node of specific Ast type at offset. Note that this is slightly
2019-01-27 07:49:02 -06:00
/// imprecise: if the cursor is strictly between two nodes of the desired type,
2019-01-08 11:47:37 -06:00
/// as in
///
/// ```no-run
/// struct Foo {}|struct Bar;
/// ```
///
/// then the shorter node will be silently preferred.
2019-07-18 11:23:05 -05:00
pub fn find_node_at_offset<N: AstNode>(syntax: &SyntaxNode, offset: TextUnit) -> Option<N> {
ancestors_at_offset(syntax, offset).find_map(N::cast)
2019-01-08 11:44:31 -06:00
}
/// Finds the first sibling in the given direction which is not `trivia`
2019-03-30 05:25:53 -05:00
pub fn non_trivia_sibling(element: SyntaxElement, direction: Direction) -> Option<SyntaxElement> {
return match element {
2019-07-20 12:04:34 -05:00
NodeOrToken::Node(node) => node.siblings_with_tokens(direction).skip(1).find(not_trivia),
NodeOrToken::Token(token) => token.siblings_with_tokens(direction).skip(1).find(not_trivia),
2019-03-30 05:25:53 -05:00
};
fn not_trivia(element: &SyntaxElement) -> bool {
match element {
2019-07-20 12:04:34 -05:00
NodeOrToken::Node(_) => true,
NodeOrToken::Token(token) => !token.kind().is_trivia(),
2019-03-30 05:25:53 -05:00
}
}
}
2019-03-30 05:25:53 -05:00
pub fn find_covering_element(root: &SyntaxNode, range: TextRange) -> SyntaxElement {
2019-07-20 12:04:34 -05:00
root.covering_element(range)
}
2019-07-21 05:08:32 -05:00
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum InsertPosition<T> {
First,
Last,
Before(T),
After(T),
}
2019-09-30 01:27:26 -05:00
pub struct TreeDiff {
replacements: FxHashMap<SyntaxElement, SyntaxElement>,
}
impl TreeDiff {
pub fn into_text_edit(&self, builder: &mut TextEditBuilder) {
for (from, to) in self.replacements.iter() {
builder.replace(from.text_range(), to.to_string())
}
}
}
2019-09-26 07:56:52 -05:00
/// Finds minimal the diff, which, applied to `from`, will result in `to`.
///
/// Specifically, returns a map whose keys are descendants of `from` and values
/// are descendants of `to`, such that `replace_descendants(from, map) == to`.
///
/// A trivial solution is a singletom map `{ from: to }`, but this function
/// tries to find a more fine-grained diff.
2019-09-30 01:27:26 -05:00
pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
2019-09-26 07:56:52 -05:00
let mut buf = FxHashMap::default();
// FIXME: this is both horrible inefficient and gives larger than
// necessary diff. I bet there's a cool algorithm to diff trees properly.
go(&mut buf, from.clone().into(), to.clone().into());
2019-09-30 01:27:26 -05:00
return TreeDiff { replacements: buf };
2019-09-26 07:56:52 -05:00
fn go(
buf: &mut FxHashMap<SyntaxElement, SyntaxElement>,
lhs: SyntaxElement,
rhs: SyntaxElement,
) {
if lhs.kind() == rhs.kind() && lhs.text_range().len() == rhs.text_range().len() {
if match (&lhs, &rhs) {
(NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => {
lhs.green() == rhs.green() || lhs.text() == rhs.text()
}
(NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(),
_ => false,
} {
return;
}
}
if let (Some(lhs), Some(rhs)) = (lhs.as_node(), rhs.as_node()) {
if lhs.children_with_tokens().count() == rhs.children_with_tokens().count() {
for (lhs, rhs) in lhs.children_with_tokens().zip(rhs.children_with_tokens()) {
go(buf, lhs, rhs)
}
return;
}
}
buf.insert(lhs, rhs);
}
}
2019-07-20 12:04:34 -05:00
/// Adds specified children (tokens or nodes) to the current node at the
/// specific position.
///
/// This is a type-unsafe low-level editing API, if you need to use it,
/// prefer to create a type-safe abstraction on top of it instead.
pub fn insert_children(
parent: &SyntaxNode,
position: InsertPosition<SyntaxElement>,
2019-09-25 09:19:16 -05:00
to_insert: &mut dyn Iterator<Item = SyntaxElement>,
2019-07-20 12:04:34 -05:00
) -> SyntaxNode {
let mut delta = TextUnit::default();
let to_insert = to_insert.map(|element| {
delta += element.text_range().len();
to_green_element(element)
});
2019-11-19 12:13:36 -06:00
let mut old_children = parent.green().children().map(|it| match it {
NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()),
NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()),
});
2019-07-20 12:04:34 -05:00
let new_children = match &position {
2019-12-04 10:15:55 -06:00
InsertPosition::First => to_insert.chain(old_children).collect::<Vec<_>>(),
InsertPosition::Last => old_children.chain(to_insert).collect::<Vec<_>>(),
2019-07-20 12:04:34 -05:00
InsertPosition::Before(anchor) | InsertPosition::After(anchor) => {
let take_anchor = if let InsertPosition::After(_) = position { 1 } else { 0 };
let split_at = position_of_child(parent, anchor.clone()) + take_anchor;
2019-11-19 12:13:36 -06:00
let before = old_children.by_ref().take(split_at).collect::<Vec<_>>();
2019-12-04 10:15:55 -06:00
before.into_iter().chain(to_insert).chain(old_children).collect::<Vec<_>>()
2019-07-20 12:04:34 -05:00
}
};
with_children(parent, new_children)
}
/// Replaces all nodes in `to_delete` with nodes from `to_insert`
///
/// This is a type-unsafe low-level editing API, if you need to use it,
/// prefer to create a type-safe abstraction on top of it instead.
pub fn replace_children(
parent: &SyntaxNode,
to_delete: RangeInclusive<SyntaxElement>,
2019-09-25 09:19:16 -05:00
to_insert: &mut dyn Iterator<Item = SyntaxElement>,
2019-07-20 12:04:34 -05:00
) -> SyntaxNode {
let start = position_of_child(parent, to_delete.start().clone());
let end = position_of_child(parent, to_delete.end().clone());
2019-11-19 12:13:36 -06:00
let mut old_children = parent.green().children().map(|it| match it {
NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()),
NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()),
});
2019-07-20 12:04:34 -05:00
2019-11-19 12:13:36 -06:00
let before = old_children.by_ref().take(start).collect::<Vec<_>>();
let new_children = before
.into_iter()
2019-07-20 12:04:34 -05:00
.chain(to_insert.map(to_green_element))
2019-11-19 12:13:36 -06:00
.chain(old_children.skip(end + 1 - start))
2019-12-04 10:15:55 -06:00
.collect::<Vec<_>>();
2019-07-20 12:04:34 -05:00
with_children(parent, new_children)
}
/// Replaces descendants in the node, according to the mapping.
///
/// This is a type-unsafe low-level editing API, if you need to use it, prefer
/// to create a type-safe abstraction on top of it instead.
pub fn replace_descendants(
parent: &SyntaxNode,
map: &FxHashMap<SyntaxElement, SyntaxElement>,
) -> SyntaxNode {
// FIXME: this could be made much faster.
2019-12-04 10:15:55 -06:00
let new_children = parent.children_with_tokens().map(|it| go(map, it)).collect::<Vec<_>>();
return with_children(parent, new_children);
fn go(
map: &FxHashMap<SyntaxElement, SyntaxElement>,
element: SyntaxElement,
) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
if let Some(replacement) = map.get(&element) {
return match replacement {
NodeOrToken::Node(it) => NodeOrToken::Node(it.green().clone()),
NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()),
};
}
match element {
NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()),
NodeOrToken::Node(it) => {
NodeOrToken::Node(replace_descendants(&it, map).green().clone())
}
}
}
}
2019-07-20 12:04:34 -05:00
fn with_children(
parent: &SyntaxNode,
2019-12-04 10:15:55 -06:00
new_children: Vec<NodeOrToken<rowan::GreenNode, rowan::GreenToken>>,
2019-07-20 12:04:34 -05:00
) -> SyntaxNode {
let len = new_children.iter().map(|it| it.text_len()).sum::<TextUnit>();
2020-01-09 09:20:05 -06:00
let new_node = rowan::GreenNode::new(rowan::SyntaxKind(parent.kind() as u16), new_children);
2019-07-21 05:28:58 -05:00
let new_root_node = parent.replace_with(new_node);
let new_root_node = SyntaxNode::new_root(new_root_node);
2019-07-20 12:04:34 -05:00
// FIXME: use a more elegant way to re-fetch the node (#1185), make
// `range` private afterwards
let mut ptr = SyntaxNodePtr::new(parent);
ptr.range = TextRange::offset_len(ptr.range().start(), len);
2019-07-21 05:28:58 -05:00
ptr.to_node(&new_root_node)
2019-07-20 12:04:34 -05:00
}
fn position_of_child(parent: &SyntaxNode, child: SyntaxElement) -> usize {
parent
.children_with_tokens()
.position(|it| it == child)
.expect("element is not a child of current element")
}
fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
match element {
NodeOrToken::Node(it) => it.green().clone().into(),
NodeOrToken::Token(it) => it.green().clone().into(),
}
2018-08-07 10:28:30 -05:00
}