summaryrefslogtreecommitdiffstats
path: root/src/tools/rust-analyzer/crates/syntax
diff options
context:
space:
mode:
Diffstat (limited to 'src/tools/rust-analyzer/crates/syntax')
-rw-r--r--src/tools/rust-analyzer/crates/syntax/rust.ungram1
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs193
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs415
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/ast/make.rs264
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/ast/operators.rs2
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/ast/token_ext.rs21
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/fuzz.rs5
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/hacks.rs2
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/lib.rs2
-rw-r--r--src/tools/rust-analyzer/crates/syntax/src/tests/sourcegen_ast.rs27
10 files changed, 559 insertions, 373 deletions
diff --git a/src/tools/rust-analyzer/crates/syntax/rust.ungram b/src/tools/rust-analyzer/crates/syntax/rust.ungram
index 62aa47839..894795435 100644
--- a/src/tools/rust-analyzer/crates/syntax/rust.ungram
+++ b/src/tools/rust-analyzer/crates/syntax/rust.ungram
@@ -343,7 +343,6 @@ Expr =
| Literal
| LoopExpr
| MacroExpr
-| MacroStmts
| MatchExpr
| MethodCallExpr
| ParenExpr
diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs
index e3e928aec..eadebbe8a 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/ast/edit_in_place.rs
@@ -11,7 +11,7 @@ use crate::{
ted::{self, Position},
AstNode, AstToken, Direction,
SyntaxKind::{ATTR, COMMENT, WHITESPACE},
- SyntaxNode,
+ SyntaxNode, SyntaxToken,
};
use super::HasName;
@@ -248,8 +248,12 @@ impl ast::WhereClause {
}
}
-impl ast::TypeBoundList {
- pub fn remove(&self) {
+pub trait Removable: AstNode {
+ fn remove(&self);
+}
+
+impl Removable for ast::TypeBoundList {
+ fn remove(&self) {
match self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:]) {
Some(colon) => ted::remove_all(colon..=self.syntax().clone().into()),
None => ted::remove(self.syntax()),
@@ -267,8 +271,8 @@ impl ast::PathSegment {
}
}
-impl ast::UseTree {
- pub fn remove(&self) {
+impl Removable for ast::UseTree {
+ fn remove(&self) {
for dir in [Direction::Next, Direction::Prev] {
if let Some(next_use_tree) = neighbor(self, dir) {
let separators = self
@@ -282,7 +286,9 @@ impl ast::UseTree {
}
ted::remove(self.syntax());
}
+}
+impl ast::UseTree {
pub fn get_or_create_use_tree_list(&self) -> ast::UseTreeList {
match self.use_tree_list() {
Some(it) => it,
@@ -373,8 +379,8 @@ impl ast::UseTreeList {
}
}
-impl ast::Use {
- pub fn remove(&self) {
+impl Removable for ast::Use {
+ fn remove(&self) {
let next_ws = self
.syntax()
.next_sibling_or_token()
@@ -444,8 +450,8 @@ impl ast::Fn {
}
}
-impl ast::MatchArm {
- pub fn remove(&self) {
+impl Removable for ast::MatchArm {
+ fn remove(&self) {
if let Some(sibling) = self.syntax().prev_sibling_or_token() {
if sibling.kind() == SyntaxKind::WHITESPACE {
ted::remove(sibling);
@@ -506,19 +512,7 @@ impl ast::RecordExprFieldList {
let position = match self.fields().last() {
Some(last_field) => {
- let comma = match last_field
- .syntax()
- .siblings_with_tokens(Direction::Next)
- .filter_map(|it| it.into_token())
- .find(|it| it.kind() == T![,])
- {
- Some(it) => it,
- None => {
- let comma = ast::make::token(T![,]);
- ted::insert(Position::after(last_field.syntax()), &comma);
- comma
- }
- };
+ let comma = get_or_insert_comma_after(last_field.syntax());
Position::after(comma)
}
None => match self.l_curly_token() {
@@ -579,19 +573,8 @@ impl ast::RecordPatFieldList {
let position = match self.fields().last() {
Some(last_field) => {
- let comma = match last_field
- .syntax()
- .siblings_with_tokens(Direction::Next)
- .filter_map(|it| it.into_token())
- .find(|it| it.kind() == T![,])
- {
- Some(it) => it,
- None => {
- let comma = ast::make::token(T![,]);
- ted::insert(Position::after(last_field.syntax()), &comma);
- comma
- }
- };
+ let syntax = last_field.syntax();
+ let comma = get_or_insert_comma_after(syntax);
Position::after(comma)
}
None => match self.l_curly_token() {
@@ -606,12 +589,53 @@ impl ast::RecordPatFieldList {
}
}
}
+
+fn get_or_insert_comma_after(syntax: &SyntaxNode) -> SyntaxToken {
+ let comma = match syntax
+ .siblings_with_tokens(Direction::Next)
+ .filter_map(|it| it.into_token())
+ .find(|it| it.kind() == T![,])
+ {
+ Some(it) => it,
+ None => {
+ let comma = ast::make::token(T![,]);
+ ted::insert(Position::after(syntax), &comma);
+ comma
+ }
+ };
+ comma
+}
+
impl ast::StmtList {
pub fn push_front(&self, statement: ast::Stmt) {
ted::insert(Position::after(self.l_curly_token().unwrap()), statement.syntax());
}
}
+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!("{}{}", "\n", indent)).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()
@@ -661,6 +685,9 @@ impl<N: AstNode + Clone> Indent for N {}
mod tests {
use std::fmt;
+ use stdx::trim_indent;
+ use test_utils::assert_eq_text;
+
use crate::SourceFile;
use super::*;
@@ -714,4 +741,100 @@ mod tests {
}",
);
}
+
+ #[test]
+ fn add_variant_to_empty_enum() {
+ let variant = make::variant(make::name("Bar"), 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(make::name("Baz"), 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(
+ make::name("Baz"),
+ Some(ast::FieldList::TupleFieldList(make::tuple_field_list(std::iter::once(
+ make::tuple_field(None, make::ty("bool")),
+ )))),
+ )
+ .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(
+ make::name("Baz"),
+ Some(ast::FieldList::RecordFieldList(make::record_field_list(std::iter::once(
+ make::record_field(None, make::name("x"), make::ty("bool")),
+ )))),
+ )
+ .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);
+ enum_.variant_list().map(|it| it.add_variant(variant));
+ let after = enum_.to_string();
+ assert_eq_text!(&trim_indent(expected.trim()), &trim_indent(&after.trim()));
+ }
}
diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs
index 63309a155..449402e5f 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/ast/generated/nodes.rs
@@ -1526,7 +1526,6 @@ pub enum Expr {
Literal(Literal),
LoopExpr(LoopExpr),
MacroExpr(MacroExpr),
- MacroStmts(MacroStmts),
MatchExpr(MatchExpr),
MethodCallExpr(MethodCallExpr),
ParenExpr(ParenExpr),
@@ -3169,10 +3168,7 @@ impl From<ConstArg> for GenericArg {
}
impl AstNode for GenericArg {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- TYPE_ARG | ASSOC_TYPE_ARG | LIFETIME_ARG | CONST_ARG => true,
- _ => false,
- }
+ matches!(kind, TYPE_ARG | ASSOC_TYPE_ARG | LIFETIME_ARG | CONST_ARG)
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -3237,12 +3233,23 @@ impl From<TupleType> for Type {
}
impl AstNode for Type {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- ARRAY_TYPE | DYN_TRAIT_TYPE | FN_PTR_TYPE | FOR_TYPE | IMPL_TRAIT_TYPE | INFER_TYPE
- | MACRO_TYPE | NEVER_TYPE | PAREN_TYPE | PATH_TYPE | PTR_TYPE | REF_TYPE
- | SLICE_TYPE | TUPLE_TYPE => true,
- _ => false,
- }
+ matches!(
+ kind,
+ ARRAY_TYPE
+ | DYN_TRAIT_TYPE
+ | FN_PTR_TYPE
+ | FOR_TYPE
+ | IMPL_TRAIT_TYPE
+ | INFER_TYPE
+ | MACRO_TYPE
+ | NEVER_TYPE
+ | PAREN_TYPE
+ | PATH_TYPE
+ | PTR_TYPE
+ | REF_TYPE
+ | SLICE_TYPE
+ | TUPLE_TYPE
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -3334,9 +3341,6 @@ impl From<LoopExpr> for Expr {
impl From<MacroExpr> for Expr {
fn from(node: MacroExpr) -> Expr { Expr::MacroExpr(node) }
}
-impl From<MacroStmts> for Expr {
- fn from(node: MacroStmts) -> Expr { Expr::MacroStmts(node) }
-}
impl From<MatchExpr> for Expr {
fn from(node: MatchExpr) -> Expr { Expr::MatchExpr(node) }
}
@@ -3384,15 +3388,41 @@ impl From<UnderscoreExpr> for Expr {
}
impl AstNode for Expr {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- ARRAY_EXPR | AWAIT_EXPR | BIN_EXPR | BLOCK_EXPR | BOX_EXPR | BREAK_EXPR | CALL_EXPR
- | CAST_EXPR | CLOSURE_EXPR | CONTINUE_EXPR | FIELD_EXPR | FOR_EXPR | IF_EXPR
- | INDEX_EXPR | LITERAL | LOOP_EXPR | MACRO_EXPR | MACRO_STMTS | MATCH_EXPR
- | METHOD_CALL_EXPR | PAREN_EXPR | PATH_EXPR | PREFIX_EXPR | RANGE_EXPR
- | RECORD_EXPR | REF_EXPR | RETURN_EXPR | TRY_EXPR | TUPLE_EXPR | WHILE_EXPR
- | YIELD_EXPR | LET_EXPR | UNDERSCORE_EXPR => true,
- _ => false,
- }
+ matches!(
+ kind,
+ ARRAY_EXPR
+ | AWAIT_EXPR
+ | BIN_EXPR
+ | BLOCK_EXPR
+ | BOX_EXPR
+ | BREAK_EXPR
+ | CALL_EXPR
+ | CAST_EXPR
+ | CLOSURE_EXPR
+ | CONTINUE_EXPR
+ | FIELD_EXPR
+ | FOR_EXPR
+ | IF_EXPR
+ | INDEX_EXPR
+ | LITERAL
+ | LOOP_EXPR
+ | MACRO_EXPR
+ | MATCH_EXPR
+ | METHOD_CALL_EXPR
+ | PAREN_EXPR
+ | PATH_EXPR
+ | PREFIX_EXPR
+ | RANGE_EXPR
+ | RECORD_EXPR
+ | REF_EXPR
+ | RETURN_EXPR
+ | TRY_EXPR
+ | TUPLE_EXPR
+ | WHILE_EXPR
+ | YIELD_EXPR
+ | LET_EXPR
+ | UNDERSCORE_EXPR
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -3413,7 +3443,6 @@ impl AstNode for Expr {
LITERAL => Expr::Literal(Literal { syntax }),
LOOP_EXPR => Expr::LoopExpr(LoopExpr { syntax }),
MACRO_EXPR => Expr::MacroExpr(MacroExpr { syntax }),
- MACRO_STMTS => Expr::MacroStmts(MacroStmts { syntax }),
MATCH_EXPR => Expr::MatchExpr(MatchExpr { syntax }),
METHOD_CALL_EXPR => Expr::MethodCallExpr(MethodCallExpr { syntax }),
PAREN_EXPR => Expr::ParenExpr(ParenExpr { syntax }),
@@ -3452,7 +3481,6 @@ impl AstNode for Expr {
Expr::Literal(it) => &it.syntax,
Expr::LoopExpr(it) => &it.syntax,
Expr::MacroExpr(it) => &it.syntax,
- Expr::MacroStmts(it) => &it.syntax,
Expr::MatchExpr(it) => &it.syntax,
Expr::MethodCallExpr(it) => &it.syntax,
Expr::ParenExpr(it) => &it.syntax,
@@ -3521,11 +3549,25 @@ impl From<Use> for Item {
}
impl AstNode for Item {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- CONST | ENUM | EXTERN_BLOCK | EXTERN_CRATE | FN | IMPL | MACRO_CALL | MACRO_RULES
- | MACRO_DEF | MODULE | STATIC | STRUCT | TRAIT | TYPE_ALIAS | UNION | USE => true,
- _ => false,
- }
+ matches!(
+ kind,
+ CONST
+ | ENUM
+ | EXTERN_BLOCK
+ | EXTERN_CRATE
+ | FN
+ | IMPL
+ | MACRO_CALL
+ | MACRO_RULES
+ | MACRO_DEF
+ | MODULE
+ | STATIC
+ | STRUCT
+ | TRAIT
+ | TYPE_ALIAS
+ | UNION
+ | USE
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -3629,12 +3671,25 @@ impl From<ConstBlockPat> for Pat {
}
impl AstNode for Pat {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- IDENT_PAT | BOX_PAT | REST_PAT | LITERAL_PAT | MACRO_PAT | OR_PAT | PAREN_PAT
- | PATH_PAT | WILDCARD_PAT | RANGE_PAT | RECORD_PAT | REF_PAT | SLICE_PAT
- | TUPLE_PAT | TUPLE_STRUCT_PAT | CONST_BLOCK_PAT => true,
- _ => false,
- }
+ matches!(
+ kind,
+ IDENT_PAT
+ | BOX_PAT
+ | REST_PAT
+ | LITERAL_PAT
+ | MACRO_PAT
+ | OR_PAT
+ | PAREN_PAT
+ | PATH_PAT
+ | WILDCARD_PAT
+ | RANGE_PAT
+ | RECORD_PAT
+ | REF_PAT
+ | SLICE_PAT
+ | TUPLE_PAT
+ | TUPLE_STRUCT_PAT
+ | CONST_BLOCK_PAT
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -3686,12 +3741,7 @@ impl From<TupleFieldList> for FieldList {
fn from(node: TupleFieldList) -> FieldList { FieldList::TupleFieldList(node) }
}
impl AstNode for FieldList {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- RECORD_FIELD_LIST | TUPLE_FIELD_LIST => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, RECORD_FIELD_LIST | TUPLE_FIELD_LIST) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
RECORD_FIELD_LIST => FieldList::RecordFieldList(RecordFieldList { syntax }),
@@ -3717,12 +3767,7 @@ impl From<Union> for Adt {
fn from(node: Union) -> Adt { Adt::Union(node) }
}
impl AstNode for Adt {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- ENUM | STRUCT | UNION => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, ENUM | STRUCT | UNION) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
ENUM => Adt::Enum(Enum { syntax }),
@@ -3753,12 +3798,7 @@ impl From<TypeAlias> for AssocItem {
fn from(node: TypeAlias) -> AssocItem { AssocItem::TypeAlias(node) }
}
impl AstNode for AssocItem {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- CONST | FN | MACRO_CALL | TYPE_ALIAS => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, CONST | FN | MACRO_CALL | TYPE_ALIAS) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
CONST => AssocItem::Const(Const { syntax }),
@@ -3791,12 +3831,7 @@ impl From<TypeAlias> for ExternItem {
fn from(node: TypeAlias) -> ExternItem { ExternItem::TypeAlias(node) }
}
impl AstNode for ExternItem {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- FN | MACRO_CALL | STATIC | TYPE_ALIAS => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, FN | MACRO_CALL | STATIC | TYPE_ALIAS) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
FN => ExternItem::Fn(Fn { syntax }),
@@ -3827,10 +3862,7 @@ impl From<TypeParam> for GenericParam {
}
impl AstNode for GenericParam {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- CONST_PARAM | LIFETIME_PARAM | TYPE_PARAM => true,
- _ => false,
- }
+ matches!(kind, CONST_PARAM | LIFETIME_PARAM | TYPE_PARAM)
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -3856,12 +3888,7 @@ impl AnyHasArgList {
}
}
impl AstNode for AnyHasArgList {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- CALL_EXPR | METHOD_CALL_EXPR => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, CALL_EXPR | METHOD_CALL_EXPR) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasArgList { syntax })
}
@@ -3875,76 +3902,76 @@ impl AnyHasAttrs {
}
impl AstNode for AnyHasAttrs {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
+ matches!(
+ kind,
MACRO_CALL
- | SOURCE_FILE
- | CONST
- | ENUM
- | EXTERN_BLOCK
- | EXTERN_CRATE
- | FN
- | IMPL
- | MACRO_RULES
- | MACRO_DEF
- | MODULE
- | STATIC
- | STRUCT
- | TRAIT
- | TYPE_ALIAS
- | UNION
- | USE
- | ITEM_LIST
- | BLOCK_EXPR
- | SELF_PARAM
- | PARAM
- | RECORD_FIELD
- | TUPLE_FIELD
- | VARIANT
- | ASSOC_ITEM_LIST
- | EXTERN_ITEM_LIST
- | CONST_PARAM
- | LIFETIME_PARAM
- | TYPE_PARAM
- | LET_STMT
- | ARRAY_EXPR
- | AWAIT_EXPR
- | BIN_EXPR
- | BOX_EXPR
- | BREAK_EXPR
- | CALL_EXPR
- | CAST_EXPR
- | CLOSURE_EXPR
- | CONTINUE_EXPR
- | FIELD_EXPR
- | FOR_EXPR
- | IF_EXPR
- | INDEX_EXPR
- | LITERAL
- | LOOP_EXPR
- | MATCH_EXPR
- | METHOD_CALL_EXPR
- | PAREN_EXPR
- | PATH_EXPR
- | PREFIX_EXPR
- | RANGE_EXPR
- | REF_EXPR
- | RETURN_EXPR
- | TRY_EXPR
- | TUPLE_EXPR
- | WHILE_EXPR
- | YIELD_EXPR
- | LET_EXPR
- | UNDERSCORE_EXPR
- | STMT_LIST
- | RECORD_EXPR_FIELD_LIST
- | RECORD_EXPR_FIELD
- | MATCH_ARM_LIST
- | MATCH_ARM
- | IDENT_PAT
- | REST_PAT
- | RECORD_PAT_FIELD => true,
- _ => false,
- }
+ | SOURCE_FILE
+ | CONST
+ | ENUM
+ | EXTERN_BLOCK
+ | EXTERN_CRATE
+ | FN
+ | IMPL
+ | MACRO_RULES
+ | MACRO_DEF
+ | MODULE
+ | STATIC
+ | STRUCT
+ | TRAIT
+ | TYPE_ALIAS
+ | UNION
+ | USE
+ | ITEM_LIST
+ | BLOCK_EXPR
+ | SELF_PARAM
+ | PARAM
+ | RECORD_FIELD
+ | TUPLE_FIELD
+ | VARIANT
+ | ASSOC_ITEM_LIST
+ | EXTERN_ITEM_LIST
+ | CONST_PARAM
+ | LIFETIME_PARAM
+ | TYPE_PARAM
+ | LET_STMT
+ | ARRAY_EXPR
+ | AWAIT_EXPR
+ | BIN_EXPR
+ | BOX_EXPR
+ | BREAK_EXPR
+ | CALL_EXPR
+ | CAST_EXPR
+ | CLOSURE_EXPR
+ | CONTINUE_EXPR
+ | FIELD_EXPR
+ | FOR_EXPR
+ | IF_EXPR
+ | INDEX_EXPR
+ | LITERAL
+ | LOOP_EXPR
+ | MATCH_EXPR
+ | METHOD_CALL_EXPR
+ | PAREN_EXPR
+ | PATH_EXPR
+ | PREFIX_EXPR
+ | RANGE_EXPR
+ | REF_EXPR
+ | RETURN_EXPR
+ | TRY_EXPR
+ | TUPLE_EXPR
+ | WHILE_EXPR
+ | YIELD_EXPR
+ | LET_EXPR
+ | UNDERSCORE_EXPR
+ | STMT_LIST
+ | RECORD_EXPR_FIELD_LIST
+ | RECORD_EXPR_FIELD
+ | MATCH_ARM_LIST
+ | MATCH_ARM
+ | IDENT_PAT
+ | REST_PAT
+ | RECORD_PAT_FIELD
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasAttrs { syntax })
@@ -3959,12 +3986,29 @@ impl AnyHasDocComments {
}
impl AstNode for AnyHasDocComments {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- MACRO_CALL | SOURCE_FILE | CONST | ENUM | EXTERN_BLOCK | EXTERN_CRATE | FN | IMPL
- | MACRO_RULES | MACRO_DEF | MODULE | STATIC | STRUCT | TRAIT | TYPE_ALIAS | UNION
- | USE | RECORD_FIELD | TUPLE_FIELD | VARIANT => true,
- _ => false,
- }
+ matches!(
+ kind,
+ MACRO_CALL
+ | SOURCE_FILE
+ | CONST
+ | ENUM
+ | EXTERN_BLOCK
+ | EXTERN_CRATE
+ | FN
+ | IMPL
+ | MACRO_RULES
+ | MACRO_DEF
+ | MODULE
+ | STATIC
+ | STRUCT
+ | TRAIT
+ | TYPE_ALIAS
+ | UNION
+ | USE
+ | RECORD_FIELD
+ | TUPLE_FIELD
+ | VARIANT
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasDocComments { syntax })
@@ -3979,10 +4023,7 @@ impl AnyHasGenericParams {
}
impl AstNode for AnyHasGenericParams {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- ENUM | FN | IMPL | STRUCT | TRAIT | TYPE_ALIAS | UNION => true,
- _ => false,
- }
+ matches!(kind, ENUM | FN | IMPL | STRUCT | TRAIT | TYPE_ALIAS | UNION)
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasGenericParams { syntax })
@@ -3996,12 +4037,7 @@ impl AnyHasLoopBody {
}
}
impl AstNode for AnyHasLoopBody {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- FOR_EXPR | LOOP_EXPR | WHILE_EXPR => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, FOR_EXPR | LOOP_EXPR | WHILE_EXPR) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasLoopBody { syntax })
}
@@ -4014,12 +4050,7 @@ impl AnyHasModuleItem {
}
}
impl AstNode for AnyHasModuleItem {
- fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- MACRO_ITEMS | SOURCE_FILE | ITEM_LIST => true,
- _ => false,
- }
- }
+ fn can_cast(kind: SyntaxKind) -> bool { matches!(kind, MACRO_ITEMS | SOURCE_FILE | ITEM_LIST) }
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasModuleItem { syntax })
}
@@ -4033,12 +4064,27 @@ impl AnyHasName {
}
impl AstNode for AnyHasName {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- CONST | ENUM | FN | MACRO_RULES | MACRO_DEF | MODULE | STATIC | STRUCT | TRAIT
- | TYPE_ALIAS | UNION | RENAME | SELF_PARAM | RECORD_FIELD | VARIANT | CONST_PARAM
- | TYPE_PARAM | IDENT_PAT => true,
- _ => false,
- }
+ matches!(
+ kind,
+ CONST
+ | ENUM
+ | FN
+ | MACRO_RULES
+ | MACRO_DEF
+ | MODULE
+ | STATIC
+ | STRUCT
+ | TRAIT
+ | TYPE_ALIAS
+ | UNION
+ | RENAME
+ | SELF_PARAM
+ | RECORD_FIELD
+ | VARIANT
+ | CONST_PARAM
+ | TYPE_PARAM
+ | IDENT_PAT
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasName { syntax })
@@ -4053,10 +4099,10 @@ impl AnyHasTypeBounds {
}
impl AstNode for AnyHasTypeBounds {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- ASSOC_TYPE_ARG | TRAIT | TYPE_ALIAS | LIFETIME_PARAM | TYPE_PARAM | WHERE_PRED => true,
- _ => false,
- }
+ matches!(
+ kind,
+ ASSOC_TYPE_ARG | TRAIT | TYPE_ALIAS | LIFETIME_PARAM | TYPE_PARAM | WHERE_PRED
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasTypeBounds { syntax })
@@ -4071,13 +4117,26 @@ impl AnyHasVisibility {
}
impl AstNode for AnyHasVisibility {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- CONST | ENUM | EXTERN_CRATE | FN | IMPL | MACRO_RULES | MACRO_DEF | MODULE | STATIC
- | STRUCT | TRAIT | TYPE_ALIAS | UNION | USE | RECORD_FIELD | TUPLE_FIELD | VARIANT => {
- true
- }
- _ => false,
- }
+ matches!(
+ kind,
+ CONST
+ | ENUM
+ | EXTERN_CRATE
+ | FN
+ | IMPL
+ | MACRO_RULES
+ | MACRO_DEF
+ | MODULE
+ | STATIC
+ | STRUCT
+ | TRAIT
+ | TYPE_ALIAS
+ | UNION
+ | USE
+ | RECORD_FIELD
+ | TUPLE_FIELD
+ | VARIANT
+ )
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| AnyHasVisibility { syntax })
diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs
index 5908dda8e..83f8bbac5 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/ast/make.rs
@@ -25,7 +25,7 @@ pub mod ext {
return from_text(&name.text());
fn from_text(text: &str) -> ast::IdentPat {
- ast_from_text(&format!("fn f({}: ())", text))
+ ast_from_text(&format!("fn f({text}: ())"))
}
}
pub fn ident_path(ident: &str) -> ast::Path {
@@ -60,10 +60,10 @@ pub mod ext {
expr_from_text("todo!()")
}
pub fn expr_ty_default(ty: &ast::Type) -> ast::Expr {
- expr_from_text(&format!("{}::default()", ty))
+ expr_from_text(&format!("{ty}::default()"))
}
pub fn expr_ty_new(ty: &ast::Type) -> ast::Expr {
- expr_from_text(&format!("{}::new()", ty))
+ expr_from_text(&format!("{ty}::new()"))
}
pub fn zero_number() -> ast::Expr {
@@ -92,18 +92,20 @@ pub mod ext {
ty_path(ident_path("bool"))
}
pub fn ty_option(t: ast::Type) -> ast::Type {
- ty_from_text(&format!("Option<{}>", t))
+ ty_from_text(&format!("Option<{t}>"))
}
pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
- ty_from_text(&format!("Result<{}, {}>", t, e))
+ ty_from_text(&format!("Result<{t}, {e}>"))
}
}
-pub fn name(text: &str) -> ast::Name {
- ast_from_text(&format!("mod {}{};", raw_ident_esc(text), text))
+pub fn name(name: &str) -> ast::Name {
+ let raw_escape = raw_ident_esc(name);
+ ast_from_text(&format!("mod {raw_escape}{name};"))
}
-pub fn name_ref(text: &str) -> ast::NameRef {
- ast_from_text(&format!("fn f() {{ {}{}; }}", raw_ident_esc(text), text))
+pub fn name_ref(name_ref: &str) -> ast::NameRef {
+ let raw_escape = raw_ident_esc(name_ref);
+ ast_from_text(&format!("fn f() {{ {raw_escape}{name_ref}; }}"))
}
fn raw_ident_esc(ident: &str) -> &'static str {
let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
@@ -118,10 +120,10 @@ pub fn lifetime(text: &str) -> ast::Lifetime {
let mut text = text;
let tmp;
if never!(!text.starts_with('\'')) {
- tmp = format!("'{}", text);
+ tmp = format!("'{text}");
text = &tmp;
}
- ast_from_text(&format!("fn f<{}>() {{ }}", text))
+ ast_from_text(&format!("fn f<{text}>() {{ }}"))
}
// FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
@@ -142,16 +144,16 @@ pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
contents.push(',');
}
- ty_from_text(&format!("({})", contents))
+ ty_from_text(&format!("({contents})"))
}
pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
- ty_from_text(&if exclusive { format!("&mut {}", target) } else { format!("&{}", target) })
+ ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
}
pub fn ty_path(path: ast::Path) -> ast::Type {
ty_from_text(&path.to_string())
}
fn ty_from_text(text: &str) -> ast::Type {
- ast_from_text(&format!("type _T = {};", text))
+ ast_from_text(&format!("type _T = {text};"))
}
pub fn assoc_item_list() -> ast::AssocItemList {
@@ -171,7 +173,7 @@ pub fn impl_(
Some(params) => params.to_string(),
None => String::new(),
};
- ast_from_text(&format!("impl{} {}{} {{}}", params, ty, ty_params))
+ ast_from_text(&format!("impl{params} {ty}{ty_params} {{}}"))
}
pub fn impl_trait(
@@ -180,7 +182,7 @@ pub fn impl_trait(
ty_params: Option<ast::GenericParamList>,
) -> ast::Impl {
let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
- ast_from_text(&format!("impl{2} {} for {}{2} {{}}", trait_, ty, ty_params))
+ ast_from_text(&format!("impl{ty_params} {trait_} for {ty}{ty_params} {{}}"))
}
pub(crate) fn generic_arg_list() -> ast::GenericArgList {
@@ -188,13 +190,13 @@ pub(crate) fn generic_arg_list() -> ast::GenericArgList {
}
pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
- ast_from_text(&format!("type __ = {};", name_ref))
+ ast_from_text(&format!("type __ = {name_ref};"))
}
pub fn path_segment_ty(type_ref: ast::Type, trait_ref: Option<ast::PathType>) -> ast::PathSegment {
let text = match trait_ref {
- Some(trait_ref) => format!("fn f(x: <{} as {}>) {{}}", type_ref, trait_ref),
- None => format!("fn f(x: <{}>) {{}}", type_ref),
+ Some(trait_ref) => format!("fn f(x: <{type_ref} as {trait_ref}>) {{}}"),
+ None => format!("fn f(x: <{type_ref}>) {{}}"),
};
ast_from_text(&text)
}
@@ -212,15 +214,15 @@ pub fn path_segment_crate() -> ast::PathSegment {
}
pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
- ast_from_text(&format!("type __ = {};", segment))
+ ast_from_text(&format!("type __ = {segment};"))
}
pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
- ast_from_text(&format!("{}::{}", qual, segment))
+ ast_from_text(&format!("{qual}::{segment}"))
}
// FIXME: path concatenation operation doesn't make sense as AST op.
pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
- ast_from_text(&format!("type __ = {}::{};", first, second))
+ ast_from_text(&format!("type __ = {first}::{second};"))
}
pub fn path_from_segments(
@@ -229,20 +231,20 @@ pub fn path_from_segments(
) -> ast::Path {
let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
ast_from_text(&if is_abs {
- format!("fn f(x: ::{}) {{}}", segments)
+ format!("fn f(x: ::{segments}) {{}}")
} else {
- format!("fn f(x: {}) {{}}", segments)
+ format!("fn f(x: {segments}) {{}}")
})
}
pub fn join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path {
let paths = paths.into_iter().map(|it| it.syntax().clone()).join("::");
- ast_from_text(&format!("type __ = {};", paths))
+ ast_from_text(&format!("type __ = {paths};"))
}
// FIXME: should not be pub
pub fn path_from_text(text: &str) -> ast::Path {
- ast_from_text(&format!("fn main() {{ let test = {}; }}", text))
+ ast_from_text(&format!("fn main() {{ let test = {text}; }}"))
}
pub fn use_tree_glob() -> ast::UseTree {
@@ -257,50 +259,50 @@ pub fn use_tree(
let mut buf = "use ".to_string();
buf += &path.syntax().to_string();
if let Some(use_tree_list) = use_tree_list {
- format_to!(buf, "::{}", use_tree_list);
+ format_to!(buf, "::{use_tree_list}");
}
if add_star {
buf += "::*";
}
if let Some(alias) = alias {
- format_to!(buf, " {}", alias);
+ format_to!(buf, " {alias}");
}
ast_from_text(&buf)
}
pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
- ast_from_text(&format!("use {{{}}};", use_trees))
+ ast_from_text(&format!("use {{{use_trees}}};"))
}
pub fn use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use {
let visibility = match visibility {
None => String::new(),
- Some(it) => format!("{} ", it),
+ Some(it) => format!("{it} "),
};
- ast_from_text(&format!("{}use {};", visibility, use_tree))
+ ast_from_text(&format!("{visibility}use {use_tree};"))
}
pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
- ast_from_text(&format!("fn f() {{ {} {} }}", path, fields))
+ ast_from_text(&format!("fn f() {{ {path} {fields} }}"))
}
pub fn record_expr_field_list(
fields: impl IntoIterator<Item = ast::RecordExprField>,
) -> ast::RecordExprFieldList {
let fields = fields.into_iter().join(", ");
- ast_from_text(&format!("fn f() {{ S {{ {} }} }}", fields))
+ ast_from_text(&format!("fn f() {{ S {{ {fields} }} }}"))
}
pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
return match expr {
- Some(expr) => from_text(&format!("{}: {}", name, expr)),
+ Some(expr) => from_text(&format!("{name}: {expr}")),
None => from_text(&name.to_string()),
};
fn from_text(text: &str) -> ast::RecordExprField {
- ast_from_text(&format!("fn f() {{ S {{ {}, }} }}", text))
+ ast_from_text(&format!("fn f() {{ S {{ {text}, }} }}"))
}
}
@@ -311,9 +313,9 @@ pub fn record_field(
) -> ast::RecordField {
let visibility = match visibility {
None => String::new(),
- Some(it) => format!("{} ", it),
+ Some(it) => format!("{it} "),
};
- ast_from_text(&format!("struct S {{ {}{}: {}, }}", visibility, name, ty))
+ ast_from_text(&format!("struct S {{ {visibility}{name}: {ty}, }}"))
}
// TODO
@@ -323,13 +325,13 @@ pub fn block_expr(
) -> ast::BlockExpr {
let mut buf = "{\n".to_string();
for stmt in stmts.into_iter() {
- format_to!(buf, " {}\n", stmt);
+ format_to!(buf, " {stmt}\n");
}
if let Some(tail_expr) = tail_expr {
- format_to!(buf, " {}\n", tail_expr);
+ format_to!(buf, " {tail_expr}\n");
}
buf += "}";
- ast_from_text(&format!("fn f() {}", buf))
+ ast_from_text(&format!("fn f() {buf}"))
}
/// Ideally this function wouldn't exist since it involves manual indenting.
@@ -343,18 +345,18 @@ pub fn hacky_block_expr_with_comments(
let mut buf = "{\n".to_string();
for node_or_token in elements.into_iter() {
match node_or_token {
- rowan::NodeOrToken::Node(n) => format_to!(buf, " {}\n", n),
+ rowan::NodeOrToken::Node(n) => format_to!(buf, " {n}\n"),
rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::COMMENT => {
- format_to!(buf, " {}\n", t)
+ format_to!(buf, " {t}\n")
}
_ => (),
}
}
if let Some(tail_expr) = tail_expr {
- format_to!(buf, " {}\n", tail_expr);
+ format_to!(buf, " {tail_expr}\n");
}
buf += "}";
- ast_from_text(&format!("fn f() {}", buf))
+ ast_from_text(&format!("fn f() {buf}"))
}
pub fn expr_unit() -> ast::Expr {
@@ -362,7 +364,7 @@ pub fn expr_unit() -> ast::Expr {
}
pub fn expr_literal(text: &str) -> ast::Literal {
assert_eq!(text.trim(), text);
- ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
+ ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
}
pub fn expr_empty_block() -> ast::Expr {
@@ -373,41 +375,41 @@ pub fn expr_path(path: ast::Path) -> ast::Expr {
}
pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
match label {
- Some(label) => expr_from_text(&format!("continue {}", label)),
+ Some(label) => expr_from_text(&format!("continue {label}")),
None => expr_from_text("continue"),
}
}
// Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
- expr_from_text(&format!("{} {} {}", lhs, op, rhs))
+ expr_from_text(&format!("{lhs} {op} {rhs}"))
}
pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
let mut s = String::from("break");
if let Some(label) = label {
- format_to!(s, " {}", label);
+ format_to!(s, " {label}");
}
if let Some(expr) = expr {
- format_to!(s, " {}", expr);
+ format_to!(s, " {expr}");
}
expr_from_text(&s)
}
pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
match expr {
- Some(expr) => expr_from_text(&format!("return {}", expr)),
+ Some(expr) => expr_from_text(&format!("return {expr}")),
None => expr_from_text("return"),
}
}
pub fn expr_try(expr: ast::Expr) -> ast::Expr {
- expr_from_text(&format!("{}?", expr))
+ expr_from_text(&format!("{expr}?"))
}
pub fn expr_await(expr: ast::Expr) -> ast::Expr {
- expr_from_text(&format!("{}.await", expr))
+ expr_from_text(&format!("{expr}.await"))
}
pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
- expr_from_text(&format!("match {} {}", expr, match_arm_list))
+ expr_from_text(&format!("match {expr} {match_arm_list}"))
}
pub fn expr_if(
condition: ast::Expr,
@@ -415,66 +417,67 @@ pub fn expr_if(
else_branch: Option<ast::ElseBranch>,
) -> ast::Expr {
let else_branch = match else_branch {
- Some(ast::ElseBranch::Block(block)) => format!("else {}", block),
- Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {}", if_expr),
+ Some(ast::ElseBranch::Block(block)) => format!("else {block}"),
+ Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {if_expr}"),
None => String::new(),
};
- expr_from_text(&format!("if {} {} {}", condition, then_branch, else_branch))
+ expr_from_text(&format!("if {condition} {then_branch} {else_branch}"))
}
pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
- expr_from_text(&format!("for {} in {} {}", pat, expr, block))
+ expr_from_text(&format!("for {pat} in {expr} {block}"))
}
pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
- expr_from_text(&format!("loop {}", block))
+ expr_from_text(&format!("loop {block}"))
}
pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
let token = token(op);
- expr_from_text(&format!("{}{}", token, expr))
+ expr_from_text(&format!("{token}{expr}"))
}
pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
- expr_from_text(&format!("{}{}", f, arg_list))
+ expr_from_text(&format!("{f}{arg_list}"))
}
pub fn expr_method_call(
receiver: ast::Expr,
method: ast::NameRef,
arg_list: ast::ArgList,
) -> ast::Expr {
- expr_from_text(&format!("{}.{}{}", receiver, method, arg_list))
+ expr_from_text(&format!("{receiver}.{method}{arg_list}"))
}
pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
- expr_from_text(&format!("{}!{}", f, arg_list))
+ expr_from_text(&format!("{f}!{arg_list}"))
}
pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
- expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
+ expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
}
pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
let params = pats.into_iter().join(", ");
- expr_from_text(&format!("|{}| {}", params, expr))
+ expr_from_text(&format!("|{params}| {expr}"))
}
pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
- expr_from_text(&format!("{}.{}", receiver, field))
+ expr_from_text(&format!("{receiver}.{field}"))
}
pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
- expr_from_text(&format!("({})", expr))
+ expr_from_text(&format!("({expr})"))
}
pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
let expr = elements.into_iter().format(", ");
- expr_from_text(&format!("({})", expr))
+ expr_from_text(&format!("({expr})"))
}
pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
- expr_from_text(&format!("{} = {}", lhs, rhs))
+ expr_from_text(&format!("{lhs} = {rhs}"))
}
fn expr_from_text(text: &str) -> ast::Expr {
- ast_from_text(&format!("const C: () = {};", text))
+ ast_from_text(&format!("const C: () = {text};"))
}
pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
- ast_from_text(&format!("const _: () = while let {} = {} {{}};", pattern, expr))
+ ast_from_text(&format!("const _: () = while let {pattern} = {expr} {{}};"))
}
pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
- ast_from_text(&format!("fn main() {{ ()({}) }}", args.into_iter().format(", ")))
+ let args = args.into_iter().format(", ");
+ ast_from_text(&format!("fn main() {{ ()({args}) }}"))
}
pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
@@ -485,7 +488,7 @@ pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
if mut_ {
s.push_str("mut ");
}
- format_to!(s, "{}", name);
+ format_to!(s, "{name}");
s.push_str(": ())");
ast_from_text(&s)
}
@@ -494,7 +497,7 @@ pub fn wildcard_pat() -> ast::WildcardPat {
return from_text("_");
fn from_text(text: &str) -> ast::WildcardPat {
- ast_from_text(&format!("fn f({}: ())", text))
+ ast_from_text(&format!("fn f({text}: ())"))
}
}
@@ -502,7 +505,7 @@ pub fn literal_pat(lit: &str) -> ast::LiteralPat {
return from_text(lit);
fn from_text(text: &str) -> ast::LiteralPat {
- ast_from_text(&format!("fn f() {{ match x {{ {} => {{}} }} }}", text))
+ ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
}
}
@@ -515,10 +518,10 @@ pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
if count == 1 {
pats_str.push(',');
}
- return from_text(&format!("({})", pats_str));
+ return from_text(&format!("({pats_str})"));
fn from_text(text: &str) -> ast::TuplePat {
- ast_from_text(&format!("fn f({}: ())", text))
+ ast_from_text(&format!("fn f({text}: ())"))
}
}
@@ -527,46 +530,46 @@ pub fn tuple_struct_pat(
pats: impl IntoIterator<Item = ast::Pat>,
) -> ast::TupleStructPat {
let pats_str = pats.into_iter().join(", ");
- return from_text(&format!("{}({})", path, pats_str));
+ return from_text(&format!("{path}({pats_str})"));
fn from_text(text: &str) -> ast::TupleStructPat {
- ast_from_text(&format!("fn f({}: ())", text))
+ ast_from_text(&format!("fn f({text}: ())"))
}
}
pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
let pats_str = pats.into_iter().join(", ");
- return from_text(&format!("{} {{ {} }}", path, pats_str));
+ return from_text(&format!("{path} {{ {pats_str} }}"));
fn from_text(text: &str) -> ast::RecordPat {
- ast_from_text(&format!("fn f({}: ())", text))
+ ast_from_text(&format!("fn f({text}: ())"))
}
}
pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
- ast_from_text(&format!("fn f({} {}: ()))", path, fields))
+ ast_from_text(&format!("fn f({path} {fields}: ()))"))
}
pub fn record_pat_field_list(
fields: impl IntoIterator<Item = ast::RecordPatField>,
) -> ast::RecordPatFieldList {
let fields = fields.into_iter().join(", ");
- ast_from_text(&format!("fn f(S {{ {} }}: ()))", fields))
+ ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
}
pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
- ast_from_text(&format!("fn f(S {{ {}: {} }}: ()))", name_ref, pat))
+ ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
}
pub fn record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField {
- ast_from_text(&format!("fn f(S {{ {} }}: ()))", name_ref))
+ ast_from_text(&format!("fn f(S {{ {name_ref} }}: ()))"))
}
/// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
pub fn path_pat(path: ast::Path) -> ast::Pat {
return from_text(&path.to_string());
fn from_text(text: &str) -> ast::Pat {
- ast_from_text(&format!("fn f({}: ())", text))
+ ast_from_text(&format!("fn f({text}: ())"))
}
}
@@ -577,12 +580,12 @@ pub fn match_arm(
) -> ast::MatchArm {
let pats_str = pats.into_iter().join(" | ");
return match guard {
- Some(guard) => from_text(&format!("{} if {} => {}", pats_str, guard, expr)),
- None => from_text(&format!("{} => {}", pats_str, expr)),
+ Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
+ None => from_text(&format!("{pats_str} => {expr}")),
};
fn from_text(text: &str) -> ast::MatchArm {
- ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
+ ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
}
}
@@ -592,10 +595,10 @@ pub fn match_arm_with_guard(
expr: ast::Expr,
) -> ast::MatchArm {
let pats_str = pats.into_iter().join(" | ");
- return from_text(&format!("{} if {} => {}", pats_str, guard, expr));
+ return from_text(&format!("{pats_str} if {guard} => {expr}"));
fn from_text(text: &str) -> ast::MatchArm {
- ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
+ ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
}
}
@@ -605,13 +608,14 @@ pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::Mat
.map(|arm| {
let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
let comma = if needs_comma { "," } else { "" };
- format!(" {}{}\n", arm.syntax(), comma)
+ let arm = arm.syntax();
+ format!(" {arm}{comma}\n")
})
.collect::<String>();
return from_text(&arms_str);
fn from_text(text: &str) -> ast::MatchArmList {
- ast_from_text(&format!("fn f() {{ match () {{\n{}}} }}", text))
+ ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
}
}
@@ -620,10 +624,10 @@ pub fn where_pred(
bounds: impl IntoIterator<Item = ast::TypeBound>,
) -> ast::WherePred {
let bounds = bounds.into_iter().join(" + ");
- return from_text(&format!("{}: {}", path, bounds));
+ return from_text(&format!("{path}: {bounds}"));
fn from_text(text: &str) -> ast::WherePred {
- ast_from_text(&format!("fn f() where {} {{ }}", text))
+ ast_from_text(&format!("fn f() where {text} {{ }}"))
}
}
@@ -632,7 +636,7 @@ pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::Whe
return from_text(preds.as_str());
fn from_text(text: &str) -> ast::WhereClause {
- ast_from_text(&format!("fn f() where {} {{ }}", text))
+ ast_from_text(&format!("fn f() where {text} {{ }}"))
}
}
@@ -642,19 +646,19 @@ pub fn let_stmt(
initializer: Option<ast::Expr>,
) -> ast::LetStmt {
let mut text = String::new();
- format_to!(text, "let {}", pattern);
+ format_to!(text, "let {pattern}");
if let Some(ty) = ty {
- format_to!(text, ": {}", ty);
+ format_to!(text, ": {ty}");
}
match initializer {
- Some(it) => format_to!(text, " = {};", it),
+ Some(it) => format_to!(text, " = {it};"),
None => format_to!(text, ";"),
};
- ast_from_text(&format!("fn f() {{ {} }}", text))
+ ast_from_text(&format!("fn f() {{ {text} }}"))
}
pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
let semi = if expr.is_block_like() { "" } else { ";" };
- ast_from_text(&format!("fn f() {{ {}{} (); }}", expr, semi))
+ ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
}
pub fn item_const(
@@ -665,13 +669,13 @@ pub fn item_const(
) -> ast::Const {
let visibility = match visibility {
None => String::new(),
- Some(it) => format!("{} ", it),
+ Some(it) => format!("{it} "),
};
- ast_from_text(&format!("{} const {}: {} = {};", visibility, name, ty, expr))
+ ast_from_text(&format!("{visibility} const {name}: {ty} = {expr};"))
}
pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
- ast_from_text(&format!("fn f({}: {}) {{ }}", pat, ty))
+ ast_from_text(&format!("fn f({pat}: {ty}) {{ }}"))
}
pub fn self_param() -> ast::SelfParam {
@@ -679,7 +683,7 @@ pub fn self_param() -> ast::SelfParam {
}
pub fn ret_type(ty: ast::Type) -> ast::RetType {
- ast_from_text(&format!("fn f() -> {} {{ }}", ty))
+ ast_from_text(&format!("fn f() -> {ty} {{ }}"))
}
pub fn param_list(
@@ -688,30 +692,30 @@ pub fn param_list(
) -> ast::ParamList {
let args = pats.into_iter().join(", ");
let list = match self_param {
- Some(self_param) if args.is_empty() => format!("fn f({}) {{ }}", self_param),
- Some(self_param) => format!("fn f({}, {}) {{ }}", self_param, args),
- None => format!("fn f({}) {{ }}", args),
+ Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
+ Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
+ None => format!("fn f({args}) {{ }}"),
};
ast_from_text(&list)
}
pub fn type_param(name: ast::Name, ty: Option<ast::TypeBoundList>) -> ast::TypeParam {
let bound = match ty {
- Some(it) => format!(": {}", it),
+ Some(it) => format!(": {it}"),
None => String::new(),
};
- ast_from_text(&format!("fn f<{}{}>() {{ }}", name, bound))
+ ast_from_text(&format!("fn f<{name}{bound}>() {{ }}"))
}
pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
- ast_from_text(&format!("fn f<{}>() {{ }}", lifetime))
+ ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
}
pub fn generic_param_list(
pats: impl IntoIterator<Item = ast::GenericParam>,
) -> ast::GenericParamList {
let args = pats.into_iter().join(", ");
- ast_from_text(&format!("fn f<{}>() {{ }}", args))
+ ast_from_text(&format!("fn f<{args}>() {{ }}"))
}
pub fn visibility_pub_crate() -> ast::Visibility {
@@ -724,30 +728,33 @@ pub fn visibility_pub() -> ast::Visibility {
pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
let fields = fields.into_iter().join(", ");
- ast_from_text(&format!("struct f({});", fields))
+ ast_from_text(&format!("struct f({fields});"))
}
pub fn record_field_list(
fields: impl IntoIterator<Item = ast::RecordField>,
) -> ast::RecordFieldList {
let fields = fields.into_iter().join(", ");
- ast_from_text(&format!("struct f {{ {} }}", fields))
+ ast_from_text(&format!("struct f {{ {fields} }}"))
}
pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
let visibility = match visibility {
None => String::new(),
- Some(it) => format!("{} ", it),
+ Some(it) => format!("{it} "),
};
- ast_from_text(&format!("struct f({}{});", visibility, ty))
+ ast_from_text(&format!("struct f({visibility}{ty});"))
}
pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
let field_list = match field_list {
None => String::new(),
- Some(it) => format!("{}", it),
+ Some(it) => match it {
+ ast::FieldList::RecordFieldList(record) => format!(" {record}"),
+ ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
+ },
};
- ast_from_text(&format!("enum f {{ {}{} }}", name, field_list))
+ ast_from_text(&format!("enum f {{ {name}{field_list} }}"))
}
pub fn fn_(
@@ -760,23 +767,22 @@ pub fn fn_(
is_async: bool,
) -> ast::Fn {
let type_params = match type_params {
- Some(type_params) => format!("{}", type_params),
+ Some(type_params) => format!("{type_params}"),
None => "".into(),
};
let ret_type = match ret_type {
- Some(ret_type) => format!("{} ", ret_type),
+ Some(ret_type) => format!("{ret_type} "),
None => "".into(),
};
let visibility = match visibility {
None => String::new(),
- Some(it) => format!("{} ", it),
+ Some(it) => format!("{it} "),
};
let async_literal = if is_async { "async " } else { "" };
ast_from_text(&format!(
- "{}{}fn {}{}{} {}{}",
- visibility, async_literal, fn_name, type_params, params, ret_type, body
+ "{visibility}{async_literal}fn {fn_name}{type_params}{params} {ret_type}{body}",
))
}
@@ -790,13 +796,10 @@ pub fn struct_(
let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
let visibility = match visibility {
None => String::new(),
- Some(it) => format!("{} ", it),
+ Some(it) => format!("{it} "),
};
- ast_from_text(&format!(
- "{}struct {}{}{}{}",
- visibility, strukt_name, type_params, field_list, semicolon
- ))
+ ast_from_text(&format!("{visibility}struct {strukt_name}{type_params}{field_list}{semicolon}",))
}
#[track_caller]
@@ -805,7 +808,8 @@ fn ast_from_text<N: AstNode>(text: &str) -> N {
let node = match parse.tree().syntax().descendants().find_map(N::cast) {
Some(it) => it,
None => {
- panic!("Failed to make ast node `{}` from text {}", std::any::type_name::<N>(), text)
+ let node = std::any::type_name::<N>();
+ panic!("Failed to make ast node `{node}` from text {text}")
}
};
let node = node.clone_subtree();
@@ -821,7 +825,7 @@ pub fn token(kind: SyntaxKind) -> SyntaxToken {
.descendants_with_tokens()
.filter_map(|it| it.into_token())
.find(|it| it.kind() == kind)
- .unwrap_or_else(|| panic!("unhandled token: {:?}", kind))
+ .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
}
pub mod tokens {
@@ -860,7 +864,7 @@ pub mod tokens {
pub fn literal(text: &str) -> SyntaxToken {
assert_eq!(text.trim(), text);
- let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {}; }}", text));
+ let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
}
diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/operators.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/operators.rs
index a687ba0b7..8f7b3fb60 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/ast/operators.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/ast/operators.rs
@@ -111,10 +111,10 @@ impl fmt::Display for BinaryOp {
BinaryOp::ArithOp(op) => fmt::Display::fmt(op, f),
BinaryOp::CmpOp(op) => fmt::Display::fmt(op, f),
BinaryOp::Assignment { op } => {
- f.write_str("=")?;
if let Some(op) = op {
fmt::Display::fmt(op, f)?;
}
+ f.write_str("=")?;
Ok(())
}
}
diff --git a/src/tools/rust-analyzer/crates/syntax/src/ast/token_ext.rs b/src/tools/rust-analyzer/crates/syntax/src/ast/token_ext.rs
index 28976d837..ba72e6442 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/ast/token_ext.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/ast/token_ext.rs
@@ -322,7 +322,7 @@ impl ast::IntNumber {
pub fn float_value(&self) -> Option<f64> {
let (_, text, _) = self.split_into_parts();
- text.parse::<f64>().ok()
+ text.replace('_', "").parse::<f64>().ok()
}
}
@@ -361,7 +361,7 @@ impl ast::FloatNumber {
pub fn value(&self) -> Option<f64> {
let (text, _) = self.split_into_parts();
- text.parse::<f64>().ok()
+ text.replace('_', "").parse::<f64>().ok()
}
}
@@ -397,6 +397,15 @@ mod tests {
assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.suffix(), expected.into());
}
+ fn check_float_value(lit: &str, expected: impl Into<Option<f64>> + Copy) {
+ assert_eq!(FloatNumber { syntax: make::tokens::literal(lit) }.value(), expected.into());
+ assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.float_value(), expected.into());
+ }
+
+ fn check_int_value(lit: &str, expected: impl Into<Option<u128>>) {
+ assert_eq!(IntNumber { syntax: make::tokens::literal(lit) }.value(), expected.into());
+ }
+
#[test]
fn test_float_number_suffix() {
check_float_suffix("123.0", None);
@@ -437,6 +446,14 @@ mod tests {
check_string_value(r"\nfoobar", "\nfoobar");
check_string_value(r"C:\\Windows\\System32\\", "C:\\Windows\\System32\\");
}
+
+ #[test]
+ fn test_value_underscores() {
+ check_float_value("3.141592653589793_f64", 3.141592653589793_f64);
+ check_float_value("1__0.__0__f32", 10.0);
+ check_int_value("0b__1_0_", 2);
+ check_int_value("1_1_1_1_1_1", 111111);
+ }
}
impl ast::Char {
diff --git a/src/tools/rust-analyzer/crates/syntax/src/fuzz.rs b/src/tools/rust-analyzer/crates/syntax/src/fuzz.rs
index 256999fe0..7c7a60d62 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/fuzz.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/fuzz.rs
@@ -2,10 +2,7 @@
//!
//! We don't normally run fuzzying, so this is hopelessly bitrotten :(
-use std::{
- convert::TryInto,
- str::{self, FromStr},
-};
+use std::str::{self, FromStr};
use text_edit::Indel;
diff --git a/src/tools/rust-analyzer/crates/syntax/src/hacks.rs b/src/tools/rust-analyzer/crates/syntax/src/hacks.rs
index a047f61fa..ec3d3d444 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/hacks.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/hacks.rs
@@ -1,4 +1,4 @@
-//! Things which exist to solve practial issues, but which shouldn't exist.
+//! Things which exist to solve practical issues, but which shouldn't exist.
//!
//! Please avoid adding new usages of the functions in this module
diff --git a/src/tools/rust-analyzer/crates/syntax/src/lib.rs b/src/tools/rust-analyzer/crates/syntax/src/lib.rs
index 7fa354c0c..4f5e273a5 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/lib.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/lib.rs
@@ -1,4 +1,4 @@
-//! Syntax Tree library used throughout the rust analyzer.
+//! Syntax Tree library used throughout the rust-analyzer.
//!
//! Properties:
//! - easy and fast incremental re-parsing
diff --git a/src/tools/rust-analyzer/crates/syntax/src/tests/sourcegen_ast.rs b/src/tools/rust-analyzer/crates/syntax/src/tests/sourcegen_ast.rs
index 6d2766225..70b54843d 100644
--- a/src/tools/rust-analyzer/crates/syntax/src/tests/sourcegen_ast.rs
+++ b/src/tools/rust-analyzer/crates/syntax/src/tests/sourcegen_ast.rs
@@ -169,10 +169,7 @@ fn generate_nodes(kinds: KindsSrc<'_>, grammar: &AstSrc) -> String {
quote! {
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- #(#kinds)|* => true,
- _ => false,
- }
+ matches!(kind, #(#kinds)|*)
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
@@ -253,10 +250,7 @@ fn generate_nodes(kinds: KindsSrc<'_>, grammar: &AstSrc) -> String {
}
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
- match kind {
- #(#kinds)|* => true,
- _ => false,
- }
+ matches!(kind, #(#kinds)|*)
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
Self::can_cast(syntax.kind()).then(|| #name { syntax })
@@ -410,24 +404,17 @@ fn generate_syntax_kinds(grammar: KindsSrc<'_>) -> String {
impl SyntaxKind {
pub fn is_keyword(self) -> bool {
- match self {
- #(#all_keywords)|* => true,
- _ => false,
- }
+ matches!(self, #(#all_keywords)|*)
}
pub fn is_punct(self) -> bool {
- match self {
- #(#punctuation)|* => true,
- _ => false,
- }
+
+ matches!(self, #(#punctuation)|*)
+
}
pub fn is_literal(self) -> bool {
- match self {
- #(#literals)|* => true,
- _ => false,
- }
+ matches!(self, #(#literals)|*)
}
pub fn from_keyword(ident: &str) -> Option<SyntaxKind> {