Skip to content

Commit e2b664e

Browse files
fix: use raw idents in make::name{_ref} with keywords
1 parent a8da2ca commit e2b664e

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

crates/ide/src/diagnostics.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,26 @@ fn test_fn() {
653653
);
654654
}
655655

656+
#[test]
657+
fn test_fill_struct_fields_raw_ident() {
658+
check_fix(
659+
r#"
660+
struct TestStruct { r#type: u8 }
661+
662+
fn test_fn() {
663+
TestStruct { $0 };
664+
}
665+
"#,
666+
r"
667+
struct TestStruct { r#type: u8 }
668+
669+
fn test_fn() {
670+
TestStruct { r#type: () };
671+
}
672+
",
673+
);
674+
}
675+
656676
#[test]
657677
fn test_fill_struct_fields_no_diagnostic() {
658678
check_no_diagnostics(

crates/syntax/src/ast/make.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,22 @@ use stdx::format_to;
1515
use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxNode, SyntaxToken};
1616

1717
pub fn name(text: &str) -> ast::Name {
18-
ast_from_text(&format!("mod {};", text))
18+
ast_from_text(&format!("mod {}{};", raw_ident_esc(text), text))
1919
}
2020

2121
pub fn name_ref(text: &str) -> ast::NameRef {
22-
ast_from_text(&format!("fn f() {{ {}; }}", text))
22+
ast_from_text(&format!("fn f() {{ {}{}; }}", raw_ident_esc(text), text))
2323
}
24+
25+
fn raw_ident_esc(ident: &str) -> &'static str {
26+
let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
27+
if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
28+
"r#"
29+
} else {
30+
""
31+
}
32+
}
33+
2434
// FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
2535
// `expr_xxx`.
2636
pub fn ty(text: &str) -> ast::Type {

0 commit comments

Comments
 (0)