aboutsummaryrefslogtreecommitdiff
path: root/crates/syntax
diff options
context:
space:
mode:
Diffstat (limited to 'crates/syntax')
-rw-r--r--crates/syntax/src/algo.rs4
-rw-r--r--crates/syntax/src/ast.rs4
-rw-r--r--crates/syntax/src/ast/edit.rs8
-rw-r--r--crates/syntax/src/ast/edit_in_place.rs41
-rw-r--r--crates/syntax/src/ast/expr_ext.rs44
-rw-r--r--crates/syntax/src/ast/generated/nodes.rs46
-rw-r--r--crates/syntax/src/ast/make.rs2
-rw-r--r--crates/syntax/src/ast/node_ext.rs68
-rw-r--r--crates/syntax/src/ast/token_ext.rs5
-rw-r--r--crates/syntax/src/fuzz.rs2
-rw-r--r--crates/syntax/src/ted.rs65
-rw-r--r--crates/syntax/src/validation.rs4
12 files changed, 167 insertions, 126 deletions
diff --git a/crates/syntax/src/algo.rs b/crates/syntax/src/algo.rs
index 82ebf9037..a153a9e1c 100644
--- a/crates/syntax/src/algo.rs
+++ b/crates/syntax/src/algo.rs
@@ -567,7 +567,7 @@ impl<'a> SyntaxRewriter<'a> {
567 567
568fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 568fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
569 match element { 569 match element {
570 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().to_owned()), 570 NodeOrToken::Node(it) => NodeOrToken::Node(it.green()),
571 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().to_owned()), 571 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().to_owned()),
572 } 572 }
573} 573}
@@ -625,7 +625,7 @@ fn position_of_child(parent: &SyntaxNode, child: SyntaxElement) -> usize {
625 625
626fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 626fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
627 match element { 627 match element {
628 NodeOrToken::Node(it) => it.green().to_owned().into(), 628 NodeOrToken::Node(it) => it.green().into(),
629 NodeOrToken::Token(it) => it.green().to_owned().into(), 629 NodeOrToken::Token(it) => it.green().to_owned().into(),
630 } 630 }
631} 631}
diff --git a/crates/syntax/src/ast.rs b/crates/syntax/src/ast.rs
index 38e0b04ef..7f472d4db 100644
--- a/crates/syntax/src/ast.rs
+++ b/crates/syntax/src/ast.rs
@@ -20,8 +20,8 @@ pub use self::{
20 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp}, 20 expr_ext::{ArrayExprKind, BinOp, Effect, ElseBranch, LiteralKind, PrefixOp, RangeOp},
21 generated::{nodes::*, tokens::*}, 21 generated::{nodes::*, tokens::*},
22 node_ext::{ 22 node_ext::{
23 AttrKind, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind, SelfParamKind, 23 AttrKind, AttrsOwnerNode, FieldKind, Macro, NameLike, NameOrNameRef, PathSegmentKind,
24 SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind, 24 SelfParamKind, SlicePatComponents, StructKind, TypeBoundKind, VisibilityKind,
25 }, 25 },
26 token_ext::*, 26 token_ext::*,
27 traits::*, 27 traits::*,
diff --git a/crates/syntax/src/ast/edit.rs b/crates/syntax/src/ast/edit.rs
index 64fac13a7..347862b8a 100644
--- a/crates/syntax/src/ast/edit.rs
+++ b/crates/syntax/src/ast/edit.rs
@@ -333,8 +333,7 @@ impl ast::Use {
333 .and_then(ast::Whitespace::cast); 333 .and_then(ast::Whitespace::cast);
334 if let Some(next_ws) = next_ws { 334 if let Some(next_ws) = next_ws {
335 let ws_text = next_ws.syntax().text(); 335 let ws_text = next_ws.syntax().text();
336 if ws_text.starts_with('\n') { 336 if let Some(rest) = ws_text.strip_prefix('\n') {
337 let rest = &ws_text[1..];
338 if rest.is_empty() { 337 if rest.is_empty() {
339 res.delete(next_ws.syntax()) 338 res.delete(next_ws.syntax())
340 } else { 339 } else {
@@ -462,8 +461,7 @@ impl ast::MatchArmList {
462 let end = if let Some(comma) = start 461 let end = if let Some(comma) = start
463 .siblings_with_tokens(Direction::Next) 462 .siblings_with_tokens(Direction::Next)
464 .skip(1) 463 .skip(1)
465 .skip_while(|it| it.kind().is_trivia()) 464 .find(|it| !it.kind().is_trivia())
466 .next()
467 .filter(|it| it.kind() == T![,]) 465 .filter(|it| it.kind() == T![,])
468 { 466 {
469 comma 467 comma
@@ -597,7 +595,7 @@ impl IndentLevel {
597 pub fn from_node(node: &SyntaxNode) -> IndentLevel { 595 pub fn from_node(node: &SyntaxNode) -> IndentLevel {
598 match node.first_token() { 596 match node.first_token() {
599 Some(it) => Self::from_token(&it), 597 Some(it) => Self::from_token(&it),
600 None => return IndentLevel(0), 598 None => IndentLevel(0),
601 } 599 }
602 } 600 }
603 601
diff --git a/crates/syntax/src/ast/edit_in_place.rs b/crates/syntax/src/ast/edit_in_place.rs
index 449b058fb..b1eed0a2c 100644
--- a/crates/syntax/src/ast/edit_in_place.rs
+++ b/crates/syntax/src/ast/edit_in_place.rs
@@ -8,7 +8,7 @@ use parser::T;
8use crate::{ 8use crate::{
9 ast, 9 ast,
10 ted::{self, Position}, 10 ted::{self, Position},
11 AstNode, Direction, SyntaxElement, 11 AstNode, Direction,
12}; 12};
13 13
14use super::NameOwner; 14use super::NameOwner;
@@ -21,11 +21,11 @@ impl GenericParamsOwnerEdit for ast::Fn {
21 fn get_or_create_where_clause(&self) -> WhereClause { 21 fn get_or_create_where_clause(&self) -> WhereClause {
22 if self.where_clause().is_none() { 22 if self.where_clause().is_none() {
23 let position = if let Some(ty) = self.ret_type() { 23 let position = if let Some(ty) = self.ret_type() {
24 Position::after(ty.syntax().clone()) 24 Position::after(ty.syntax())
25 } else if let Some(param_list) = self.param_list() { 25 } else if let Some(param_list) = self.param_list() {
26 Position::after(param_list.syntax().clone()) 26 Position::after(param_list.syntax())
27 } else { 27 } else {
28 Position::last_child_of(self.syntax().clone()) 28 Position::last_child_of(self.syntax())
29 }; 29 };
30 create_where_clause(position) 30 create_where_clause(position)
31 } 31 }
@@ -37,9 +37,9 @@ impl GenericParamsOwnerEdit for ast::Impl {
37 fn get_or_create_where_clause(&self) -> WhereClause { 37 fn get_or_create_where_clause(&self) -> WhereClause {
38 if self.where_clause().is_none() { 38 if self.where_clause().is_none() {
39 let position = if let Some(items) = self.assoc_item_list() { 39 let position = if let Some(items) = self.assoc_item_list() {
40 Position::before(items.syntax().clone()) 40 Position::before(items.syntax())
41 } else { 41 } else {
42 Position::last_child_of(self.syntax().clone()) 42 Position::last_child_of(self.syntax())
43 }; 43 };
44 create_where_clause(position) 44 create_where_clause(position)
45 } 45 }
@@ -51,9 +51,9 @@ impl GenericParamsOwnerEdit for ast::Trait {
51 fn get_or_create_where_clause(&self) -> WhereClause { 51 fn get_or_create_where_clause(&self) -> WhereClause {
52 if self.where_clause().is_none() { 52 if self.where_clause().is_none() {
53 let position = if let Some(items) = self.assoc_item_list() { 53 let position = if let Some(items) = self.assoc_item_list() {
54 Position::before(items.syntax().clone()) 54 Position::before(items.syntax())
55 } else { 55 } else {
56 Position::last_child_of(self.syntax().clone()) 56 Position::last_child_of(self.syntax())
57 }; 57 };
58 create_where_clause(position) 58 create_where_clause(position)
59 } 59 }
@@ -69,13 +69,13 @@ impl GenericParamsOwnerEdit for ast::Struct {
69 ast::FieldList::TupleFieldList(it) => Some(it), 69 ast::FieldList::TupleFieldList(it) => Some(it),
70 }); 70 });
71 let position = if let Some(tfl) = tfl { 71 let position = if let Some(tfl) = tfl {
72 Position::after(tfl.syntax().clone()) 72 Position::after(tfl.syntax())
73 } else if let Some(gpl) = self.generic_param_list() { 73 } else if let Some(gpl) = self.generic_param_list() {
74 Position::after(gpl.syntax().clone()) 74 Position::after(gpl.syntax())
75 } else if let Some(name) = self.name() { 75 } else if let Some(name) = self.name() {
76 Position::after(name.syntax().clone()) 76 Position::after(name.syntax())
77 } else { 77 } else {
78 Position::last_child_of(self.syntax().clone()) 78 Position::last_child_of(self.syntax())
79 }; 79 };
80 create_where_clause(position) 80 create_where_clause(position)
81 } 81 }
@@ -87,11 +87,11 @@ impl GenericParamsOwnerEdit for ast::Enum {
87 fn get_or_create_where_clause(&self) -> WhereClause { 87 fn get_or_create_where_clause(&self) -> WhereClause {
88 if self.where_clause().is_none() { 88 if self.where_clause().is_none() {
89 let position = if let Some(gpl) = self.generic_param_list() { 89 let position = if let Some(gpl) = self.generic_param_list() {
90 Position::after(gpl.syntax().clone()) 90 Position::after(gpl.syntax())
91 } else if let Some(name) = self.name() { 91 } else if let Some(name) = self.name() {
92 Position::after(name.syntax().clone()) 92 Position::after(name.syntax())
93 } else { 93 } else {
94 Position::last_child_of(self.syntax().clone()) 94 Position::last_child_of(self.syntax())
95 }; 95 };
96 create_where_clause(position) 96 create_where_clause(position)
97 } 97 }
@@ -100,19 +100,18 @@ impl GenericParamsOwnerEdit for ast::Enum {
100} 100}
101 101
102fn create_where_clause(position: Position) { 102fn create_where_clause(position: Position) {
103 let where_clause: SyntaxElement = 103 let where_clause = make::where_clause(empty()).clone_for_update();
104 make::where_clause(empty()).clone_for_update().syntax().clone().into(); 104 ted::insert(position, where_clause.syntax());
105 ted::insert(position, where_clause);
106} 105}
107 106
108impl ast::WhereClause { 107impl ast::WhereClause {
109 pub fn add_predicate(&self, predicate: ast::WherePred) { 108 pub fn add_predicate(&self, predicate: ast::WherePred) {
110 if let Some(pred) = self.predicates().last() { 109 if let Some(pred) = self.predicates().last() {
111 if !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) { 110 if !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) {
112 ted::append_child_raw(self.syntax().clone(), make::token(T![,])); 111 ted::append_child_raw(self.syntax(), make::token(T![,]));
113 } 112 }
114 } 113 }
115 ted::append_child(self.syntax().clone(), predicate.syntax().clone()) 114 ted::append_child(self.syntax(), predicate.syntax())
116 } 115 }
117} 116}
118 117
@@ -123,7 +122,7 @@ impl ast::TypeBoundList {
123 { 122 {
124 ted::remove_all(colon..=self.syntax().clone().into()) 123 ted::remove_all(colon..=self.syntax().clone().into())
125 } else { 124 } else {
126 ted::remove(self.syntax().clone()) 125 ted::remove(self.syntax())
127 } 126 }
128 } 127 }
129} 128}
diff --git a/crates/syntax/src/ast/expr_ext.rs b/crates/syntax/src/ast/expr_ext.rs
index 636ce166d..6317d84ba 100644
--- a/crates/syntax/src/ast/expr_ext.rs
+++ b/crates/syntax/src/ast/expr_ext.rs
@@ -11,16 +11,16 @@ impl ast::AttrsOwner for ast::Expr {}
11 11
12impl ast::Expr { 12impl ast::Expr {
13 pub fn is_block_like(&self) -> bool { 13 pub fn is_block_like(&self) -> bool {
14 match self { 14 matches!(
15 self,
15 ast::Expr::IfExpr(_) 16 ast::Expr::IfExpr(_)
16 | ast::Expr::LoopExpr(_) 17 | ast::Expr::LoopExpr(_)
17 | ast::Expr::ForExpr(_) 18 | ast::Expr::ForExpr(_)
18 | ast::Expr::WhileExpr(_) 19 | ast::Expr::WhileExpr(_)
19 | ast::Expr::BlockExpr(_) 20 | ast::Expr::BlockExpr(_)
20 | ast::Expr::MatchExpr(_) 21 | ast::Expr::MatchExpr(_)
21 | ast::Expr::EffectExpr(_) => true, 22 | ast::Expr::EffectExpr(_)
22 _ => false, 23 )
23 }
24 } 24 }
25 25
26 pub fn name_ref(&self) -> Option<ast::NameRef> { 26 pub fn name_ref(&self) -> Option<ast::NameRef> {
@@ -151,20 +151,20 @@ pub enum BinOp {
151 151
152impl BinOp { 152impl BinOp {
153 pub fn is_assignment(self) -> bool { 153 pub fn is_assignment(self) -> bool {
154 match self { 154 matches!(
155 self,
155 BinOp::Assignment 156 BinOp::Assignment
156 | BinOp::AddAssign 157 | BinOp::AddAssign
157 | BinOp::DivAssign 158 | BinOp::DivAssign
158 | BinOp::MulAssign 159 | BinOp::MulAssign
159 | BinOp::RemAssign 160 | BinOp::RemAssign
160 | BinOp::ShrAssign 161 | BinOp::ShrAssign
161 | BinOp::ShlAssign 162 | BinOp::ShlAssign
162 | BinOp::SubAssign 163 | BinOp::SubAssign
163 | BinOp::BitOrAssign 164 | BinOp::BitOrAssign
164 | BinOp::BitAndAssign 165 | BinOp::BitAndAssign
165 | BinOp::BitXorAssign => true, 166 | BinOp::BitXorAssign
166 _ => false, 167 )
167 }
168 } 168 }
169} 169}
170 170
diff --git a/crates/syntax/src/ast/generated/nodes.rs b/crates/syntax/src/ast/generated/nodes.rs
index 6097178b6..9a88fdb56 100644
--- a/crates/syntax/src/ast/generated/nodes.rs
+++ b/crates/syntax/src/ast/generated/nodes.rs
@@ -152,7 +152,7 @@ impl Attr {
152 pub fn l_brack_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T!['[']) } 152 pub fn l_brack_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T!['[']) }
153 pub fn path(&self) -> Option<Path> { support::child(&self.syntax) } 153 pub fn path(&self) -> Option<Path> { support::child(&self.syntax) }
154 pub fn eq_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![=]) } 154 pub fn eq_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![=]) }
155 pub fn literal(&self) -> Option<Literal> { support::child(&self.syntax) } 155 pub fn expr(&self) -> Option<Expr> { support::child(&self.syntax) }
156 pub fn token_tree(&self) -> Option<TokenTree> { support::child(&self.syntax) } 156 pub fn token_tree(&self) -> Option<TokenTree> { support::child(&self.syntax) }
157 pub fn r_brack_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![']']) } 157 pub fn r_brack_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![']']) }
158} 158}
@@ -632,12 +632,6 @@ impl WherePred {
632 pub fn ty(&self) -> Option<Type> { support::child(&self.syntax) } 632 pub fn ty(&self) -> Option<Type> { support::child(&self.syntax) }
633} 633}
634#[derive(Debug, Clone, PartialEq, Eq, Hash)] 634#[derive(Debug, Clone, PartialEq, Eq, Hash)]
635pub struct Literal {
636 pub(crate) syntax: SyntaxNode,
637}
638impl ast::AttrsOwner for Literal {}
639impl Literal {}
640#[derive(Debug, Clone, PartialEq, Eq, Hash)]
641pub struct ExprStmt { 635pub struct ExprStmt {
642 pub(crate) syntax: SyntaxNode, 636 pub(crate) syntax: SyntaxNode,
643} 637}
@@ -805,6 +799,12 @@ impl IndexExpr {
805 pub fn r_brack_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![']']) } 799 pub fn r_brack_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, T![']']) }
806} 800}
807#[derive(Debug, Clone, PartialEq, Eq, Hash)] 801#[derive(Debug, Clone, PartialEq, Eq, Hash)]
802pub struct Literal {
803 pub(crate) syntax: SyntaxNode,
804}
805impl ast::AttrsOwner for Literal {}
806impl Literal {}
807#[derive(Debug, Clone, PartialEq, Eq, Hash)]
808pub struct LoopExpr { 808pub struct LoopExpr {
809 pub(crate) syntax: SyntaxNode, 809 pub(crate) syntax: SyntaxNode,
810} 810}
@@ -2072,17 +2072,6 @@ impl AstNode for WherePred {
2072 } 2072 }
2073 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2073 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2074} 2074}
2075impl AstNode for Literal {
2076 fn can_cast(kind: SyntaxKind) -> bool { kind == LITERAL }
2077 fn cast(syntax: SyntaxNode) -> Option<Self> {
2078 if Self::can_cast(syntax.kind()) {
2079 Some(Self { syntax })
2080 } else {
2081 None
2082 }
2083 }
2084 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2085}
2086impl AstNode for ExprStmt { 2075impl AstNode for ExprStmt {
2087 fn can_cast(kind: SyntaxKind) -> bool { kind == EXPR_STMT } 2076 fn can_cast(kind: SyntaxKind) -> bool { kind == EXPR_STMT }
2088 fn cast(syntax: SyntaxNode) -> Option<Self> { 2077 fn cast(syntax: SyntaxNode) -> Option<Self> {
@@ -2259,6 +2248,17 @@ impl AstNode for IndexExpr {
2259 } 2248 }
2260 fn syntax(&self) -> &SyntaxNode { &self.syntax } 2249 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2261} 2250}
2251impl AstNode for Literal {
2252 fn can_cast(kind: SyntaxKind) -> bool { kind == LITERAL }
2253 fn cast(syntax: SyntaxNode) -> Option<Self> {
2254 if Self::can_cast(syntax.kind()) {
2255 Some(Self { syntax })
2256 } else {
2257 None
2258 }
2259 }
2260 fn syntax(&self) -> &SyntaxNode { &self.syntax }
2261}
2262impl AstNode for LoopExpr { 2262impl AstNode for LoopExpr {
2263 fn can_cast(kind: SyntaxKind) -> bool { kind == LOOP_EXPR } 2263 fn can_cast(kind: SyntaxKind) -> bool { kind == LOOP_EXPR }
2264 fn cast(syntax: SyntaxNode) -> Option<Self> { 2264 fn cast(syntax: SyntaxNode) -> Option<Self> {
@@ -3887,11 +3887,6 @@ impl std::fmt::Display for WherePred {
3887 std::fmt::Display::fmt(self.syntax(), f) 3887 std::fmt::Display::fmt(self.syntax(), f)
3888 } 3888 }
3889} 3889}
3890impl std::fmt::Display for Literal {
3891 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3892 std::fmt::Display::fmt(self.syntax(), f)
3893 }
3894}
3895impl std::fmt::Display for ExprStmt { 3890impl std::fmt::Display for ExprStmt {
3896 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 3891 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3897 std::fmt::Display::fmt(self.syntax(), f) 3892 std::fmt::Display::fmt(self.syntax(), f)
@@ -3972,6 +3967,11 @@ impl std::fmt::Display for IndexExpr {
3972 std::fmt::Display::fmt(self.syntax(), f) 3967 std::fmt::Display::fmt(self.syntax(), f)
3973 } 3968 }
3974} 3969}
3970impl std::fmt::Display for Literal {
3971 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3972 std::fmt::Display::fmt(self.syntax(), f)
3973 }
3974}
3975impl std::fmt::Display for LoopExpr { 3975impl std::fmt::Display for LoopExpr {
3976 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 3976 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3977 std::fmt::Display::fmt(self.syntax(), f) 3977 std::fmt::Display::fmt(self.syntax(), f)
diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs
index 810c8d4c8..7049affd9 100644
--- a/crates/syntax/src/ast/make.rs
+++ b/crates/syntax/src/ast/make.rs
@@ -532,7 +532,7 @@ fn ast_from_text<N: AstNode>(text: &str) -> N {
532} 532}
533 533
534fn unroot(n: SyntaxNode) -> SyntaxNode { 534fn unroot(n: SyntaxNode) -> SyntaxNode {
535 SyntaxNode::new_root(n.green().to_owned()) 535 SyntaxNode::new_root(n.green())
536} 536}
537 537
538pub mod tokens { 538pub mod tokens {
diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs
index 0b0d39a75..bdf907a21 100644
--- a/crates/syntax/src/ast/node_ext.rs
+++ b/crates/syntax/src/ast/node_ext.rs
@@ -58,10 +58,7 @@ impl From<ast::MacroDef> for Macro {
58 58
59impl AstNode for Macro { 59impl AstNode for Macro {
60 fn can_cast(kind: SyntaxKind) -> bool { 60 fn can_cast(kind: SyntaxKind) -> bool {
61 match kind { 61 matches!(kind, SyntaxKind::MACRO_RULES | SyntaxKind::MACRO_DEF)
62 SyntaxKind::MACRO_RULES | SyntaxKind::MACRO_DEF => true,
63 _ => false,
64 }
65 } 62 }
66 fn cast(syntax: SyntaxNode) -> Option<Self> { 63 fn cast(syntax: SyntaxNode) -> Option<Self> {
67 let res = match syntax.kind() { 64 let res = match syntax.kind() {
@@ -90,6 +87,36 @@ impl NameOwner for Macro {
90 87
91impl AttrsOwner for Macro {} 88impl AttrsOwner for Macro {}
92 89
90/// Basically an owned `dyn AttrsOwner` without extra boxing.
91pub struct AttrsOwnerNode {
92 node: SyntaxNode,
93}
94
95impl AttrsOwnerNode {
96 pub fn new<N: AttrsOwner>(node: N) -> Self {
97 AttrsOwnerNode { node: node.syntax().clone() }
98 }
99}
100
101impl AttrsOwner for AttrsOwnerNode {}
102impl AstNode for AttrsOwnerNode {
103 fn can_cast(_: SyntaxKind) -> bool
104 where
105 Self: Sized,
106 {
107 false
108 }
109 fn cast(_: SyntaxNode) -> Option<Self>
110 where
111 Self: Sized,
112 {
113 None
114 }
115 fn syntax(&self) -> &SyntaxNode {
116 &self.node
117 }
118}
119
93#[derive(Debug, Clone, PartialEq, Eq)] 120#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum AttrKind { 121pub enum AttrKind {
95 Inner, 122 Inner,
@@ -109,16 +136,6 @@ impl ast::Attr {
109 Some((self.simple_name()?, tt)) 136 Some((self.simple_name()?, tt))
110 } 137 }
111 138
112 pub fn as_simple_key_value(&self) -> Option<(SmolStr, SmolStr)> {
113 let lit = self.literal()?;
114 let key = self.simple_name()?;
115 let value_token = lit.syntax().first_token()?;
116
117 let value: SmolStr = ast::String::cast(value_token)?.value()?.into();
118
119 Some((key, value))
120 }
121
122 pub fn simple_name(&self) -> Option<SmolStr> { 139 pub fn simple_name(&self) -> Option<SmolStr> {
123 let path = self.path()?; 140 let path = self.path()?;
124 match (path.segment(), path.qualifier()) { 141 match (path.segment(), path.qualifier()) {
@@ -360,6 +377,15 @@ impl fmt::Display for NameOrNameRef {
360 } 377 }
361} 378}
362 379
380impl NameOrNameRef {
381 pub fn text(&self) -> &str {
382 match self {
383 NameOrNameRef::Name(name) => name.text(),
384 NameOrNameRef::NameRef(name_ref) => name_ref.text(),
385 }
386 }
387}
388
363impl ast::RecordPatField { 389impl ast::RecordPatField {
364 pub fn for_field_name_ref(field_name: &ast::NameRef) -> Option<ast::RecordPatField> { 390 pub fn for_field_name_ref(field_name: &ast::NameRef) -> Option<ast::RecordPatField> {
365 let candidate = field_name.syntax().parent().and_then(ast::RecordPatField::cast)?; 391 let candidate = field_name.syntax().parent().and_then(ast::RecordPatField::cast)?;
@@ -433,10 +459,8 @@ impl ast::FieldExpr {
433 pub fn field_access(&self) -> Option<FieldKind> { 459 pub fn field_access(&self) -> Option<FieldKind> {
434 if let Some(nr) = self.name_ref() { 460 if let Some(nr) = self.name_ref() {
435 Some(FieldKind::Name(nr)) 461 Some(FieldKind::Name(nr))
436 } else if let Some(tok) = self.index_token() {
437 Some(FieldKind::Index(tok))
438 } else { 462 } else {
439 None 463 self.index_token().map(FieldKind::Index)
440 } 464 }
441 } 465 }
442} 466}
@@ -453,16 +477,10 @@ impl ast::SlicePat {
453 let prefix = args 477 let prefix = args
454 .peeking_take_while(|p| match p { 478 .peeking_take_while(|p| match p {
455 ast::Pat::RestPat(_) => false, 479 ast::Pat::RestPat(_) => false,
456 ast::Pat::IdentPat(bp) => match bp.pat() { 480 ast::Pat::IdentPat(bp) => !matches!(bp.pat(), Some(ast::Pat::RestPat(_))),
457 Some(ast::Pat::RestPat(_)) => false,
458 _ => true,
459 },
460 ast::Pat::RefPat(rp) => match rp.pat() { 481 ast::Pat::RefPat(rp) => match rp.pat() {
461 Some(ast::Pat::RestPat(_)) => false, 482 Some(ast::Pat::RestPat(_)) => false,
462 Some(ast::Pat::IdentPat(bp)) => match bp.pat() { 483 Some(ast::Pat::IdentPat(bp)) => !matches!(bp.pat(), Some(ast::Pat::RestPat(_))),
463 Some(ast::Pat::RestPat(_)) => false,
464 _ => true,
465 },
466 _ => true, 484 _ => true,
467 }, 485 },
468 _ => true, 486 _ => true,
diff --git a/crates/syntax/src/ast/token_ext.rs b/crates/syntax/src/ast/token_ext.rs
index 6c242d126..090282d28 100644
--- a/crates/syntax/src/ast/token_ext.rs
+++ b/crates/syntax/src/ast/token_ext.rs
@@ -494,9 +494,8 @@ pub trait HasFormatSpecifier: AstToken {
494 } 494 }
495 _ => { 495 _ => {
496 while let Some((_, Ok(next_char))) = chars.peek() { 496 while let Some((_, Ok(next_char))) = chars.peek() {
497 match next_char { 497 if next_char == &'{' {
498 '{' => break, 498 break;
499 _ => {}
500 } 499 }
501 chars.next(); 500 chars.next();
502 } 501 }
diff --git a/crates/syntax/src/fuzz.rs b/crates/syntax/src/fuzz.rs
index fbb97aa27..aa84239d2 100644
--- a/crates/syntax/src/fuzz.rs
+++ b/crates/syntax/src/fuzz.rs
@@ -43,7 +43,7 @@ impl CheckReparse {
43 TextRange::at(delete_start.try_into().unwrap(), delete_len.try_into().unwrap()); 43 TextRange::at(delete_start.try_into().unwrap(), delete_len.try_into().unwrap());
44 let edited_text = 44 let edited_text =
45 format!("{}{}{}", &text[..delete_start], &insert, &text[delete_start + delete_len..]); 45 format!("{}{}{}", &text[..delete_start], &insert, &text[delete_start + delete_len..]);
46 let edit = Indel { delete, insert }; 46 let edit = Indel { insert, delete };
47 Some(CheckReparse { text, edit, edited_text }) 47 Some(CheckReparse { text, edit, edited_text })
48 } 48 }
49 49
diff --git a/crates/syntax/src/ted.rs b/crates/syntax/src/ted.rs
index 442dfa14a..be2b846b1 100644
--- a/crates/syntax/src/ted.rs
+++ b/crates/syntax/src/ted.rs
@@ -8,6 +8,33 @@ use parser::T;
8 8
9use crate::{ast::make, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken}; 9use crate::{ast::make, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken};
10 10
11/// Utility trait to allow calling `ted` functions with references or owned
12/// nodes. Do not use outside of this module.
13pub trait Element {
14 fn syntax_element(self) -> SyntaxElement;
15}
16
17impl<E: Element + Clone> Element for &'_ E {
18 fn syntax_element(self) -> SyntaxElement {
19 self.clone().syntax_element()
20 }
21}
22impl Element for SyntaxElement {
23 fn syntax_element(self) -> SyntaxElement {
24 self
25 }
26}
27impl Element for SyntaxNode {
28 fn syntax_element(self) -> SyntaxElement {
29 self.into()
30 }
31}
32impl Element for SyntaxToken {
33 fn syntax_element(self) -> SyntaxElement {
34 self.into()
35 }
36}
37
11#[derive(Debug)] 38#[derive(Debug)]
12pub struct Position { 39pub struct Position {
13 repr: PositionRepr, 40 repr: PositionRepr,
@@ -20,24 +47,24 @@ enum PositionRepr {
20} 47}
21 48
22impl Position { 49impl Position {
23 pub fn after(elem: impl Into<SyntaxElement>) -> Position { 50 pub fn after(elem: impl Element) -> Position {
24 let repr = PositionRepr::After(elem.into()); 51 let repr = PositionRepr::After(elem.syntax_element());
25 Position { repr } 52 Position { repr }
26 } 53 }
27 pub fn before(elem: impl Into<SyntaxElement>) -> Position { 54 pub fn before(elem: impl Element) -> Position {
28 let elem = elem.into(); 55 let elem = elem.syntax_element();
29 let repr = match elem.prev_sibling_or_token() { 56 let repr = match elem.prev_sibling_or_token() {
30 Some(it) => PositionRepr::After(it), 57 Some(it) => PositionRepr::After(it),
31 None => PositionRepr::FirstChild(elem.parent().unwrap()), 58 None => PositionRepr::FirstChild(elem.parent().unwrap()),
32 }; 59 };
33 Position { repr } 60 Position { repr }
34 } 61 }
35 pub fn first_child_of(node: impl Into<SyntaxNode>) -> Position { 62 pub fn first_child_of(node: &(impl Into<SyntaxNode> + Clone)) -> Position {
36 let repr = PositionRepr::FirstChild(node.into()); 63 let repr = PositionRepr::FirstChild(node.clone().into());
37 Position { repr } 64 Position { repr }
38 } 65 }
39 pub fn last_child_of(node: impl Into<SyntaxNode>) -> Position { 66 pub fn last_child_of(node: &(impl Into<SyntaxNode> + Clone)) -> Position {
40 let node = node.into(); 67 let node = node.clone().into();
41 let repr = match node.last_child_or_token() { 68 let repr = match node.last_child_or_token() {
42 Some(it) => PositionRepr::After(it), 69 Some(it) => PositionRepr::After(it),
43 None => PositionRepr::FirstChild(node), 70 None => PositionRepr::FirstChild(node),
@@ -46,11 +73,11 @@ impl Position {
46 } 73 }
47} 74}
48 75
49pub fn insert(position: Position, elem: impl Into<SyntaxElement>) { 76pub fn insert(position: Position, elem: impl Element) {
50 insert_all(position, vec![elem.into()]) 77 insert_all(position, vec![elem.syntax_element()])
51} 78}
52pub fn insert_raw(position: Position, elem: impl Into<SyntaxElement>) { 79pub fn insert_raw(position: Position, elem: impl Element) {
53 insert_all_raw(position, vec![elem.into()]) 80 insert_all_raw(position, vec![elem.syntax_element()])
54} 81}
55pub fn insert_all(position: Position, mut elements: Vec<SyntaxElement>) { 82pub fn insert_all(position: Position, mut elements: Vec<SyntaxElement>) {
56 if let Some(first) = elements.first() { 83 if let Some(first) = elements.first() {
@@ -73,17 +100,17 @@ pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) {
73 parent.splice_children(index..index, elements); 100 parent.splice_children(index..index, elements);
74} 101}
75 102
76pub fn remove(elem: impl Into<SyntaxElement>) { 103pub fn remove(elem: impl Element) {
77 let elem = elem.into(); 104 let elem = elem.syntax_element();
78 remove_all(elem.clone()..=elem) 105 remove_all(elem.clone()..=elem)
79} 106}
80pub fn remove_all(range: RangeInclusive<SyntaxElement>) { 107pub fn remove_all(range: RangeInclusive<SyntaxElement>) {
81 replace_all(range, Vec::new()) 108 replace_all(range, Vec::new())
82} 109}
83 110
84pub fn replace(old: impl Into<SyntaxElement>, new: impl Into<SyntaxElement>) { 111pub fn replace(old: impl Element, new: impl Element) {
85 let old = old.into(); 112 let old = old.syntax_element();
86 replace_all(old.clone()..=old, vec![new.into()]) 113 replace_all(old.clone()..=old, vec![new.syntax_element()])
87} 114}
88pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) { 115pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) {
89 let start = range.start().index(); 116 let start = range.start().index();
@@ -92,11 +119,11 @@ pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>
92 parent.splice_children(start..end + 1, new) 119 parent.splice_children(start..end + 1, new)
93} 120}
94 121
95pub fn append_child(node: impl Into<SyntaxNode>, child: impl Into<SyntaxElement>) { 122pub fn append_child(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) {
96 let position = Position::last_child_of(node); 123 let position = Position::last_child_of(node);
97 insert(position, child) 124 insert(position, child)
98} 125}
99pub fn append_child_raw(node: impl Into<SyntaxNode>, child: impl Into<SyntaxElement>) { 126pub fn append_child_raw(node: &(impl Into<SyntaxNode> + Clone), child: impl Element) {
100 let position = Position::last_child_of(node); 127 let position = Position::last_child_of(node);
101 insert_raw(position, child) 128 insert_raw(position, child)
102} 129}
diff --git a/crates/syntax/src/validation.rs b/crates/syntax/src/validation.rs
index 3e216fb70..bbe802174 100644
--- a/crates/syntax/src/validation.rs
+++ b/crates/syntax/src/validation.rs
@@ -297,7 +297,7 @@ fn validate_path_keywords(segment: ast::PathSegment, errors: &mut Vec<SyntaxErro
297 } 297 }
298 }; 298 };
299 } 299 }
300 return None; 300 None
301 } 301 }
302 302
303 fn all_supers(path: &ast::Path) -> bool { 303 fn all_supers(path: &ast::Path) -> bool {
@@ -314,7 +314,7 @@ fn validate_path_keywords(segment: ast::PathSegment, errors: &mut Vec<SyntaxErro
314 return all_supers(subpath); 314 return all_supers(subpath);
315 } 315 }
316 316
317 return true; 317 true
318 } 318 }
319} 319}
320 320