rename range -> text_range

This commit is contained in:
Aleksey Kladov 2019-07-20 12:58:27 +03:00
parent 6d5d82e412
commit f3bdbec1b6
54 changed files with 219 additions and 192 deletions

View File

@ -22,9 +22,9 @@ pub(crate) fn add_derive(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
edit.insert(node_start, "#[derive()]\n");
node_start + TextUnit::of_str("#[derive(")
}
Some(tt) => tt.syntax().range().end() - TextUnit::of_char(')'),
Some(tt) => tt.syntax().text_range().end() - TextUnit::of_char(')'),
};
edit.target(nominal.syntax().range());
edit.target(nominal.syntax().text_range());
edit.set_cursor(offset)
});
@ -37,7 +37,7 @@ fn derive_insertion_offset(nominal: &ast::NominalDef) -> Option<TextUnit> {
.syntax()
.children_with_tokens()
.find(|it| it.kind() != COMMENT && it.kind() != WHITESPACE)?;
Some(non_ws_child.range().start())
Some(non_ws_child.text_range().start())
}
#[cfg(test)]

View File

@ -16,10 +16,10 @@ pub(crate) fn add_explicit_type(mut ctx: AssistCtx<impl HirDatabase>) -> Option<
PatKind::BindPat(bind_pat) => bind_pat,
_ => return None,
};
let pat_range = pat.syntax().range();
let pat_range = pat.syntax().text_range();
// The binding must have a name
let name = pat.name()?;
let name_range = name.syntax().range();
let name_range = name.syntax().text_range();
// Assist not applicable if the type has already been specified
if stmt.syntax().children_with_tokens().any(|child| child.kind() == T![:]) {
return None;

View File

@ -11,9 +11,9 @@ pub(crate) fn add_impl(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let nominal = ctx.node_at_offset::<ast::NominalDef>()?;
let name = nominal.name()?;
ctx.add_action(AssistId("add_impl"), "add impl", |edit| {
edit.target(nominal.syntax().range());
edit.target(nominal.syntax().text_range());
let type_params = nominal.type_param_list();
let start_offset = nominal.syntax().range().end();
let start_offset = nominal.syntax().text_range().end();
let mut buf = String::new();
buf.push_str("\n\nimpl");
if let Some(type_params) = &type_params {

View File

@ -43,7 +43,7 @@ fn add_missing_impl_members_inner(
let trait_def = {
let file_id = ctx.frange.file_id;
let position = FilePosition { file_id, offset: impl_node.syntax().range().start() };
let position = FilePosition { file_id, offset: impl_node.syntax().text_range().start() };
let analyzer = hir::SourceAnalyzer::new(ctx.db, position.file_id, impl_node.syntax(), None);
resolve_target_trait_def(ctx.db, &analyzer, &impl_node)?
@ -87,7 +87,7 @@ fn add_missing_impl_members_inner(
ast_editor.append_items(items);
let first_new_item = ast_editor.ast().impl_items().nth(n_existing_items).unwrap();
let cursor_position = first_new_item.syntax().range().start();
let cursor_position = first_new_item.syntax().text_range().start();
ast_editor.into_text_edit(edit.text_edit_builder());
edit.set_cursor(cursor_position);

View File

@ -141,7 +141,7 @@ pub(crate) fn replace_node_and_indent(
if let Some(indent) = leading_indent(node) {
replace_with = reindent(&replace_with, &indent)
}
self.replace(node.range(), replace_with)
self.replace(node.text_range(), replace_with)
}
pub(crate) fn set_edit_builder(&mut self, edit: TextEditBuilder) {

View File

@ -22,7 +22,10 @@ pub fn into_text_edit(self, builder: &mut TextEditBuilder) {
// FIXME: compute a more fine-grained diff here.
// If *you* know a nice algorithm to compute diff between two syntax
// tree, tell me about it!
builder.replace(self.original_ast.syntax().range(), self.ast().syntax().text().to_string());
builder.replace(
self.original_ast.syntax().text_range(),
self.ast().syntax().text().to_string(),
);
}
pub fn ast(&self) -> &N {

View File

@ -356,7 +356,7 @@ fn best_action_for_target(
// todo: we should include even whitespace blocks as anchor candidates
let anchor = container
.children()
.find(|n| n.range().start() < anchor.range().start())
.find(|n| n.text_range().start() < anchor.text_range().start())
.or_else(|| Some(anchor));
ImportAction::add_new_use(anchor, false)
@ -418,7 +418,7 @@ fn make_assist_add_new_use(
buf.push_str(&spaces);
}
}
let position = if after { anchor.range().end() } else { anchor.range().start() };
let position = if after { anchor.text_range().end() } else { anchor.text_range().start() };
edit.insert(position, buf);
}
}
@ -434,10 +434,10 @@ fn make_assist_add_in_tree_list(
let mut buf = String::new();
let comma = last.syntax().siblings(Direction::Next).find(|n| n.kind() == T![,]);
let offset = if let Some(comma) = comma {
comma.range().end()
comma.text_range().end()
} else {
buf.push_str(",");
last.syntax().range().end()
last.syntax().text_range().end()
};
if add_self {
buf.push_str(" self")
@ -462,11 +462,11 @@ fn make_assist_add_nested_import(
if let Some(use_tree) = use_tree {
let (start, add_colon_colon) = if let Some(first_segment_to_split) = first_segment_to_split
{
(first_segment_to_split.syntax().range().start(), false)
(first_segment_to_split.syntax().text_range().start(), false)
} else {
(use_tree.syntax().range().end(), true)
(use_tree.syntax().text_range().end(), true)
};
let end = use_tree.syntax().range().end();
let end = use_tree.syntax().text_range().end();
let mut buf = String::new();
if add_colon_colon {
@ -497,8 +497,8 @@ fn apply_auto_import(
// Here we are assuming the assist will provide a correct use statement
// so we can delete the path qualifier
edit.delete(TextRange::from_to(
path.syntax().range().start(),
last.syntax().range().start(),
path.syntax().text_range().start(),
last.syntax().text_range().start(),
));
}
}

View File

@ -35,14 +35,15 @@ fn add_vis(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
if parent.children().any(|child| child.kind() == VISIBILITY) {
return None;
}
(vis_offset(&parent), keyword.range())
(vis_offset(&parent), keyword.text_range())
} else {
let ident = ctx.token_at_offset().find(|leaf| leaf.kind() == IDENT)?;
let field = ident.parent().ancestors().find_map(ast::NamedFieldDef::cast)?;
if field.name()?.syntax().range() != ident.range() && field.visibility().is_some() {
if field.name()?.syntax().text_range() != ident.text_range() && field.visibility().is_some()
{
return None;
}
(vis_offset(field.syntax()), ident.range())
(vis_offset(field.syntax()), ident.text_range())
};
ctx.add_action(AssistId("change_visibility"), "make pub(crate)", |edit| {
@ -61,25 +62,25 @@ fn vis_offset(node: &SyntaxNode) -> TextUnit {
_ => false,
})
.next()
.map(|it| it.range().start())
.unwrap_or_else(|| node.range().start())
.map(|it| it.text_range().start())
.unwrap_or_else(|| node.text_range().start())
}
fn change_vis(mut ctx: AssistCtx<impl HirDatabase>, vis: ast::Visibility) -> Option<Assist> {
if vis.syntax().text() == "pub" {
ctx.add_action(AssistId("change_visibility"), "change to pub(crate)", |edit| {
edit.target(vis.syntax().range());
edit.replace(vis.syntax().range(), "pub(crate)");
edit.set_cursor(vis.syntax().range().start())
edit.target(vis.syntax().text_range());
edit.replace(vis.syntax().text_range(), "pub(crate)");
edit.set_cursor(vis.syntax().text_range().start())
});
return ctx.build();
}
if vis.syntax().text() == "pub(crate)" {
ctx.add_action(AssistId("change_visibility"), "change to pub", |edit| {
edit.target(vis.syntax().range());
edit.replace(vis.syntax().range(), "pub");
edit.set_cursor(vis.syntax().range().start());
edit.target(vis.syntax().text_range());
edit.replace(vis.syntax().text_range(), "pub");
edit.set_cursor(vis.syntax().text_range().start());
});
return ctx.build();

View File

@ -84,8 +84,8 @@ pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<As
buf.push_str(" => (),\n");
}
buf.push_str("}");
edit.target(match_expr.syntax().range());
edit.set_cursor(expr.syntax().range().start());
edit.target(match_expr.syntax().text_range());
edit.set_cursor(expr.syntax().text_range().start());
edit.replace_node_and_indent(match_expr.syntax(), buf);
});

View File

@ -8,7 +8,7 @@ pub(crate) fn flip_binexpr(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assis
let expr = ctx.node_at_offset::<BinExpr>()?;
let lhs = expr.lhs()?.syntax().clone();
let rhs = expr.rhs()?.syntax().clone();
let op_range = expr.op_token()?.range();
let op_range = expr.op_token()?.text_range();
// The assist should be applied only if the cursor is on the operator
let cursor_in_range = ctx.frange.range.is_subrange(&op_range);
if !cursor_in_range {
@ -25,8 +25,8 @@ pub(crate) fn flip_binexpr(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assis
if let FlipAction::FlipAndReplaceOp(new_op) = action {
edit.replace(op_range, new_op);
}
edit.replace(lhs.range(), rhs.text());
edit.replace(rhs.range(), lhs.text());
edit.replace(lhs.text_range(), rhs.text());
edit.replace(rhs.text_range(), lhs.text());
});
ctx.build()

View File

@ -8,9 +8,9 @@ pub(crate) fn flip_comma(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
let prev = non_trivia_sibling(comma.clone().into(), Direction::Prev)?;
let next = non_trivia_sibling(comma.clone().into(), Direction::Next)?;
ctx.add_action(AssistId("flip_comma"), "flip comma", |edit| {
edit.target(comma.range());
edit.replace(prev.range(), next.to_string());
edit.replace(next.range(), prev.to_string());
edit.target(comma.text_range());
edit.replace(prev.text_range(), next.to_string());
edit.replace(next.text_range(), prev.to_string());
});
ctx.build()

View File

@ -22,9 +22,12 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
.next_sibling_or_token()
.and_then(|it| ast::Whitespace::cast(it.as_token()?.clone()))
{
TextRange::from_to(let_stmt.syntax().range().start(), whitespace.syntax().range().end())
TextRange::from_to(
let_stmt.syntax().text_range().start(),
whitespace.syntax().text_range().end(),
)
} else {
let_stmt.syntax().range()
let_stmt.syntax().text_range()
};
let analyzer = hir::SourceAnalyzer::new(ctx.db, ctx.frange.file_id, bind_pat.syntax(), None);
let refs = analyzer.find_all_refs(&bind_pat);

View File

@ -48,7 +48,7 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
if !full_stmt.unwrap().has_semi() {
buf.push_str(";");
}
edit.replace(expr.syntax().range(), buf);
edit.replace(expr.syntax().text_range(), buf);
} else {
buf.push_str(";");
@ -66,14 +66,14 @@ pub(crate) fn introduce_variable(mut ctx: AssistCtx<impl HirDatabase>) -> Option
buf.push_str(text);
}
edit.target(expr.syntax().range());
edit.replace(expr.syntax().range(), "var_name".to_string());
edit.insert(anchor_stmt.range().start(), buf);
edit.target(expr.syntax().text_range());
edit.replace(expr.syntax().text_range(), "var_name".to_string());
edit.insert(anchor_stmt.text_range().start(), buf);
if wrap_in_block {
edit.insert(anchor_stmt.range().end(), " }");
edit.insert(anchor_stmt.text_range().end(), " }");
}
}
edit.set_cursor(anchor_stmt.range().start() + cursor_offset);
edit.set_cursor(anchor_stmt.text_range().start() + cursor_offset);
});
ctx.build()

View File

@ -17,11 +17,11 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
let buf = format!("if {} {{ {} }}", guard_conditions.syntax().text(), arm_expr.syntax().text());
ctx.add_action(AssistId("move_guard_to_arm_body"), "move guard to arm body", |edit| {
edit.target(guard.syntax().range());
edit.target(guard.syntax().text_range());
let offseting_amount = match &space_before_guard {
Some(SyntaxElement::Token(tok)) => {
if let Some(_) = ast::Whitespace::cast(tok.clone()) {
let ele = space_before_guard.unwrap().range();
let ele = space_before_guard.unwrap().text_range();
edit.delete(ele);
ele.len()
} else {
@ -31,9 +31,11 @@ pub(crate) fn move_guard_to_arm_body(mut ctx: AssistCtx<impl HirDatabase>) -> Op
_ => TextUnit::from(0),
};
edit.delete(guard.syntax().range());
edit.delete(guard.syntax().text_range());
edit.replace_node_and_indent(arm_expr.syntax(), buf);
edit.set_cursor(arm_expr.syntax().range().start() + TextUnit::from(3) - offseting_amount);
edit.set_cursor(
arm_expr.syntax().text_range().start() + TextUnit::from(3) - offseting_amount,
);
});
ctx.build()
}
@ -62,18 +64,18 @@ pub(crate) fn move_arm_cond_to_match_guard(mut ctx: AssistCtx<impl HirDatabase>)
AssistId("move_arm_cond_to_match_guard"),
"move condition to match guard",
|edit| {
edit.target(if_expr.syntax().range());
edit.target(if_expr.syntax().text_range());
let then_only_expr = then_block.statements().next().is_none();
match &then_block.expr() {
Some(then_expr) if then_only_expr => {
edit.replace(if_expr.syntax().range(), then_expr.syntax().text())
edit.replace(if_expr.syntax().text_range(), then_expr.syntax().text())
}
_ => edit.replace(if_expr.syntax().range(), then_block.syntax().text()),
_ => edit.replace(if_expr.syntax().text_range(), then_block.syntax().text()),
}
edit.insert(last_match_pat.syntax().range().end(), buf);
edit.set_cursor(last_match_pat.syntax().range().end() + TextUnit::from(1));
edit.insert(last_match_pat.syntax().text_range().end(), buf);
edit.set_cursor(last_match_pat.syntax().text_range().end() + TextUnit::from(1));
},
);
ctx.build()

View File

@ -12,7 +12,7 @@ pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
return None;
}
let macro_range = macro_call.syntax().range();
let macro_range = macro_call.syntax().text_range();
// If the cursor is inside the macro call, we'll try to maintain the cursor
// position by subtracting the length of dbg!( from the start of the file
@ -43,7 +43,7 @@ pub(crate) fn remove_dbg(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist>
};
ctx.add_action(AssistId("remove_dbg"), "remove dbg!()", |edit| {
edit.target(macro_call.syntax().range());
edit.target(macro_call.syntax().text_range());
edit.replace(macro_range, macro_content);
edit.set_cursor(cursor_pos);
});

View File

@ -17,9 +17,9 @@ pub(crate) fn replace_if_let_with_match(mut ctx: AssistCtx<impl HirDatabase>) ->
ctx.add_action(AssistId("replace_if_let_with_match"), "replace with match", |edit| {
let match_expr = build_match_expr(expr, pat, then_block, else_block);
edit.target(if_expr.syntax().range());
edit.target(if_expr.syntax().text_range());
edit.replace_node_and_indent(if_expr.syntax(), match_expr);
edit.set_cursor(if_expr.syntax().range().start())
edit.set_cursor(if_expr.syntax().text_range().start())
});
ctx.build()

View File

@ -15,14 +15,14 @@ pub(crate) fn split_import(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assis
return None;
}
let l_curly = colon_colon.range().end();
let l_curly = colon_colon.text_range().end();
let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) {
Some(tree) => tree.syntax().range().end(),
None => top_path.syntax().range().end(),
Some(tree) => tree.syntax().text_range().end(),
None => top_path.syntax().text_range().end(),
};
ctx.add_action(AssistId("split_import"), "split import", |edit| {
edit.target(colon_colon.range());
edit.target(colon_colon.text_range());
edit.insert(l_curly, "{");
edit.insert(r_curly, "}");
edit.set_cursor(l_curly + TextUnit::of_str("{"));

View File

@ -70,7 +70,7 @@ pub fn run(verbose: bool, memory_usage: bool, path: &Path, only: Option<&str>) -
let src = f.source(db);
let original_file = src.file_id.original_file(db);
let path = db.file_relative_path(original_file);
let syntax_range = src.ast.syntax().range();
let syntax_range = src.ast.syntax().text_range();
write!(msg, " ({:?} {})", path, syntax_range).unwrap();
}
bar.set_message(&msg);

View File

@ -296,7 +296,7 @@ fn do_check_local_name(code: &str, expected_offset: u32) {
let local_name_entry = analyzer.resolve_local_name(&name_ref).unwrap();
let local_name =
local_name_entry.ptr().either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr());
assert_eq!(local_name.range(), expected_name.syntax().range());
assert_eq!(local_name.range(), expected_name.syntax().text_range());
}
#[test]

View File

@ -361,7 +361,7 @@ pub fn find_all_refs(&self, pat: &ast::BindPat) -> Vec<ReferenceDescriptor> {
})
.map(|name_ref| ReferenceDescriptor {
name: name_ref.text().to_string(),
range: name_ref.syntax().range(),
range: name_ref.syntax().text_range(),
})
.collect()
}

View File

@ -3127,7 +3127,7 @@ fn infer(content: &str) -> String {
for (syntax_ptr, ty) in &types {
let node = syntax_ptr.to_node(source_file.syntax());
let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.clone()) {
(self_param.self_kw_token().range(), "self".to_string())
(self_param.self_kw_token().text_range(), "self".to_string())
} else {
(syntax_ptr.range(), node.text().to_string().replace("\n", " "))
};

View File

@ -47,7 +47,7 @@ pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<Cal
// Number of arguments specified at the call site
let num_args_at_callsite = arg_list.args().count();
let arg_list_range = arg_list.syntax().range();
let arg_list_range = arg_list.syntax().text_range();
if !arg_list_range.contains_inclusive(position.offset) {
tested_by!(call_info_bad_offset);
return None;
@ -57,7 +57,7 @@ pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<Cal
num_args_at_callsite,
arg_list
.args()
.take_while(|arg| arg.syntax().range().end() < position.offset)
.take_while(|arg| arg.syntax().text_range().end() < position.offset)
.count(),
);

View File

@ -88,7 +88,7 @@ fn is_in_loop_body(leaf: &SyntaxToken) -> bool {
.visit::<ast::LoopExpr, _>(|it| it.loop_body())
.accept(&node);
if let Some(Some(body)) = loop_body {
if leaf.range().is_subrange(&body.syntax().range()) {
if leaf.text_range().is_subrange(&body.syntax().text_range()) {
return true;
}
}

View File

@ -26,7 +26,7 @@ pub(super) fn complete_path(acc: &mut Completions, ctx: &CompletionContext) {
if Some(module) == ctx.module {
if let Some(import) = res.import {
if let Either::A(use_tree) = module.import_source(ctx.db, import) {
if use_tree.syntax().range().contains_inclusive(ctx.offset) {
if use_tree.syntax().text_range().contains_inclusive(ctx.offset) {
// for `use self::foo<|>`, don't suggest `foo` as a completion
tested_by!(dont_complete_current_use);
continue;

View File

@ -12,7 +12,7 @@
fn postfix_snippet(ctx: &CompletionContext, label: &str, detail: &str, snippet: &str) -> Builder {
let edit = {
let receiver_range =
ctx.dot_receiver.as_ref().expect("no receiver available").syntax().range();
ctx.dot_receiver.as_ref().expect("no receiver available").syntax().text_range();
let delete_range = TextRange::from_to(receiver_range.start(), ctx.source_range().end());
let mut builder = TextEditBuilder::default();
builder.replace(delete_range, snippet.to_string());

View File

@ -78,7 +78,7 @@ pub(super) fn new(
pub(crate) fn source_range(&self) -> TextRange {
match self.token.kind() {
// workaroud when completion is triggered by trigger characters.
IDENT => self.token.range(),
IDENT => self.token.text_range(),
_ => TextRange::offset_len(self.offset, 0.into()),
}
}
@ -123,13 +123,17 @@ fn fill(&mut self, original_parse: &'a Parse<ast::SourceFile>, offset: TextUnit)
}
fn classify_name_ref(&mut self, original_file: SourceFile, name_ref: ast::NameRef) {
let name_range = name_ref.syntax().range();
let name_range = name_ref.syntax().text_range();
if name_ref.syntax().parent().and_then(ast::NamedField::cast).is_some() {
self.struct_lit_syntax = find_node_at_offset(original_file.syntax(), self.offset);
}
let top_node =
name_ref.syntax().ancestors().take_while(|it| it.range() == name_range).last().unwrap();
let top_node = name_ref
.syntax()
.ancestors()
.take_while(|it| it.text_range() == name_range)
.last()
.unwrap();
match top_node.parent().map(|it| it.kind()) {
Some(SOURCE_FILE) | Some(ITEM_LIST) => {
@ -180,23 +184,27 @@ fn classify_name_ref(&mut self, original_file: SourceFile, name_ref: ast::NameRe
.ancestors()
.find_map(|node| {
if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
return Some(stmt.syntax().range() == name_ref.syntax().range());
return Some(
stmt.syntax().text_range() == name_ref.syntax().text_range(),
);
}
if let Some(block) = ast::Block::cast(node) {
return Some(
block.expr().map(|e| e.syntax().range())
== Some(name_ref.syntax().range()),
block.expr().map(|e| e.syntax().text_range())
== Some(name_ref.syntax().text_range()),
);
}
None
})
.unwrap_or(false);
if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) {
if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
if let Some(if_expr) =
find_node_at_offset::<ast::IfExpr>(original_file.syntax(), off)
{
if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
if if_expr.syntax().text_range().end()
< name_ref.syntax().text_range().start()
{
self.after_if = true;
}
}
@ -208,14 +216,14 @@ fn classify_name_ref(&mut self, original_file: SourceFile, name_ref: ast::NameRe
// ident, so it should have the same range in the non-modified file
self.dot_receiver = field_expr
.expr()
.map(|e| e.syntax().range())
.map(|e| e.syntax().text_range())
.and_then(|r| find_node_with_range(original_file.syntax(), r));
}
if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
// As above
self.dot_receiver = method_call_expr
.expr()
.map(|e| e.syntax().range())
.map(|e| e.syntax().text_range())
.and_then(|r| find_node_with_range(original_file.syntax(), r));
self.is_call = true;
}
@ -229,6 +237,6 @@ fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Op
fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
match node.ancestors().filter_map(N::cast).next() {
None => false,
Some(n) => n.syntax().range() == node.range(),
Some(n) => n.syntax().text_range() == node.text_range(),
}
}

View File

@ -96,7 +96,7 @@ fn check_unnecessary_braces_in_use_statement(
) -> Option<()> {
let use_tree_list = ast::UseTreeList::cast(node.clone())?;
if let Some((single_use_tree,)) = use_tree_list.use_trees().collect_tuple() {
let range = use_tree_list.syntax().range();
let range = use_tree_list.syntax().text_range();
let edit =
text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(&single_use_tree)
.unwrap_or_else(|| {
@ -126,8 +126,8 @@ fn text_edit_for_remove_unnecessary_braces_with_self_in_use_statement(
) -> Option<TextEdit> {
let use_tree_list_node = single_use_tree.syntax().parent()?;
if single_use_tree.path()?.segment()?.syntax().first_child_or_token()?.kind() == T![self] {
let start = use_tree_list_node.prev_sibling_or_token()?.range().start();
let end = use_tree_list_node.range().end();
let start = use_tree_list_node.prev_sibling_or_token()?.text_range().start();
let end = use_tree_list_node.text_range().end();
let range = TextRange::from_to(start, end);
let mut edit_builder = TextEditBuilder::default();
edit_builder.delete(range);
@ -149,12 +149,12 @@ fn check_struct_shorthand_initialization(
let field_expr = expr.syntax().text().to_string();
if field_name == field_expr {
let mut edit_builder = TextEditBuilder::default();
edit_builder.delete(named_field.syntax().range());
edit_builder.insert(named_field.syntax().range().start(), field_name);
edit_builder.delete(named_field.syntax().text_range());
edit_builder.insert(named_field.syntax().text_range().start(), field_name);
let edit = edit_builder.finish();
acc.push(Diagnostic {
range: named_field.syntax().range(),
range: named_field.syntax().text_range(),
message: "Shorthand struct initialization".to_string(),
severity: Severity::WeakWarning,
fix: Some(SourceChange::source_file_edit(

View File

@ -275,7 +275,7 @@ pub(crate) fn from_named(
) -> NavigationTarget {
//FIXME: use `_` instead of empty string
let name = node.name().map(|it| it.text().clone()).unwrap_or_default();
let focus_range = node.name().map(|it| it.syntax().range());
let focus_range = node.name().map(|it| it.syntax().text_range());
NavigationTarget::from_syntax(file_id, name, focus_range, node.syntax(), docs, description)
}
@ -291,7 +291,7 @@ fn from_syntax(
file_id,
name,
kind: node.kind(),
full_range: node.range(),
full_range: node.text_range(),
focus_range,
// ptr: Some(LocalSyntaxPtr::new(node)),
container_name: None,

View File

@ -73,8 +73,8 @@ fn decl_with_detail<N: NameOwner + AttrsOwner>(
Some(StructureNode {
parent: None,
label: name.text().to_string(),
navigation_range: name.syntax().range(),
node_range: node.syntax().range(),
navigation_range: name.syntax().text_range(),
node_range: node.syntax().text_range(),
kind: node.syntax().kind(),
detail,
deprecated: node.attrs().filter_map(|x| x.as_named()).any(|x| x == "deprecated"),
@ -140,8 +140,8 @@ fn collapse_ws(node: &SyntaxNode, output: &mut String) {
let node = StructureNode {
parent: None,
label,
navigation_range: target_type.syntax().range(),
node_range: im.syntax().range(),
navigation_range: target_type.syntax().text_range(),
node_range: im.syntax().text_range(),
kind: im.syntax().kind(),
detail: None,
deprecated: false,

View File

@ -42,19 +42,20 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
TokenAtOffset::None => return None,
TokenAtOffset::Single(l) => {
if string_kinds.contains(&l.kind()) {
extend_single_word_in_comment_or_string(&l, offset).unwrap_or_else(|| l.range())
extend_single_word_in_comment_or_string(&l, offset)
.unwrap_or_else(|| l.text_range())
} else {
l.range()
l.text_range()
}
}
TokenAtOffset::Between(l, r) => pick_best(l, r).range(),
TokenAtOffset::Between(l, r) => pick_best(l, r).text_range(),
};
return Some(leaf_range);
};
let node = match find_covering_element(root, range) {
SyntaxElement::Token(token) => {
if token.range() != range {
return Some(token.range());
if token.text_range() != range {
return Some(token.text_range());
}
if let Some(comment) = ast::Comment::cast(token.clone()) {
if let Some(range) = extend_comments(comment) {
@ -65,12 +66,12 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
}
SyntaxElement::Node(node) => node,
};
if node.range() != range {
return Some(node.range());
if node.text_range() != range {
return Some(node.text_range());
}
// Using shallowest node with same range allows us to traverse siblings.
let node = node.ancestors().take_while(|n| n.range() == node.range()).last().unwrap();
let node = node.ancestors().take_while(|n| n.text_range() == node.text_range()).last().unwrap();
if node.parent().map(|n| list_kinds.contains(&n.kind())) == Some(true) {
if let Some(range) = extend_list_item(&node) {
@ -78,7 +79,7 @@ fn try_extend_selection(root: &SyntaxNode, range: TextRange) -> Option<TextRange
}
}
node.parent().map(|it| it.range())
node.parent().map(|it| it.text_range())
}
fn extend_single_word_in_comment_or_string(
@ -86,7 +87,7 @@ fn extend_single_word_in_comment_or_string(
offset: TextUnit,
) -> Option<TextRange> {
let text: &str = leaf.text();
let cursor_position: u32 = (offset - leaf.range().start()).into();
let cursor_position: u32 = (offset - leaf.text_range().start()).into();
let (before, after) = text.split_at(cursor_position as usize);
@ -104,31 +105,31 @@ fn non_word_char(c: char) -> bool {
if range.is_empty() {
None
} else {
Some(range + leaf.range().start())
Some(range + leaf.text_range().start())
}
}
fn extend_ws(root: &SyntaxNode, ws: SyntaxToken, offset: TextUnit) -> TextRange {
let ws_text = ws.text();
let suffix = TextRange::from_to(offset, ws.range().end()) - ws.range().start();
let prefix = TextRange::from_to(ws.range().start(), offset) - ws.range().start();
let suffix = TextRange::from_to(offset, ws.text_range().end()) - ws.text_range().start();
let prefix = TextRange::from_to(ws.text_range().start(), offset) - ws.text_range().start();
let ws_suffix = &ws_text.as_str()[suffix];
let ws_prefix = &ws_text.as_str()[prefix];
if ws_text.contains('\n') && !ws_suffix.contains('\n') {
if let Some(node) = ws.next_sibling_or_token() {
let start = match ws_prefix.rfind('\n') {
Some(idx) => ws.range().start() + TextUnit::from((idx + 1) as u32),
None => node.range().start(),
Some(idx) => ws.text_range().start() + TextUnit::from((idx + 1) as u32),
None => node.text_range().start(),
};
let end = if root.text().char_at(node.range().end()) == Some('\n') {
node.range().end() + TextUnit::of_char('\n')
let end = if root.text().char_at(node.text_range().end()) == Some('\n') {
node.text_range().end() + TextUnit::of_char('\n')
} else {
node.range().end()
node.text_range().end()
};
return TextRange::from_to(start, end);
}
}
ws.range()
ws.text_range()
}
fn pick_best<'a>(l: SyntaxToken, r: SyntaxToken) -> SyntaxToken {
@ -161,7 +162,7 @@ fn nearby_comma(node: &SyntaxNode, dir: Direction) -> Option<SyntaxToken> {
}
if let Some(comma_node) = nearby_comma(node, Direction::Prev) {
return Some(TextRange::from_to(comma_node.range().start(), node.range().end()));
return Some(TextRange::from_to(comma_node.text_range().start(), node.text_range().end()));
}
if let Some(comma_node) = nearby_comma(node, Direction::Next) {
// Include any following whitespace when comma if after list item.
@ -171,7 +172,7 @@ fn nearby_comma(node: &SyntaxNode, dir: Direction) -> Option<SyntaxToken> {
.filter(|node| is_single_line_ws(node))
.unwrap_or(comma_node);
return Some(TextRange::from_to(node.range().start(), final_node.range().end()));
return Some(TextRange::from_to(node.text_range().start(), final_node.text_range().end()));
}
None
@ -181,7 +182,10 @@ fn extend_comments(comment: ast::Comment) -> Option<TextRange> {
let prev = adj_comments(&comment, Direction::Prev);
let next = adj_comments(&comment, Direction::Next);
if prev != next {
Some(TextRange::from_to(prev.syntax().range().start(), next.syntax().range().end()))
Some(TextRange::from_to(
prev.syntax().text_range().start(),
next.syntax().text_range().end(),
))
} else {
None
}

View File

@ -35,7 +35,7 @@ pub(crate) fn folding_ranges(file: &SourceFile) -> Vec<Fold> {
SyntaxElement::Token(token) => token.text().contains('\n'),
};
if is_multiline {
res.push(Fold { range: element.range(), kind });
res.push(Fold { range: element.text_range(), kind });
continue;
}
}
@ -132,7 +132,7 @@ fn contiguous_range_for_group_unless(
}
if first != &last {
Some(TextRange::from_to(first.range().start(), last.range().end()))
Some(TextRange::from_to(first.text_range().start(), last.text_range().end()))
} else {
// The group consists of only one element, therefore it cannot be folded
None
@ -178,7 +178,10 @@ fn contiguous_range_for_comment(
}
if first != last {
Some(TextRange::from_to(first.syntax().range().start(), last.syntax().range().end()))
Some(TextRange::from_to(
first.syntax().text_range().start(),
last.syntax().text_range().end(),
))
} else {
// The group consists of only one element, therefore it cannot be folded
None

View File

@ -23,11 +23,11 @@ pub(crate) fn goto_definition(
let syntax = parse.tree().syntax().clone();
if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&syntax, position.offset) {
let navs = reference_definition(db, position.file_id, &name_ref).to_vec();
return Some(RangeInfo::new(name_ref.syntax().range(), navs.to_vec()));
return Some(RangeInfo::new(name_ref.syntax().text_range(), navs.to_vec()));
}
if let Some(name) = find_node_at_offset::<ast::Name>(&syntax, position.offset) {
let navs = name_definition(db, position.file_id, &name)?;
return Some(RangeInfo::new(name.syntax().range(), navs));
return Some(RangeInfo::new(name.syntax().text_range(), navs));
}
None
}

View File

@ -32,7 +32,7 @@ pub(crate) fn goto_type_definition(
let adt_def = analyzer.autoderef(db, ty).find_map(|ty| ty.as_adt().map(|adt| adt.0))?;
let nav = NavigationTarget::from_adt_def(db, adt_def);
Some(RangeInfo::new(node.range(), vec![nav]))
Some(RangeInfo::new(node.text_range(), vec![nav]))
}
#[cfg(test)]

View File

@ -172,7 +172,7 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
}
if !res.is_empty() {
range = Some(name_ref.syntax().range())
range = Some(name_ref.syntax().text_range())
}
} else if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), position.offset) {
if let Some(parent) = name.syntax().parent() {
@ -210,7 +210,7 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
}
if !res.is_empty() && range.is_none() {
range = Some(name.syntax().range());
range = Some(name.syntax().text_range());
}
}
@ -218,9 +218,9 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn
let node = ancestors_at_offset(file.syntax(), position.offset).find(|n| {
ast::Expr::cast(n.clone()).is_some() || ast::Pat::cast(n.clone()).is_some()
})?;
let frange = FileRange { file_id: position.file_id, range: node.range() };
let frange = FileRange { file_id: position.file_id, range: node.text_range() };
res.extend(type_of(db, frange).map(rust_code_markup));
range = Some(node.range());
range = Some(node.text_range());
}
let range = range?;
@ -246,7 +246,7 @@ pub(crate) fn type_of(db: &RootDatabase, frange: FileRange) -> Option<String> {
// if we picked identifier, expand to pattern/expression
let node = leaf_node
.ancestors()
.take_while(|it| it.range() == leaf_node.range())
.take_while(|it| it.text_range() == leaf_node.text_range())
.find(|it| ast::Expr::cast(it.clone()).is_some() || ast::Pat::cast(it.clone()).is_some())?;
let analyzer = hir::SourceAnalyzer::new(db, frange.file_id, &node, None);
let ty = if let Some(ty) = ast::Expr::cast(node.clone()).and_then(|e| analyzer.type_of(db, &e))

View File

@ -15,12 +15,12 @@ pub(crate) fn goto_implementation(
if let Some(nominal_def) = find_node_at_offset::<ast::NominalDef>(&syntax, position.offset) {
return Some(RangeInfo::new(
nominal_def.syntax().range(),
nominal_def.syntax().text_range(),
impls_for_def(db, &nominal_def, module)?,
));
} else if let Some(trait_def) = find_node_at_offset::<ast::TraitDef>(&syntax, position.offset) {
return Some(RangeInfo::new(
trait_def.syntax().range(),
trait_def.syntax().text_range(),
impls_for_trait(db, &trait_def, module)?,
));
}

View File

@ -28,14 +28,14 @@ pub fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
};
let mut edit = TextEditBuilder::default();
for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) {
let range = match range.intersection(&token.range()) {
let range = match range.intersection(&token.text_range()) {
Some(range) => range,
None => continue,
} - token.range().start();
} - token.text_range().start();
let text = token.text();
for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
let pos: TextUnit = (pos as u32).into();
let off = token.range().start() + range.start() + pos;
let off = token.text_range().start() + range.start() + pos;
if !edit.invalidates_offset(off) {
remove_newline(&mut edit, &token, off);
}
@ -49,7 +49,7 @@ fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextU
if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
// The node is either the first or the last in the file
let suff = &token.text()[TextRange::from_to(
offset - token.range().start() + TextUnit::of_char('\n'),
offset - token.text_range().start() + TextUnit::of_char('\n'),
TextUnit::of_str(token.text()),
)];
let spaces = suff.bytes().take_while(|&b| b == b' ').count();
@ -86,7 +86,7 @@ fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextU
let next = token.next_sibling_or_token().unwrap();
if is_trailing_comma(prev.kind(), next.kind()) {
// Removes: trailing comma, newline (incl. surrounding whitespace)
edit.delete(TextRange::from_to(prev.range().start(), token.range().end()));
edit.delete(TextRange::from_to(prev.text_range().start(), token.text_range().end()));
} else if prev.kind() == T![,] && next.kind() == T!['}'] {
// Removes: comma, newline (incl. surrounding whitespace)
let space = if let Some(left) = prev.prev_sibling_or_token() {
@ -95,7 +95,7 @@ fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextU
" "
};
edit.replace(
TextRange::from_to(prev.range().start(), token.range().end()),
TextRange::from_to(prev.text_range().start(), token.text_range().end()),
space.to_string(),
);
} else if let (Some(_), Some(next)) = (
@ -104,12 +104,12 @@ fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextU
) {
// Removes: newline (incl. surrounding whitespace), start of the next comment
edit.delete(TextRange::from_to(
token.range().start(),
next.syntax().range().start() + TextUnit::of_str(next.prefix()),
token.text_range().start(),
next.syntax().text_range().start() + TextUnit::of_str(next.prefix()),
));
} else {
// Remove newline but add a computed amount of whitespace characters
edit.replace(token.range(), compute_ws(prev.kind(), next.kind()).to_string());
edit.replace(token.text_range(), compute_ws(prev.kind(), next.kind()).to_string());
}
}
@ -125,7 +125,7 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Op
let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?;
let expr = extract_trivial_expression(&block)?;
let block_range = block_expr.syntax().range();
let block_range = block_expr.syntax().text_range();
let mut buf = expr.syntax().text().to_string();
// Match block needs to have a comma after the block
@ -143,7 +143,7 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Op
fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
let use_tree_list = ast::UseTreeList::cast(token.parent())?;
let (tree,) = use_tree_list.use_trees().collect_tuple()?;
edit.replace(use_tree_list.syntax().range(), tree.syntax().text().to_string());
edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());
Some(())
}

View File

@ -12,7 +12,7 @@ pub fn matching_brace(file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
let parent = brace_node.parent();
let matching_kind = BRACES[brace_idx ^ 1];
let matching_node = parent.children_with_tokens().find(|node| node.kind() == matching_kind)?;
Some(matching_node.range().start())
Some(matching_node.text_range().start())
}
#[cfg(test)]

View File

@ -166,7 +166,7 @@ fn rename_mod(
file_id: position.file_id,
edit: {
let mut builder = ra_text_edit::TextEditBuilder::default();
builder.replace(ast_name.syntax().range(), new_name.into());
builder.replace(ast_name.syntax().text_range(), new_name.into());
builder.finish()
},
};

View File

@ -47,7 +47,7 @@ fn runnable_fn(fn_def: ast::FnDef) -> Option<Runnable> {
} else {
return None;
};
Some(Runnable { range: fn_def.syntax().range(), kind })
Some(Runnable { range: fn_def.syntax().text_range(), kind })
}
fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Option<Runnable> {
@ -62,7 +62,7 @@ fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Opti
if !has_test_function {
return None;
}
let range = module.syntax().range();
let range = module.syntax().text_range();
let module = hir::source_binder::module_from_child_node(db, file_id, module.syntax())?;
let path = module.path_to_root(db).into_iter().rev().filter_map(|it| it.name(db)).join("::");

View File

@ -271,7 +271,7 @@ fn source_file_to_file_symbols(source_file: &SourceFile, file_id: FileId) -> Vec
fn to_symbol(node: &SyntaxNode) -> Option<(SmolStr, SyntaxNodePtr, TextRange)> {
fn decl<N: NameOwner>(node: N) -> Option<(SmolStr, SyntaxNodePtr, TextRange)> {
let name = node.name()?;
let name_range = name.syntax().range();
let name_range = name.syntax().text_range();
let name = name.text().clone();
let ptr = SyntaxNodePtr::new(node.syntax());

View File

@ -189,11 +189,11 @@ fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
if let Some(segment) = path.segment() {
if let Some(name_ref) = segment.name_ref() {
highlighted.insert(name_ref.syntax().clone().into());
let range_start = name_ref.syntax().range().start();
let mut range_end = name_ref.syntax().range().end();
let range_start = name_ref.syntax().text_range().start();
let mut range_end = name_ref.syntax().text_range().end();
for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
match sibling.kind() {
T![!] | IDENT => range_end = sibling.range().end(),
T![!] | IDENT => range_end = sibling.text_range().end(),
_ => (),
}
}
@ -209,7 +209,7 @@ fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
continue;
}
};
res.push(HighlightedRange { range: node.range(), tag, binding_hash })
res.push(HighlightedRange { range: node.text_range(), tag, binding_hash })
}
res
}
@ -239,9 +239,9 @@ fn rainbowify(seed: u64) -> String {
buf.push_str("<pre><code>");
let tokens = parse.tree().syntax().descendants_with_tokens().filter_map(|it| it.into_token());
for token in tokens {
could_intersect.retain(|it| token.range().start() <= it.range.end());
could_intersect.retain(|it| token.text_range().start() <= it.range.end());
while let Some(r) = ranges.get(frontier) {
if r.range.start() <= token.range().end() {
if r.range.start() <= token.text_range().end() {
could_intersect.push(r);
frontier += 1;
} else {
@ -251,7 +251,7 @@ fn rainbowify(seed: u64) -> String {
let text = html_escape(&token.text());
let ranges = could_intersect
.iter()
.filter(|it| token.range().is_subrange(&it.range))
.filter(|it| token.text_range().is_subrange(&it.range))
.collect::<Vec<_>>();
if ranges.is_empty() {
buf.push_str(&text);

View File

@ -45,7 +45,7 @@ fn syntax_tree_for_string(token: &SyntaxToken, text_range: TextRange) -> Option<
fn syntax_tree_for_token(node: &SyntaxToken, text_range: TextRange) -> Option<String> {
// Range of the full node
let node_range = node.range();
let node_range = node.text_range();
let text = node.text().to_string();
// We start at some point inside the node

View File

@ -24,7 +24,7 @@ pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<Sour
let prefix = comment.prefix();
if position.offset
< comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1)
< comment.syntax().text_range().start() + TextUnit::of_str(prefix) + TextUnit::from(1)
{
return None;
}
@ -45,7 +45,7 @@ pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<Sour
}
fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {
let ws = match find_token_at_offset(file.syntax(), token.range().start()) {
let ws = match find_token_at_offset(file.syntax(), token.text_range().start()) {
TokenAtOffset::Between(l, r) => {
assert!(r == *token);
l
@ -71,7 +71,7 @@ pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> {
return None;
}
if let Some(expr) = let_stmt.initializer() {
let expr_range = expr.syntax().range();
let expr_range = expr.syntax().text_range();
if expr_range.contains(eq_offset) && eq_offset != expr_range.start() {
return None;
}
@ -81,7 +81,7 @@ pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> {
} else {
return None;
}
let offset = let_stmt.syntax().range().end();
let offset = let_stmt.syntax().text_range().end();
let mut edit = TextEditBuilder::default();
edit.insert(offset, ";".to_string());
Some(edit.finish())

View File

@ -19,7 +19,7 @@ pub struct TokenMap {
pub fn ast_to_token_tree(ast: &ast::TokenTree) -> Option<(tt::Subtree, TokenMap)> {
let mut token_map = TokenMap::default();
let node = ast.syntax();
let tt = convert_tt(&mut token_map, node.range().start(), node)?;
let tt = convert_tt(&mut token_map, node.text_range().start(), node)?;
Some((tt, token_map))
}
@ -27,7 +27,7 @@ pub fn ast_to_token_tree(ast: &ast::TokenTree) -> Option<(tt::Subtree, TokenMap)
/// will consume).
pub fn syntax_node_to_token_tree(node: &SyntaxNode) -> Option<(tt::Subtree, TokenMap)> {
let mut token_map = TokenMap::default();
let tt = convert_tt(&mut token_map, node.range().start(), node)?;
let tt = convert_tt(&mut token_map, node.text_range().start(), node)?;
Some((tt, token_map))
}
@ -229,7 +229,7 @@ fn convert_tt(
|| token.kind() == IDENT
|| token.kind() == LIFETIME
{
let relative_range = token.range() - global_offset;
let relative_range = token.text_range() - global_offset;
let id = token_map.alloc(relative_range);
let text = token.text().clone();
tt::Leaf::from(tt::Ident { text, id }).into()

View File

@ -25,7 +25,7 @@ pub fn ancestors_at_offset(
) -> impl Iterator<Item = SyntaxNode> {
find_token_at_offset(node, offset)
.map(|token| token.parent().ancestors())
.kmerge_by(|node1, node2| node1.range().len() < node2.range().len())
.kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
}
/// Finds a node of specific Ast type at offset. Note that this is slightly

View File

@ -51,7 +51,7 @@ pub fn run(&self) {
for (a, b) in
new_parse.tree().syntax().descendants().zip(full_reparse.tree().syntax().descendants())
{
if (a.kind(), a.range()) != (b.kind(), b.range()) {
if (a.kind(), a.text_range()) != (b.kind(), b.text_range()) {
eprint!("original:\n{:#?}", parse.tree().syntax());
eprint!("reparsed:\n{:#?}", new_parse.tree().syntax());
eprint!("full reparse:\n{:#?}", full_reparse.tree().syntax());

View File

@ -234,7 +234,7 @@ fn foo() {
assert_eq!(expr_syntax.kind(), SyntaxKind::BIN_EXPR);
// And text range:
assert_eq!(expr_syntax.range(), TextRange::from_to(32.into(), 37.into()));
assert_eq!(expr_syntax.text_range(), TextRange::from_to(32.into(), 37.into()));
// You can get node's text as a `SyntaxText` object, which will traverse the
// tree collecting token's text:

View File

@ -46,7 +46,8 @@ fn reparse_token<'node>(
WHITESPACE | COMMENT | IDENT | STRING | RAW_STRING => {
if token.kind() == WHITESPACE || token.kind() == COMMENT {
// removing a new line may extends previous token
if token.text().to_string()[edit.delete - token.range().start()].contains('\n') {
if token.text().to_string()[edit.delete - token.text_range().start()].contains('\n')
{
return None;
}
}
@ -62,7 +63,7 @@ fn reparse_token<'node>(
return None;
}
if let Some(next_char) = root.text().char_at(token.range().end()) {
if let Some(next_char) = root.text().char_at(token.text_range().end()) {
let tokens_with_next_char = tokenize(&format!("{}{}", text, next_char));
if tokens_with_next_char.len() == 1 {
return None;
@ -70,7 +71,7 @@ fn reparse_token<'node>(
}
let new_token = GreenToken::new(rowan::SyntaxKind(token.kind().into()), text.into());
Some((token.replace_with(new_token), token.range()))
Some((token.replace_with(new_token), token.text_range()))
}
_ => None,
}
@ -90,11 +91,12 @@ fn reparse_block<'node>(
let mut tree_sink = TextTreeSink::new(&text, &tokens);
reparser.parse(&mut token_source, &mut tree_sink);
let (green, new_errors) = tree_sink.finish();
Some((node.replace_with(green), new_errors, node.range()))
Some((node.replace_with(green), new_errors, node.text_range()))
}
fn get_text_after_edit(element: SyntaxElement, edit: &AtomTextEdit) -> String {
let edit = AtomTextEdit::replace(edit.delete - element.range().start(), edit.insert.clone());
let edit =
AtomTextEdit::replace(edit.delete - element.text_range().start(), edit.insert.clone());
let text = match element {
SyntaxElement::Token(token) => token.text().to_string(),
SyntaxElement::Node(node) => node.text().to_string(),

View File

@ -12,15 +12,15 @@ pub struct SyntaxNodePtr {
impl SyntaxNodePtr {
pub fn new(node: &SyntaxNode) -> SyntaxNodePtr {
SyntaxNodePtr { range: node.range(), kind: node.kind() }
SyntaxNodePtr { range: node.text_range(), kind: node.kind() }
}
pub fn to_node(self, root: &SyntaxNode) -> SyntaxNode {
assert!(root.parent().is_none());
successors(Some(root.clone()), |node| {
node.children().find(|it| self.range.is_subrange(&it.range()))
node.children().find(|it| self.range.is_subrange(&it.text_range()))
})
.find(|it| it.range() == self.range && it.kind() == self.kind)
.find(|it| it.text_range() == self.range && it.kind() == self.kind)
.unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self))
}

View File

@ -53,7 +53,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
assert_eq!(level, 0);
Ok(())
} else {
write!(f, "{:?}@{:?}", self.kind(), self.range())
write!(f, "{:?}@{:?}", self.kind(), self.text_range())
}
}
}
@ -80,7 +80,7 @@ pub fn kind(&self) -> SyntaxKind {
self.0.kind().0.into()
}
pub fn range(&self) -> TextRange {
pub fn text_range(&self) -> TextRange {
self.0.text_range()
}
@ -291,7 +291,7 @@ fn to_green_element(element: SyntaxElement) -> rowan::GreenElement {
impl fmt::Debug for SyntaxToken {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{:?}@{:?}", self.kind(), self.range())?;
write!(fmt, "{:?}@{:?}", self.kind(), self.text_range())?;
if self.text().len() < 25 {
return write!(fmt, " {:?}", self.text());
}
@ -321,7 +321,7 @@ pub fn text(&self) -> &SmolStr {
self.0.text()
}
pub fn range(&self) -> TextRange {
pub fn text_range(&self) -> TextRange {
self.0.text_range()
}
@ -453,10 +453,10 @@ pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode> {
.ancestors()
}
pub fn range(&self) -> TextRange {
pub fn text_range(&self) -> TextRange {
match self {
SyntaxElement::Node(it) => it.range(),
SyntaxElement::Token(it) => it.range(),
SyntaxElement::Node(it) => it.text_range(),
SyntaxElement::Token(it) => it.text_range(),
}
}

View File

@ -13,7 +13,7 @@ pub struct SyntaxText {
impl SyntaxText {
pub(crate) fn new(node: SyntaxNode) -> SyntaxText {
let range = node.range();
let range = node.text_range();
SyntaxText { node, range }
}
@ -24,14 +24,14 @@ pub fn try_fold_chunks<T, F, E>(&self, init: T, mut f: F) -> Result<T, E>
self.node.descendants_with_tokens().try_fold(init, move |acc, element| {
let res = match element {
SyntaxElement::Token(token) => {
let range = match self.range.intersection(&token.range()) {
let range = match self.range.intersection(&token.text_range()) {
None => return Ok(acc),
Some(it) => it,
};
let slice = if range == token.range() {
let slice = if range == token.text_range() {
token.text()
} else {
let range = range - token.range().start();
let range = range - token.text_range().start();
&token.text()[range]
};
f(acc, slice)?

View File

@ -33,7 +33,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
if let Some(end) = text.rfind('\'') {
if let Some(without_quotes) = text.get(2..end) {
if let Err((off, err)) = unescape::unescape_byte(without_quotes) {
let off = token.range().start() + TextUnit::from_usize(off + 2);
let off = token.text_range().start() + TextUnit::from_usize(off + 2);
acc.push(SyntaxError::new(err.into(), off))
}
}
@ -43,7 +43,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
if let Some(end) = text.rfind('\'') {
if let Some(without_quotes) = text.get(1..end) {
if let Err((off, err)) = unescape::unescape_char(without_quotes) {
let off = token.range().start() + TextUnit::from_usize(off + 1);
let off = token.text_range().start() + TextUnit::from_usize(off + 1);
acc.push(SyntaxError::new(err.into(), off))
}
}
@ -55,7 +55,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
unescape::unescape_byte_str(without_quotes, &mut |range, char| {
if let Err(err) = char {
let off = range.start;
let off = token.range().start() + TextUnit::from_usize(off + 2);
let off = token.text_range().start() + TextUnit::from_usize(off + 2);
acc.push(SyntaxError::new(err.into(), off))
}
})
@ -68,7 +68,7 @@ fn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {
unescape::unescape_str(without_quotes, &mut |range, char| {
if let Err(err) = char {
let off = range.start;
let off = token.range().start() + TextUnit::from_usize(off + 1);
let off = token.text_range().start() + TextUnit::from_usize(off + 1);
acc.push(SyntaxError::new(err.into(), off))
}
})

View File

@ -16,6 +16,7 @@ pub(crate) fn validate_block_node(node: ast::Block, errors: &mut Vec<SyntaxError
_ => {}
}
}
errors
.extend(node.attrs().map(|attr| SyntaxError::new(InvalidBlockAttr, attr.syntax().range())))
errors.extend(
node.attrs().map(|attr| SyntaxError::new(InvalidBlockAttr, attr.syntax().text_range())),
)
}

View File

@ -7,7 +7,7 @@
pub(crate) fn validate_field_expr_node(node: ast::FieldExpr, errors: &mut Vec<SyntaxError>) {
if let Some(FieldKind::Index(idx)) = node.field_access() {
if idx.text().chars().any(|c| c < '0' || c > '9') {
errors.push(SyntaxError::new(InvalidTupleIndexFormat, idx.range()));
errors.push(SyntaxError::new(InvalidTupleIndexFormat, idx.text_range()));
}
}
}