Auto-magical whitespace

This commit is contained in:
Aleksey Kladov 2021-03-16 22:51:37 +03:00
parent d733c9bdad
commit 34555593ca
2 changed files with 58 additions and 23 deletions

View file

@ -1,8 +1,9 @@
//! Primitive tree editor, ed for trees
#![allow(unused)]
use std::ops::RangeInclusive;
use crate::{SyntaxElement, SyntaxNode};
use parser::T;
use crate::{ast::make, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken};
#[derive(Debug)]
pub struct Position {
@ -42,9 +43,25 @@ impl Position {
}
}
pub fn insert_ws(position: Position, elem: impl Into<SyntaxElement>) {
insert_all_ws(position, vec![elem.into()])
}
pub fn insert(position: Position, elem: impl Into<SyntaxElement>) {
insert_all(position, vec![elem.into()])
}
pub fn insert_all_ws(position: Position, mut elements: Vec<SyntaxElement>) {
if let Some(first) = elements.first() {
if let Some(ws) = ws_before(&position, first) {
elements.insert(0, ws.into())
}
}
if let Some(last) = elements.last() {
if let Some(ws) = ws_after(&position, last) {
elements.push(ws.into())
}
}
insert_all(position, elements)
}
pub fn insert_all(position: Position, elements: Vec<SyntaxElement>) {
let (parent, index) = match position.repr {
PositionRepr::FirstChild(parent) => (parent, 0),
@ -72,7 +89,35 @@ pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>
parent.splice_children(start..end + 1, new)
}
pub fn append_child_ws(node: impl Into<SyntaxNode>, child: impl Into<SyntaxElement>) {
let position = Position::last_child_of(node);
insert_ws(position, child)
}
pub fn append_child(node: impl Into<SyntaxNode>, child: impl Into<SyntaxElement>) {
let position = Position::last_child_of(node);
insert(position, child)
}
fn ws_before(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {
let prev = match &position.repr {
PositionRepr::FirstChild(_) => return None,
PositionRepr::After(it) => it,
};
ws_between(prev, new)
}
fn ws_after(position: &Position, new: &SyntaxElement) -> Option<SyntaxToken> {
let next = match &position.repr {
PositionRepr::FirstChild(parent) => parent.first_child_or_token()?,
PositionRepr::After(sibling) => sibling.next_sibling_or_token()?,
};
ws_between(new, &next)
}
fn ws_between(left: &SyntaxElement, right: &SyntaxElement) -> Option<SyntaxToken> {
if left.kind() == SyntaxKind::WHITESPACE || right.kind() == SyntaxKind::WHITESPACE {
return None;
}
if right.kind() == T![;] || right.kind() == T![,] {
return None;
}
Some(make::tokens::single_space().into())
}