minor: Migrate generate_enum_variant to SyntaxEditor

This commit is contained in:
Giga Bowser 2024-12-10 13:11:33 -05:00
parent 21b376583a
commit 547f75a2ce
3 changed files with 275 additions and 229 deletions

View file

@ -1,7 +1,7 @@
use hir::{HasSource, HirDisplay, InRealFile};
use ide_db::assists::{AssistId, AssistKind};
use syntax::{
ast::{self, make, HasArgList},
ast::{self, syntax_factory::SyntaxFactory, HasArgList},
match_ast, AstNode, SyntaxNode,
};
@ -33,7 +33,7 @@ use crate::assist_context::{AssistContext, Assists};
// ```
pub(crate) fn generate_enum_variant(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let path: ast::Path = ctx.find_node_at_offset()?;
let parent = path_parent(&path)?;
let parent = PathParent::new(&path)?;
if ctx.sema.resolve_path(&path).is_some() {
// No need to generate anything if the path resolves
@ -46,14 +46,32 @@ pub(crate) fn generate_enum_variant(acc: &mut Assists, ctx: &AssistContext<'_>)
return None;
}
if let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(hir::Adt::Enum(e)))) =
let Some(hir::PathResolution::Def(hir::ModuleDef::Adt(hir::Adt::Enum(e)))) =
ctx.sema.resolve_path(&path.qualifier()?)
{
let target = path.syntax().text_range();
return add_variant_to_accumulator(acc, ctx, target, e, &name_ref, parent);
}
else {
return None;
};
None
let target = path.syntax().text_range();
let name_ref: &ast::NameRef = &name_ref;
let db = ctx.db();
let InRealFile { file_id, value: enum_node } = e.source(db)?.original_ast_node_rooted(db)?;
acc.add(
AssistId("generate_enum_variant", AssistKind::Generate),
"Generate variant",
target,
|builder| {
let mut editor = builder.make_editor(enum_node.syntax());
let make = SyntaxFactory::new();
let field_list = parent.make_field_list(ctx, &make);
let variant = make.variant(None, make.name(&name_ref.text()), field_list, None);
if let Some(it) = enum_node.variant_list() {
it.add_variant(&mut editor, &variant);
}
builder.add_file_edits(file_id, editor);
},
)
}
#[derive(Debug)]
@ -65,6 +83,20 @@ enum PathParent {
}
impl PathParent {
fn new(path: &ast::Path) -> Option<Self> {
let parent = path.syntax().parent()?;
match_ast! {
match parent {
ast::PathExpr(it) => Some(PathParent::PathExpr(it)),
ast::RecordExpr(it) => Some(PathParent::RecordExpr(it)),
ast::PathPat(it) => Some(PathParent::PathPat(it)),
ast::UseTree(it) => Some(PathParent::UseTree(it)),
_ => None
}
}
}
fn syntax(&self) -> &SyntaxNode {
match self {
PathParent::PathExpr(it) => it.syntax(),
@ -74,97 +106,49 @@ impl PathParent {
}
}
fn make_field_list(&self, ctx: &AssistContext<'_>) -> Option<ast::FieldList> {
fn make_field_list(
&self,
ctx: &AssistContext<'_>,
make: &SyntaxFactory,
) -> Option<ast::FieldList> {
let scope = ctx.sema.scope(self.syntax())?;
match self {
PathParent::PathExpr(it) => {
if let Some(call_expr) = it.syntax().parent().and_then(ast::CallExpr::cast) {
make_tuple_field_list(call_expr, ctx, &scope)
} else {
None
}
let call_expr = ast::CallExpr::cast(it.syntax().parent()?)?;
let args = call_expr.arg_list()?.args();
let tuple_fields = args.map(|arg| {
let ty =
expr_ty(ctx, make, arg, &scope).unwrap_or_else(|| make.ty_infer().into());
make.tuple_field(None, ty)
});
Some(make.tuple_field_list(tuple_fields).into())
}
PathParent::RecordExpr(it) => {
let fields = it.record_expr_field_list()?.fields();
let record_fields = fields.map(|field| {
let name = name_from_field(make, &field);
let ty = field
.expr()
.and_then(|it| expr_ty(ctx, make, it, &scope))
.unwrap_or_else(|| make.ty_infer().into());
make.record_field(None, name, ty)
});
Some(make.record_field_list(record_fields).into())
}
PathParent::RecordExpr(it) => make_record_field_list(it, ctx, &scope),
PathParent::UseTree(_) | PathParent::PathPat(_) => None,
}
}
}
fn path_parent(path: &ast::Path) -> Option<PathParent> {
let parent = path.syntax().parent()?;
match_ast! {
match parent {
ast::PathExpr(it) => Some(PathParent::PathExpr(it)),
ast::RecordExpr(it) => Some(PathParent::RecordExpr(it)),
ast::PathPat(it) => Some(PathParent::PathPat(it)),
ast::UseTree(it) => Some(PathParent::UseTree(it)),
_ => None
}
}
}
fn add_variant_to_accumulator(
acc: &mut Assists,
ctx: &AssistContext<'_>,
target: syntax::TextRange,
adt: hir::Enum,
name_ref: &ast::NameRef,
parent: PathParent,
) -> Option<()> {
let db = ctx.db();
let InRealFile { file_id, value: enum_node } = adt.source(db)?.original_ast_node_rooted(db)?;
acc.add(
AssistId("generate_enum_variant", AssistKind::Generate),
"Generate variant",
target,
|builder| {
builder.edit_file(file_id.file_id());
let node = builder.make_mut(enum_node);
let variant = make_variant(ctx, name_ref, parent);
if let Some(it) = node.variant_list() {
it.add_variant(variant.clone_for_update())
}
},
)
}
fn make_variant(
ctx: &AssistContext<'_>,
name_ref: &ast::NameRef,
parent: PathParent,
) -> ast::Variant {
let field_list = parent.make_field_list(ctx);
make::variant(None, make::name(&name_ref.text()), field_list, None)
}
fn make_record_field_list(
record: &ast::RecordExpr,
ctx: &AssistContext<'_>,
scope: &hir::SemanticsScope<'_>,
) -> Option<ast::FieldList> {
let fields = record.record_expr_field_list()?.fields();
let record_fields = fields.map(|field| {
let name = name_from_field(&field);
let ty = field
.expr()
.and_then(|it| expr_ty(ctx, it, scope))
.unwrap_or_else(make::ty_placeholder);
make::record_field(None, name, ty)
});
Some(make::record_field_list(record_fields).into())
}
fn name_from_field(field: &ast::RecordExprField) -> ast::Name {
fn name_from_field(make: &SyntaxFactory, field: &ast::RecordExprField) -> ast::Name {
let text = match field.name_ref() {
Some(it) => it.to_string(),
None => name_from_field_shorthand(field).unwrap_or("unknown".to_owned()),
};
make::name(&text)
make.name(&text)
}
fn name_from_field_shorthand(field: &ast::RecordExprField) -> Option<String> {
@ -175,27 +159,15 @@ fn name_from_field_shorthand(field: &ast::RecordExprField) -> Option<String> {
Some(path.as_single_name_ref()?.to_string())
}
fn make_tuple_field_list(
call_expr: ast::CallExpr,
ctx: &AssistContext<'_>,
scope: &hir::SemanticsScope<'_>,
) -> Option<ast::FieldList> {
let args = call_expr.arg_list()?.args();
let tuple_fields = args.map(|arg| {
let ty = expr_ty(ctx, arg, scope).unwrap_or_else(make::ty_placeholder);
make::tuple_field(None, ty)
});
Some(make::tuple_field_list(tuple_fields).into())
}
fn expr_ty(
ctx: &AssistContext<'_>,
make: &SyntaxFactory,
arg: ast::Expr,
scope: &hir::SemanticsScope<'_>,
) -> Option<ast::Type> {
let ty = ctx.sema.type_of_expr(&arg).map(|it| it.adjusted())?;
let text = ty.display_source_code(ctx.db(), scope.module().into(), false).ok()?;
Some(make::ty(&text))
Some(make.ty(&text))
}
#[cfg(test)]

View file

@ -909,30 +909,6 @@ fn get_or_insert_comma_after(syntax: &SyntaxNode) -> SyntaxToken {
}
}
impl ast::VariantList {
pub fn add_variant(&self, variant: ast::Variant) {
let (indent, position) = match self.variants().last() {
Some(last_item) => (
IndentLevel::from_node(last_item.syntax()),
Position::after(get_or_insert_comma_after(last_item.syntax())),
),
None => match self.l_curly_token() {
Some(l_curly) => {
normalize_ws_between_braces(self.syntax());
(IndentLevel::from_token(&l_curly) + 1, Position::after(&l_curly))
}
None => (IndentLevel::single(), Position::last_child_of(self.syntax())),
},
};
let elements: Vec<SyntaxElement> = vec![
make::tokens::whitespace(&format!("{}{indent}", "\n")).into(),
variant.syntax().clone().into(),
ast::make::token(T![,]).into(),
];
ted::insert_all(position, elements);
}
}
fn normalize_ws_between_braces(node: &SyntaxNode) -> Option<()> {
let l = node
.children_with_tokens()
@ -1055,8 +1031,6 @@ mod tests {
use std::fmt;
use parser::Edition;
use stdx::trim_indent;
use test_utils::assert_eq_text;
use crate::SourceFile;
@ -1170,106 +1144,4 @@ mod tests {
check("let a: u8 = 3;", "let a = 3;", None);
check("let a: = 3;", "let a = 3;", None);
}
#[test]
fn add_variant_to_empty_enum() {
let variant = make::variant(None, make::name("Bar"), None, None).clone_for_update();
check_add_variant(
r#"
enum Foo {}
"#,
r#"
enum Foo {
Bar,
}
"#,
variant,
);
}
#[test]
fn add_variant_to_non_empty_enum() {
let variant = make::variant(None, make::name("Baz"), None, None).clone_for_update();
check_add_variant(
r#"
enum Foo {
Bar,
}
"#,
r#"
enum Foo {
Bar,
Baz,
}
"#,
variant,
);
}
#[test]
fn add_variant_with_tuple_field_list() {
let variant = make::variant(
None,
make::name("Baz"),
Some(ast::FieldList::TupleFieldList(make::tuple_field_list(std::iter::once(
make::tuple_field(None, make::ty("bool")),
)))),
None,
)
.clone_for_update();
check_add_variant(
r#"
enum Foo {
Bar,
}
"#,
r#"
enum Foo {
Bar,
Baz(bool),
}
"#,
variant,
);
}
#[test]
fn add_variant_with_record_field_list() {
let variant = make::variant(
None,
make::name("Baz"),
Some(ast::FieldList::RecordFieldList(make::record_field_list(std::iter::once(
make::record_field(None, make::name("x"), make::ty("bool")),
)))),
None,
)
.clone_for_update();
check_add_variant(
r#"
enum Foo {
Bar,
}
"#,
r#"
enum Foo {
Bar,
Baz { x: bool },
}
"#,
variant,
);
}
fn check_add_variant(before: &str, expected: &str, variant: ast::Variant) {
let enum_ = ast_mut_from_text::<ast::Enum>(before);
if let Some(it) = enum_.variant_list() {
it.add_variant(variant)
}
let after = enum_.to_string();
assert_eq_text!(&trim_indent(expected.trim()), &trim_indent(after.trim()));
}
}

View file

@ -1,8 +1,12 @@
//! Structural editing for ast using `SyntaxEditor`
use crate::{
ast::make, ast::AstNode, ast::Fn, ast::GenericParam, ast::HasGenericParams, ast::HasName,
syntax_editor::Position, syntax_editor::SyntaxEditor, SyntaxKind,
ast::{
self, edit::IndentLevel, make, syntax_factory::SyntaxFactory, AstNode, Fn, GenericParam,
HasGenericParams, HasName,
},
syntax_editor::{Position, SyntaxEditor},
Direction, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, T,
};
impl SyntaxEditor {
@ -70,3 +74,201 @@ impl SyntaxEditor {
}
}
}
fn get_or_insert_comma_after(editor: &mut SyntaxEditor, syntax: &SyntaxNode) -> SyntaxToken {
let make = SyntaxFactory::without_mappings();
match syntax
.siblings_with_tokens(Direction::Next)
.filter_map(|it| it.into_token())
.find(|it| it.kind() == T![,])
{
Some(it) => it,
None => {
let comma = make.token(T![,]);
editor.insert(Position::after(syntax), &comma);
comma
}
}
}
impl ast::VariantList {
pub fn add_variant(&self, editor: &mut SyntaxEditor, variant: &ast::Variant) {
let make = SyntaxFactory::without_mappings();
let (indent, position) = match self.variants().last() {
Some(last_item) => (
IndentLevel::from_node(last_item.syntax()),
Position::after(get_or_insert_comma_after(editor, last_item.syntax())),
),
None => match self.l_curly_token() {
Some(l_curly) => {
normalize_ws_between_braces(editor, self.syntax());
(IndentLevel::from_token(&l_curly) + 1, Position::after(&l_curly))
}
None => (IndentLevel::single(), Position::last_child_of(self.syntax())),
},
};
let elements: Vec<SyntaxElement> = vec![
make.whitespace(&format!("{}{indent}", "\n")).into(),
variant.syntax().clone().into(),
make.token(T![,]).into(),
];
editor.insert_all(position, elements);
}
}
fn normalize_ws_between_braces(editor: &mut SyntaxEditor, node: &SyntaxNode) -> Option<()> {
let make = SyntaxFactory::without_mappings();
let l = node
.children_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == T!['{'])?;
let r = node
.children_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == T!['}'])?;
let indent = IndentLevel::from_node(node);
match l.next_sibling_or_token() {
Some(ws) if ws.kind() == SyntaxKind::WHITESPACE => {
if ws.next_sibling_or_token()?.into_token()? == r {
editor.replace(ws, make.whitespace(&format!("\n{indent}")));
}
}
Some(ws) if ws.kind() == T!['}'] => {
editor.insert(Position::after(l), make.whitespace(&format!("\n{indent}")));
}
_ => (),
}
Some(())
}
#[cfg(test)]
mod tests {
use parser::Edition;
use stdx::trim_indent;
use test_utils::assert_eq_text;
use crate::SourceFile;
use super::*;
fn ast_from_text<N: AstNode>(text: &str) -> N {
let parse = SourceFile::parse(text, Edition::CURRENT);
let node = match parse.tree().syntax().descendants().find_map(N::cast) {
Some(it) => it,
None => {
let node = std::any::type_name::<N>();
panic!("Failed to make ast node `{node}` from text {text}")
}
};
let node = node.clone_subtree();
assert_eq!(node.syntax().text_range().start(), 0.into());
node
}
#[test]
fn add_variant_to_empty_enum() {
let make = SyntaxFactory::without_mappings();
let variant = make.variant(None, make.name("Bar"), None, None);
check_add_variant(
r#"
enum Foo {}
"#,
r#"
enum Foo {
Bar,
}
"#,
variant,
);
}
#[test]
fn add_variant_to_non_empty_enum() {
let make = SyntaxFactory::without_mappings();
let variant = make.variant(None, make.name("Baz"), None, None);
check_add_variant(
r#"
enum Foo {
Bar,
}
"#,
r#"
enum Foo {
Bar,
Baz,
}
"#,
variant,
);
}
#[test]
fn add_variant_with_tuple_field_list() {
let make = SyntaxFactory::without_mappings();
let variant = make.variant(
None,
make.name("Baz"),
Some(make.tuple_field_list([make.tuple_field(None, make.ty("bool"))]).into()),
None,
);
check_add_variant(
r#"
enum Foo {
Bar,
}
"#,
r#"
enum Foo {
Bar,
Baz(bool),
}
"#,
variant,
);
}
#[test]
fn add_variant_with_record_field_list() {
let make = SyntaxFactory::without_mappings();
let variant = make.variant(
None,
make.name("Baz"),
Some(
make.record_field_list([make.record_field(None, make.name("x"), make.ty("bool"))])
.into(),
),
None,
);
check_add_variant(
r#"
enum Foo {
Bar,
}
"#,
r#"
enum Foo {
Bar,
Baz { x: bool },
}
"#,
variant,
);
}
fn check_add_variant(before: &str, expected: &str, variant: ast::Variant) {
let enum_ = ast_from_text::<ast::Enum>(before);
let mut editor = SyntaxEditor::new(enum_.syntax().clone());
if let Some(it) = enum_.variant_list() {
it.add_variant(&mut editor, &variant)
}
let edit = editor.finish();
let after = edit.new_root.to_string();
assert_eq_text!(&trim_indent(expected.trim()), &trim_indent(after.trim()));
}
}