rust/crates/ra_fmt/src/lib.rs

73 lines
1.9 KiB
Rust
Raw Normal View History

//! This crate provides some utilities for indenting rust code.
2019-11-12 06:41:02 -06:00
use std::iter::successors;
2019-02-03 12:26:35 -06:00
use itertools::Itertools;
2019-01-10 09:32:02 -06:00
use ra_syntax::{
2019-04-02 02:23:18 -05:00
ast::{self, AstNode, AstToken},
2019-07-18 16:35:27 -05:00
SmolStr, SyntaxKind,
SyntaxKind::*,
SyntaxNode, SyntaxToken, T,
2019-01-10 09:32:02 -06:00
};
2019-02-03 12:26:35 -06:00
pub fn reindent(text: &str, indent: &str) -> String {
let indent = format!("\n{}", indent);
text.lines().intersperse(&indent).collect()
}
2019-01-13 12:54:28 -06:00
/// If the node is on the beginning of the line, calculate indent.
2019-07-18 16:35:27 -05:00
pub fn leading_indent(node: &SyntaxNode) -> Option<SmolStr> {
2019-03-30 05:25:53 -05:00
for token in prev_tokens(node.first_token()?) {
2019-07-18 16:35:27 -05:00
if let Some(ws) = ast::Whitespace::cast(token.clone()) {
2019-01-25 02:23:15 -06:00
let ws_text = ws.text();
if let Some(pos) = ws_text.rfind('\n') {
2019-07-18 16:35:27 -05:00
return Some(ws_text[pos + 1..].into());
2019-01-25 02:23:15 -06:00
}
}
2019-03-30 05:25:53 -05:00
if token.text().contains('\n') {
2019-01-25 02:23:15 -06:00
break;
}
}
None
}
2019-03-30 05:25:53 -05:00
fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> {
2019-07-18 16:35:27 -05:00
successors(token.prev_token(), |token| token.prev_token())
2019-01-13 09:21:23 -06:00
}
2019-09-02 13:23:19 -05:00
pub fn extract_trivial_expression(expr: &ast::BlockExpr) -> Option<ast::Expr> {
let block = expr.block()?;
2019-01-10 09:32:02 -06:00
let expr = block.expr()?;
let non_trivial_children = block.syntax().children().filter(|it| match it.kind() {
2019-05-15 07:35:47 -05:00
WHITESPACE | T!['{'] | T!['}'] => false,
2019-07-18 16:35:27 -05:00
_ => it != expr.syntax(),
2019-01-10 09:32:02 -06:00
});
if non_trivial_children.count() > 0 {
return None;
}
Some(expr)
}
2019-03-30 05:25:53 -05:00
pub fn compute_ws(left: SyntaxKind, right: SyntaxKind) -> &'static str {
match left {
2019-05-15 07:35:47 -05:00
T!['('] | T!['['] => return "",
T!['{'] => {
2019-03-30 05:25:53 -05:00
if let USE_TREE = right {
2019-01-10 09:32:02 -06:00
return "";
}
}
_ => (),
}
2019-03-30 05:25:53 -05:00
match right {
2019-05-15 07:35:47 -05:00
T![')'] | T![']'] => return "",
T!['}'] => {
2019-03-30 05:25:53 -05:00
if let USE_TREE = left {
2019-01-10 09:32:02 -06:00
return "";
}
}
2019-05-15 07:35:47 -05:00
T![.] => return "",
2019-01-10 09:32:02 -06:00
_ => (),
}
" "
}