]> git.lizzy.rs Git - rust.git/commitdiff
fix: use raw idents in `make::name{_ref}` with keywords
authorJonas Schievink <jonasschievink@gmail.com>
Fri, 7 May 2021 13:35:02 +0000 (15:35 +0200)
committerJonas Schievink <jonasschievink@gmail.com>
Fri, 7 May 2021 15:22:54 +0000 (17:22 +0200)
crates/ide/src/diagnostics.rs
crates/syntax/src/ast/make.rs

index b14f908b75e189963742bce6065774a8cef1ee22..273d8cfbb50f9308e1128ffdbd54873c4a7e02d2 100644 (file)
@@ -653,6 +653,26 @@ fn test_fn() {
         );
     }
 
+    #[test]
+    fn test_fill_struct_fields_raw_ident() {
+        check_fix(
+            r#"
+struct TestStruct { r#type: u8 }
+
+fn test_fn() {
+    TestStruct { $0 };
+}
+"#,
+            r"
+struct TestStruct { r#type: u8 }
+
+fn test_fn() {
+    TestStruct { r#type: ()  };
+}
+",
+        );
+    }
+
     #[test]
     fn test_fill_struct_fields_no_diagnostic() {
         check_no_diagnostics(
index 4bcea28cca8ba01bb354bdf3f54281a49c0dd158..f8b508a90eaa05517a22187ad8c609757cc4b3ae 100644 (file)
 use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxNode, SyntaxToken};
 
 pub fn name(text: &str) -> ast::Name {
-    ast_from_text(&format!("mod {};", text))
+    ast_from_text(&format!("mod {}{};", raw_ident_esc(text), text))
 }
 
 pub fn name_ref(text: &str) -> ast::NameRef {
-    ast_from_text(&format!("fn f() {{ {}; }}", text))
+    ast_from_text(&format!("fn f() {{ {}{}; }}", raw_ident_esc(text), text))
 }
+
+fn raw_ident_esc(ident: &str) -> &'static str {
+    let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
+    if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
+        "r#"
+    } else {
+        ""
+    }
+}
+
 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
 // `expr_xxx`.
 pub fn ty(text: &str) -> ast::Type {