1700: remove  ast::*Kind enums r=matklad a=matklad

bors r+

Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2019-08-19 11:18:09 +00:00 committed by GitHub
commit 8704a74cd5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 548 additions and 540 deletions

View File

@ -1,6 +1,6 @@
use hir::{db::HirDatabase, HirDisplay, Ty};
use ra_syntax::{
ast::{AstNode, LetStmt, NameOwner, PatKind},
ast::{self, AstNode, LetStmt, NameOwner},
T,
};
@ -12,8 +12,8 @@ pub(crate) fn add_explicit_type(mut ctx: AssistCtx<impl HirDatabase>) -> Option<
let expr = stmt.initializer()?;
let pat = stmt.pat()?;
// Must be a binding
let pat = match pat.kind() {
PatKind::BindPat(bind_pat) => bind_pat,
let pat = match pat {
ast::Pat::BindPat(bind_pat) => bind_pat,
_ => return None,
};
let pat_range = pat.syntax().text_range();

View File

@ -5,7 +5,7 @@ use crate::{
use hir::{db::HirDatabase, HasSource};
use ra_db::FilePosition;
use ra_syntax::ast::{self, AstNode, ImplItemKind, NameOwner};
use ra_syntax::ast::{self, AstNode, NameOwner};
use ra_syntax::SmolStr;
#[derive(PartialEq)]
@ -49,11 +49,11 @@ fn add_missing_impl_members_inner(
resolve_target_trait_def(ctx.db, &analyzer, &impl_node)?
};
let def_name = |kind| -> Option<SmolStr> {
match kind {
ast::ImplItemKind::FnDef(def) => def.name(),
ast::ImplItemKind::TypeAliasDef(def) => def.name(),
ast::ImplItemKind::ConstDef(def) => def.name(),
let def_name = |item: &ast::ImplItem| -> Option<SmolStr> {
match item {
ast::ImplItem::FnDef(def) => def.name(),
ast::ImplItem::TypeAliasDef(def) => def.name(),
ast::ImplItem::ConstDef(def) => def.name(),
}
.map(|it| it.text().clone())
};
@ -62,15 +62,15 @@ fn add_missing_impl_members_inner(
let impl_items = impl_item_list.impl_items().collect::<Vec<_>>();
let missing_items: Vec<_> = trait_items
.filter(|t| def_name(t.kind()).is_some())
.filter(|t| match t.kind() {
ImplItemKind::FnDef(def) => match mode {
.filter(|t| def_name(t).is_some())
.filter(|t| match t {
ast::ImplItem::FnDef(def) => match mode {
AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(),
AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(),
},
_ => mode == AddMissingImplMembersMode::NoDefaultMethods,
})
.filter(|t| impl_items.iter().all(|i| def_name(i.kind()) != def_name(t.kind())))
.filter(|t| impl_items.iter().all(|i| def_name(i) != def_name(t)))
.collect();
if missing_items.is_empty() {
return None;
@ -78,8 +78,8 @@ fn add_missing_impl_members_inner(
ctx.add_action(AssistId(assist_id), label, |edit| {
let n_existing_items = impl_item_list.impl_items().count();
let items = missing_items.into_iter().map(|it| match it.kind() {
ImplItemKind::FnDef(def) => strip_docstring(add_body(def).into()),
let items = missing_items.into_iter().map(|it| match it {
ast::ImplItem::FnDef(def) => strip_docstring(add_body(def).into()),
_ => strip_docstring(it),
});
let mut ast_editor = AstEditor::new(impl_item_list);

View File

@ -7,12 +7,12 @@ use ra_syntax::ast::{self, AstNode};
use crate::{Assist, AssistCtx, AssistId};
fn is_trivial_arm(arm: &ast::MatchArm) -> bool {
fn single_pattern(arm: &ast::MatchArm) -> Option<ast::PatKind> {
fn single_pattern(arm: &ast::MatchArm) -> Option<ast::Pat> {
let (pat,) = arm.pats().collect_tuple()?;
Some(pat.kind())
Some(pat)
}
match single_pattern(arm) {
Some(ast::PatKind::PlaceholderPat(..)) => true,
Some(ast::Pat::PlaceholderPat(..)) => true,
_ => false,
}
}

View File

@ -1,6 +1,6 @@
use hir::db::HirDatabase;
use ra_syntax::{
ast::{self, AstNode, AstToken, ExprKind, PatKind},
ast::{self, AstNode, AstToken},
TextRange,
};
@ -9,8 +9,8 @@ use crate::{Assist, AssistCtx, AssistId};
pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
let let_stmt = ctx.node_at_offset::<ast::LetStmt>()?;
let bind_pat = match let_stmt.pat()?.kind() {
PatKind::BindPat(pat) => pat,
let bind_pat = match let_stmt.pat()? {
ast::Pat::BindPat(pat) => pat,
_ => return None,
};
if bind_pat.is_mutable() {
@ -48,28 +48,28 @@ pub(crate) fn inline_local_varialbe(mut ctx: AssistCtx<impl HirDatabase>) -> Opt
}
};
wrap_in_parens[i] = match (initializer_expr.kind(), usage_parent.kind()) {
(ExprKind::CallExpr(_), _)
| (ExprKind::IndexExpr(_), _)
| (ExprKind::MethodCallExpr(_), _)
| (ExprKind::FieldExpr(_), _)
| (ExprKind::TryExpr(_), _)
| (ExprKind::RefExpr(_), _)
| (ExprKind::Literal(_), _)
| (ExprKind::TupleExpr(_), _)
| (ExprKind::ArrayExpr(_), _)
| (ExprKind::ParenExpr(_), _)
| (ExprKind::PathExpr(_), _)
| (ExprKind::BlockExpr(_), _)
| (_, ExprKind::CallExpr(_))
| (_, ExprKind::TupleExpr(_))
| (_, ExprKind::ArrayExpr(_))
| (_, ExprKind::ParenExpr(_))
| (_, ExprKind::ForExpr(_))
| (_, ExprKind::WhileExpr(_))
| (_, ExprKind::BreakExpr(_))
| (_, ExprKind::ReturnExpr(_))
| (_, ExprKind::MatchExpr(_)) => false,
wrap_in_parens[i] = match (&initializer_expr, usage_parent) {
(ast::Expr::CallExpr(_), _)
| (ast::Expr::IndexExpr(_), _)
| (ast::Expr::MethodCallExpr(_), _)
| (ast::Expr::FieldExpr(_), _)
| (ast::Expr::TryExpr(_), _)
| (ast::Expr::RefExpr(_), _)
| (ast::Expr::Literal(_), _)
| (ast::Expr::TupleExpr(_), _)
| (ast::Expr::ArrayExpr(_), _)
| (ast::Expr::ParenExpr(_), _)
| (ast::Expr::PathExpr(_), _)
| (ast::Expr::BlockExpr(_), _)
| (_, ast::Expr::CallExpr(_))
| (_, ast::Expr::TupleExpr(_))
| (_, ast::Expr::ArrayExpr(_))
| (_, ast::Expr::ParenExpr(_))
| (_, ast::Expr::ForExpr(_))
| (_, ast::Expr::WhileExpr(_))
| (_, ast::Expr::BreakExpr(_))
| (_, ast::Expr::ReturnExpr(_))
| (_, ast::Expr::MatchExpr(_)) => false,
_ => true,
};
}

View File

@ -30,8 +30,8 @@ pub(crate) fn merge_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<A
ctx.add_action(AssistId("merge_match_arms"), "merge match arms", |edit| {
fn contains_placeholder(a: &MatchArm) -> bool {
a.pats().any(|x| match x.kind() {
ra_syntax::ast::PatKind::PlaceholderPat(..) => true,
a.pats().any(|x| match x {
ra_syntax::ast::Pat::PlaceholderPat(..) => true,
_ => false,
})
}

View File

@ -602,8 +602,8 @@ where
fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
let syntax_ptr = SyntaxNodePtr::new(expr.syntax());
match expr.kind() {
ast::ExprKind::IfExpr(e) => {
match expr {
ast::Expr::IfExpr(e) => {
let then_branch = self.collect_block_opt(e.then_branch());
let else_branch = e.else_branch().map(|b| match b {
@ -639,16 +639,16 @@ where
self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
}
ast::ExprKind::TryBlockExpr(e) => {
ast::Expr::TryBlockExpr(e) => {
let body = self.collect_block_opt(e.try_body());
self.alloc_expr(Expr::TryBlock { body }, syntax_ptr)
}
ast::ExprKind::BlockExpr(e) => self.collect_block_opt(e.block()),
ast::ExprKind::LoopExpr(e) => {
ast::Expr::BlockExpr(e) => self.collect_block_opt(e.block()),
ast::Expr::LoopExpr(e) => {
let body = self.collect_block_opt(e.loop_body());
self.alloc_expr(Expr::Loop { body }, syntax_ptr)
}
ast::ExprKind::WhileExpr(e) => {
ast::Expr::WhileExpr(e) => {
let body = self.collect_block_opt(e.loop_body());
let condition = match e.condition() {
@ -675,13 +675,13 @@ where
self.alloc_expr(Expr::While { condition, body }, syntax_ptr)
}
ast::ExprKind::ForExpr(e) => {
ast::Expr::ForExpr(e) => {
let iterable = self.collect_expr_opt(e.iterable());
let pat = self.collect_pat_opt(e.pat());
let body = self.collect_block_opt(e.loop_body());
self.alloc_expr(Expr::For { iterable, pat, body }, syntax_ptr)
}
ast::ExprKind::CallExpr(e) => {
ast::Expr::CallExpr(e) => {
let callee = self.collect_expr_opt(e.expr());
let args = if let Some(arg_list) = e.arg_list() {
arg_list.args().map(|e| self.collect_expr(e)).collect()
@ -690,7 +690,7 @@ where
};
self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
}
ast::ExprKind::MethodCallExpr(e) => {
ast::Expr::MethodCallExpr(e) => {
let receiver = self.collect_expr_opt(e.expr());
let args = if let Some(arg_list) = e.arg_list() {
arg_list.args().map(|e| self.collect_expr(e)).collect()
@ -704,7 +704,7 @@ where
syntax_ptr,
)
}
ast::ExprKind::MatchExpr(e) => {
ast::Expr::MatchExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
let arms = if let Some(match_arm_list) = e.match_arm_list() {
match_arm_list
@ -723,30 +723,30 @@ where
};
self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
}
ast::ExprKind::PathExpr(e) => {
ast::Expr::PathExpr(e) => {
let path =
e.path().and_then(Path::from_ast).map(Expr::Path).unwrap_or(Expr::Missing);
self.alloc_expr(path, syntax_ptr)
}
ast::ExprKind::ContinueExpr(_e) => {
ast::Expr::ContinueExpr(_e) => {
// FIXME: labels
self.alloc_expr(Expr::Continue, syntax_ptr)
}
ast::ExprKind::BreakExpr(e) => {
ast::Expr::BreakExpr(e) => {
let expr = e.expr().map(|e| self.collect_expr(e));
self.alloc_expr(Expr::Break { expr }, syntax_ptr)
}
ast::ExprKind::ParenExpr(e) => {
ast::Expr::ParenExpr(e) => {
let inner = self.collect_expr_opt(e.expr());
// make the paren expr point to the inner expression as well
self.source_map.expr_map.insert(syntax_ptr, inner);
inner
}
ast::ExprKind::ReturnExpr(e) => {
ast::Expr::ReturnExpr(e) => {
let expr = e.expr().map(|e| self.collect_expr(e));
self.alloc_expr(Expr::Return { expr }, syntax_ptr)
}
ast::ExprKind::StructLit(e) => {
ast::Expr::StructLit(e) => {
let path = e.path().and_then(Path::from_ast);
let mut field_ptrs = Vec::new();
let struct_lit = if let Some(nfl) = e.named_field_list() {
@ -787,7 +787,7 @@ where
}
res
}
ast::ExprKind::FieldExpr(e) => {
ast::Expr::FieldExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
let name = match e.field_access() {
Some(kind) => kind.as_name(),
@ -795,25 +795,25 @@ where
};
self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
}
ast::ExprKind::AwaitExpr(e) => {
ast::Expr::AwaitExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
self.alloc_expr(Expr::Await { expr }, syntax_ptr)
}
ast::ExprKind::TryExpr(e) => {
ast::Expr::TryExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
self.alloc_expr(Expr::Try { expr }, syntax_ptr)
}
ast::ExprKind::CastExpr(e) => {
ast::Expr::CastExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
let type_ref = TypeRef::from_ast_opt(e.type_ref());
self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
}
ast::ExprKind::RefExpr(e) => {
ast::Expr::RefExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
let mutability = Mutability::from_mutable(e.is_mut());
self.alloc_expr(Expr::Ref { expr, mutability }, syntax_ptr)
}
ast::ExprKind::PrefixExpr(e) => {
ast::Expr::PrefixExpr(e) => {
let expr = self.collect_expr_opt(e.expr());
if let Some(op) = e.op_kind() {
self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
@ -821,7 +821,7 @@ where
self.alloc_expr(Expr::Missing, syntax_ptr)
}
}
ast::ExprKind::LambdaExpr(e) => {
ast::Expr::LambdaExpr(e) => {
let mut args = Vec::new();
let mut arg_types = Vec::new();
if let Some(pl) = e.param_list() {
@ -835,18 +835,18 @@ where
let body = self.collect_expr_opt(e.body());
self.alloc_expr(Expr::Lambda { args, arg_types, body }, syntax_ptr)
}
ast::ExprKind::BinExpr(e) => {
ast::Expr::BinExpr(e) => {
let lhs = self.collect_expr_opt(e.lhs());
let rhs = self.collect_expr_opt(e.rhs());
let op = e.op_kind().map(BinaryOp::from);
self.alloc_expr(Expr::BinaryOp { lhs, rhs, op }, syntax_ptr)
}
ast::ExprKind::TupleExpr(e) => {
ast::Expr::TupleExpr(e) => {
let exprs = e.exprs().map(|expr| self.collect_expr(expr)).collect();
self.alloc_expr(Expr::Tuple { exprs }, syntax_ptr)
}
ast::ExprKind::ArrayExpr(e) => {
ast::Expr::ArrayExpr(e) => {
let kind = e.kind();
match kind {
@ -865,7 +865,7 @@ where
}
}
ast::ExprKind::Literal(e) => {
ast::Expr::Literal(e) => {
let lit = match e.kind() {
LiteralKind::IntNumber { suffix } => {
let known_name = suffix
@ -895,16 +895,16 @@ where
};
self.alloc_expr(Expr::Literal(lit), syntax_ptr)
}
ast::ExprKind::IndexExpr(e) => {
ast::Expr::IndexExpr(e) => {
let base = self.collect_expr_opt(e.base());
let index = self.collect_expr_opt(e.index());
self.alloc_expr(Expr::Index { base, index }, syntax_ptr)
}
// FIXME implement HIR for these:
ast::ExprKind::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
ast::ExprKind::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
ast::ExprKind::MacroCall(e) => {
ast::Expr::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
ast::Expr::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
ast::Expr::MacroCall(e) => {
let ast_id = self
.db
.ast_id_map(self.current_file_id)
@ -945,16 +945,14 @@ where
fn collect_block(&mut self, block: ast::Block) -> ExprId {
let statements = block
.statements()
.map(|s| match s.kind() {
ast::StmtKind::LetStmt(stmt) => {
.map(|s| match s {
ast::Stmt::LetStmt(stmt) => {
let pat = self.collect_pat_opt(stmt.pat());
let type_ref = stmt.ascribed_type().map(TypeRef::from_ast);
let initializer = stmt.initializer().map(|e| self.collect_expr(e));
Statement::Let { pat, type_ref, initializer }
}
ast::StmtKind::ExprStmt(stmt) => {
Statement::Expr(self.collect_expr_opt(stmt.expr()))
}
ast::Stmt::ExprStmt(stmt) => Statement::Expr(self.collect_expr_opt(stmt.expr())),
})
.collect();
let tail = block.expr().map(|e| self.collect_expr(e));
@ -970,33 +968,33 @@ where
}
fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
let pattern = match pat.kind() {
ast::PatKind::BindPat(bp) => {
let pattern = match &pat {
ast::Pat::BindPat(bp) => {
let name = bp.name().map(|nr| nr.as_name()).unwrap_or_else(Name::missing);
let annotation = BindingAnnotation::new(bp.is_mutable(), bp.is_ref());
let subpat = bp.pat().map(|subpat| self.collect_pat(subpat));
Pat::Bind { name, mode: annotation, subpat }
}
ast::PatKind::TupleStructPat(p) => {
ast::Pat::TupleStructPat(p) => {
let path = p.path().and_then(Path::from_ast);
let args = p.args().map(|p| self.collect_pat(p)).collect();
Pat::TupleStruct { path, args }
}
ast::PatKind::RefPat(p) => {
ast::Pat::RefPat(p) => {
let pat = self.collect_pat_opt(p.pat());
let mutability = Mutability::from_mutable(p.is_mut());
Pat::Ref { pat, mutability }
}
ast::PatKind::PathPat(p) => {
ast::Pat::PathPat(p) => {
let path = p.path().and_then(Path::from_ast);
path.map(Pat::Path).unwrap_or(Pat::Missing)
}
ast::PatKind::TuplePat(p) => {
ast::Pat::TuplePat(p) => {
let args = p.args().map(|p| self.collect_pat(p)).collect();
Pat::Tuple(args)
}
ast::PatKind::PlaceholderPat(_) => Pat::Wild,
ast::PatKind::StructPat(p) => {
ast::Pat::PlaceholderPat(_) => Pat::Wild,
ast::Pat::StructPat(p) => {
let path = p.path().and_then(Path::from_ast);
let field_pat_list =
p.field_pat_list().expect("every struct should have a field list");
@ -1022,8 +1020,8 @@ where
}
// FIXME: implement
ast::PatKind::LiteralPat(_) => Pat::Missing,
ast::PatKind::SlicePat(_) | ast::PatKind::RangePat(_) => Pat::Missing,
ast::Pat::LiteralPat(_) => Pat::Missing,
ast::Pat::SlicePat(_) | ast::Pat::RangePat(_) => Pat::Missing,
};
let ptr = AstPtr::new(&pat);
self.alloc_pat(pattern, Either::A(ptr))

View File

@ -137,8 +137,8 @@ impl GenericParams {
fn add_where_predicate_from_bound(&mut self, bound: ast::TypeBound, type_ref: TypeRef) {
let path = bound
.type_ref()
.and_then(|tr| match tr.kind() {
ast::TypeRefKind::PathType(path) => path.path(),
.and_then(|tr| match tr {
ast::TypeRef::PathType(path) => path.path(),
_ => None,
})
.and_then(Path::from_ast);

View File

@ -131,10 +131,10 @@ impl ImplData {
let items = if let Some(item_list) = node.item_list() {
item_list
.impl_items()
.map(|item_node| match item_node.kind() {
ast::ImplItemKind::FnDef(it) => Function { id: ctx.to_def(&it) }.into(),
ast::ImplItemKind::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(),
ast::ImplItemKind::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(),
.map(|item_node| match item_node {
ast::ImplItem::FnDef(it) => Function { id: ctx.to_def(&it) }.into(),
ast::ImplItem::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(),
ast::ImplItem::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(),
})
.collect()
} else {

View File

@ -207,24 +207,24 @@ impl RawItemsCollector {
}
fn add_item(&mut self, current_module: Option<Module>, item: ast::ModuleItem) {
let (kind, name) = match item.kind() {
ast::ModuleItemKind::Module(module) => {
let (kind, name) = match item {
ast::ModuleItem::Module(module) => {
self.add_module(current_module, module);
return;
}
ast::ModuleItemKind::UseItem(use_item) => {
ast::ModuleItem::UseItem(use_item) => {
self.add_use_item(current_module, use_item);
return;
}
ast::ModuleItemKind::ExternCrateItem(extern_crate) => {
ast::ModuleItem::ExternCrateItem(extern_crate) => {
self.add_extern_crate_item(current_module, extern_crate);
return;
}
ast::ModuleItemKind::ImplBlock(_) => {
ast::ModuleItem::ImplBlock(_) => {
// impls don't participate in name resolution
return;
}
ast::ModuleItemKind::StructDef(it) => {
ast::ModuleItem::StructDef(it) => {
let id = self.source_ast_id_map.ast_id(&it);
let name = it.name();
if it.is_union() {
@ -233,22 +233,22 @@ impl RawItemsCollector {
(DefKind::Struct(id), name)
}
}
ast::ModuleItemKind::EnumDef(it) => {
ast::ModuleItem::EnumDef(it) => {
(DefKind::Enum(self.source_ast_id_map.ast_id(&it)), it.name())
}
ast::ModuleItemKind::FnDef(it) => {
ast::ModuleItem::FnDef(it) => {
(DefKind::Function(self.source_ast_id_map.ast_id(&it)), it.name())
}
ast::ModuleItemKind::TraitDef(it) => {
ast::ModuleItem::TraitDef(it) => {
(DefKind::Trait(self.source_ast_id_map.ast_id(&it)), it.name())
}
ast::ModuleItemKind::TypeAliasDef(it) => {
ast::ModuleItem::TypeAliasDef(it) => {
(DefKind::TypeAlias(self.source_ast_id_map.ast_id(&it)), it.name())
}
ast::ModuleItemKind::ConstDef(it) => {
ast::ModuleItem::ConstDef(it) => {
(DefKind::Const(self.source_ast_id_map.ast_id(&it)), it.name())
}
ast::ModuleItemKind::StaticDef(it) => {
ast::ModuleItem::StaticDef(it) => {
(DefKind::Static(self.source_ast_id_map.ast_id(&it)), it.name())
}
};

View File

@ -30,10 +30,10 @@ impl TraitData {
let items = if let Some(item_list) = src.ast.item_list() {
item_list
.impl_items()
.map(|item_node| match item_node.kind() {
ast::ImplItemKind::FnDef(it) => Function { id: ctx.to_def(&it) }.into(),
ast::ImplItemKind::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(),
ast::ImplItemKind::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(),
.map(|item_node| match item_node {
ast::ImplItem::FnDef(it) => Function { id: ctx.to_def(&it) }.into(),
ast::ImplItem::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(),
ast::ImplItem::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(),
})
.collect()
} else {

View File

@ -57,28 +57,33 @@ pub enum TypeRef {
impl TypeRef {
/// Converts an `ast::TypeRef` to a `hir::TypeRef`.
pub(crate) fn from_ast(node: ast::TypeRef) -> Self {
use ra_syntax::ast::TypeRefKind::*;
match node.kind() {
ParenType(inner) => TypeRef::from_ast_opt(inner.type_ref()),
TupleType(inner) => TypeRef::Tuple(inner.fields().map(TypeRef::from_ast).collect()),
NeverType(..) => TypeRef::Never,
PathType(inner) => {
match node {
ast::TypeRef::ParenType(inner) => TypeRef::from_ast_opt(inner.type_ref()),
ast::TypeRef::TupleType(inner) => {
TypeRef::Tuple(inner.fields().map(TypeRef::from_ast).collect())
}
ast::TypeRef::NeverType(..) => TypeRef::Never,
ast::TypeRef::PathType(inner) => {
inner.path().and_then(Path::from_ast).map(TypeRef::Path).unwrap_or(TypeRef::Error)
}
PointerType(inner) => {
ast::TypeRef::PointerType(inner) => {
let inner_ty = TypeRef::from_ast_opt(inner.type_ref());
let mutability = Mutability::from_mutable(inner.is_mut());
TypeRef::RawPtr(Box::new(inner_ty), mutability)
}
ArrayType(inner) => TypeRef::Array(Box::new(TypeRef::from_ast_opt(inner.type_ref()))),
SliceType(inner) => TypeRef::Slice(Box::new(TypeRef::from_ast_opt(inner.type_ref()))),
ReferenceType(inner) => {
ast::TypeRef::ArrayType(inner) => {
TypeRef::Array(Box::new(TypeRef::from_ast_opt(inner.type_ref())))
}
ast::TypeRef::SliceType(inner) => {
TypeRef::Slice(Box::new(TypeRef::from_ast_opt(inner.type_ref())))
}
ast::TypeRef::ReferenceType(inner) => {
let inner_ty = TypeRef::from_ast_opt(inner.type_ref());
let mutability = Mutability::from_mutable(inner.is_mut());
TypeRef::Reference(Box::new(inner_ty), mutability)
}
PlaceholderType(_inner) => TypeRef::Placeholder,
FnPointerType(inner) => {
ast::TypeRef::PlaceholderType(_inner) => TypeRef::Placeholder,
ast::TypeRef::FnPointerType(inner) => {
let ret_ty = TypeRef::from_ast_opt(inner.ret_type().and_then(|rt| rt.type_ref()));
let mut params = if let Some(pl) = inner.param_list() {
pl.params().map(|p| p.ascribed_type()).map(TypeRef::from_ast_opt).collect()
@ -89,9 +94,9 @@ impl TypeRef {
TypeRef::Fn(params)
}
// for types are close enough for our purposes to the inner type for now...
ForType(inner) => TypeRef::from_ast_opt(inner.type_ref()),
ImplTraitType(_inner) => TypeRef::Error,
DynTraitType(_inner) => TypeRef::Error,
ast::TypeRef::ForType(inner) => TypeRef::from_ast_opt(inner.type_ref()),
ast::TypeRef::ImplTraitType(_inner) => TypeRef::Error,
ast::TypeRef::DynTraitType(_inner) => TypeRef::Error,
}
}

View File

@ -91,8 +91,8 @@ impl FnCallNode {
fn name_ref(&self) -> Option<ast::NameRef> {
match self {
FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()?.kind() {
ast::ExprKind::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? {
ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
_ => return None,
}),

View File

@ -33,13 +33,11 @@ fn impls_for_def(
node: &ast::NominalDef,
module: hir::Module,
) -> Option<Vec<NavigationTarget>> {
let ty = match node.kind() {
ast::NominalDefKind::StructDef(def) => {
let ty = match node {
ast::NominalDef::StructDef(def) => {
source_binder::struct_from_module(db, module, &def).ty(db)
}
ast::NominalDefKind::EnumDef(def) => {
source_binder::enum_from_module(db, module, &def).ty(db)
}
ast::NominalDef::EnumDef(def) => source_binder::enum_from_module(db, module, &def).ty(db),
};
let krate = module.krate(db)?;

View File

@ -3,7 +3,7 @@ use hir::{HirDisplay, SourceAnalyzer, Ty};
use ra_syntax::{
algo::visit::{visitor, Visitor},
ast::{
AstNode, ForExpr, IfExpr, LambdaExpr, LetStmt, MatchArmList, Pat, PatKind, SourceFile,
self, AstNode, ForExpr, IfExpr, LambdaExpr, LetStmt, MatchArmList, SourceFile,
TypeAscriptionOwner, WhileExpr,
},
SmolStr, SyntaxKind, SyntaxNode, TextRange,
@ -88,7 +88,7 @@ fn get_inlay_hints(
fn get_pat_type_hints(
db: &RootDatabase,
analyzer: &SourceAnalyzer,
root_pat: Pat,
root_pat: ast::Pat,
skip_root_pat_hint: bool,
) -> Vec<InlayHint> {
let original_pat = &root_pat.clone();
@ -108,27 +108,27 @@ fn get_pat_type_hints(
.collect()
}
fn get_leaf_pats(root_pat: Pat) -> Vec<Pat> {
let mut pats_to_process = std::collections::VecDeque::<Pat>::new();
fn get_leaf_pats(root_pat: ast::Pat) -> Vec<ast::Pat> {
let mut pats_to_process = std::collections::VecDeque::<ast::Pat>::new();
pats_to_process.push_back(root_pat);
let mut leaf_pats = Vec::new();
while let Some(maybe_leaf_pat) = pats_to_process.pop_front() {
match maybe_leaf_pat.kind() {
PatKind::BindPat(bind_pat) => {
match &maybe_leaf_pat {
ast::Pat::BindPat(bind_pat) => {
if let Some(pat) = bind_pat.pat() {
pats_to_process.push_back(pat);
} else {
leaf_pats.push(maybe_leaf_pat);
}
}
PatKind::TuplePat(tuple_pat) => {
ast::Pat::TuplePat(tuple_pat) => {
for arg_pat in tuple_pat.args() {
pats_to_process.push_back(arg_pat);
}
}
PatKind::StructPat(struct_pat) => {
ast::Pat::StructPat(struct_pat) => {
if let Some(pat_list) = struct_pat.field_pat_list() {
pats_to_process.extend(
pat_list
@ -139,12 +139,12 @@ fn get_leaf_pats(root_pat: Pat) -> Vec<Pat> {
.filter(|pat| pat.syntax().kind() != SyntaxKind::BIND_PAT)
})
.chain(pat_list.bind_pats().map(|bind_pat| {
bind_pat.pat().unwrap_or_else(|| Pat::from(bind_pat))
bind_pat.pat().unwrap_or_else(|| ast::Pat::from(bind_pat))
})),
);
}
}
PatKind::TupleStructPat(tuple_struct_pat) => {
ast::Pat::TupleStructPat(tuple_struct_pat) => {
for arg_pat in tuple_struct_pat.args() {
pats_to_process.push_back(arg_pat);
}
@ -158,7 +158,7 @@ fn get_leaf_pats(root_pat: Pat) -> Vec<Pat> {
fn get_node_displayable_type(
db: &RootDatabase,
analyzer: &SourceAnalyzer,
node_pat: &Pat,
node_pat: &ast::Pat,
) -> Option<Ty> {
analyzer.type_of_pat(db, node_pat).and_then(|resolved_type| {
if let Ty::Apply(_) = resolved_type {

View File

@ -75,7 +75,7 @@ pub(crate) fn find_all_refs(
let analyzer = hir::SourceAnalyzer::new(db, position.file_id, name_ref.syntax(), None);
let resolved = analyzer.resolve_local_name(&name_ref)?;
if let Either::A(ptr) = resolved.ptr() {
if let ast::PatKind::BindPat(binding) = ptr.to_node(source_file.syntax()).kind() {
if let ast::Pat::BindPat(binding) = ptr.to_node(source_file.syntax()) {
return Some((binding, analyzer));
}
}

View File

@ -54,8 +54,8 @@ fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Opti
let has_test_function = module
.item_list()?
.items()
.filter_map(|it| match it.kind() {
ast::ModuleItemKind::FnDef(it) => Some(it),
.filter_map(|it| match it {
ast::ModuleItem::FnDef(it) => Some(it),
_ => None,
})
.any(|f| f.has_atom_attr("test"));

File diff suppressed because it is too large Load Diff

View File

@ -186,8 +186,8 @@ fn api_walkthrough() {
// Let's fetch the `foo` function.
let mut func = None;
for item in file.items() {
match item.kind() {
ast::ModuleItemKind::FnDef(f) => func = Some(f),
match item {
ast::ModuleItem::FnDef(f) => func = Some(f),
_ => unreachable!(),
}
}
@ -206,12 +206,12 @@ fn api_walkthrough() {
let block: ast::Block = func.body().unwrap();
let expr: ast::Expr = block.expr().unwrap();
// "Enum"-like nodes are represented using the "kind" pattern. It allows us
// to match exhaustively against all flavors of nodes, while maintaining
// internal representation flexibility. The drawback is that one can't write
// nested matches as one pattern.
let bin_expr: ast::BinExpr = match expr.kind() {
ast::ExprKind::BinExpr(e) => e,
// Enums are used to group related ast nodes together, and can be used for
// matching. However, because there are no public fields, it's possible to
// match only the top level enum: that is the price we pay for increased API
// flexibility
let bin_expr: &ast::BinExpr = match &expr {
ast::Expr::BinExpr(e) => e,
_ => unreachable!(),
};

View File

@ -37,41 +37,72 @@ fn generate_ast(grammar: &Grammar) -> Result<String> {
ast_node.variants.iter().map(|var| format_ident!("{}", var)).collect::<Vec<_>>();
let name = format_ident!("{}", name);
let kinds = if variants.is_empty() { vec![name.clone()] } else { variants.clone() }
.into_iter()
.map(|name| format_ident!("{}", name.to_string().to_shouty_snake_case()))
.collect::<Vec<_>>();
let adt = if variants.is_empty() {
let kind = format_ident!("{}", name.to_string().to_shouty_snake_case());
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct #name {
pub(crate) syntax: SyntaxNode,
}
let variants = if variants.is_empty() {
None
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#kind => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }
}
fn syntax(&self) -> &SyntaxNode { &self.syntax }
}
}
} else {
let kind_enum = format_ident!("{}Kind", name);
Some(quote!(
pub enum #kind_enum {
let kinds = variants
.iter()
.map(|name| format_ident!("{}", name.to_string().to_shouty_snake_case()))
.collect::<Vec<_>>();
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum #name {
#(#variants(#variants),)*
}
#(
impl From<#variants> for #name {
fn from(node: #variants) -> #name {
#name { syntax: node.syntax }
#name::#variants(node)
}
}
)*
impl #name {
pub fn kind(&self) -> #kind_enum {
let syntax = self.syntax.clone();
match syntax.kind() {
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#(#kinds)|* => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
let res = match syntax.kind() {
#(
#kinds =>
#kind_enum::#variants(#variants { syntax }),
#kinds => #name::#variants(#variants { syntax }),
)*
_ => return None,
};
Some(res)
}
fn syntax(&self) -> &SyntaxNode {
match self {
#(
#name::#variants(it) => &it.syntax,
)*
_ => unreachable!(),
}
}
}
))
}
};
let traits = ast_node.traits.iter().map(|trait_name| {
@ -105,25 +136,7 @@ fn generate_ast(grammar: &Grammar) -> Result<String> {
});
quote! {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct #name {
pub(crate) syntax: SyntaxNode,
}
impl AstNode for #name {
fn can_cast(kind: SyntaxKind) -> bool {
match kind {
#(#kinds)|* => true,
_ => false,
}
}
fn cast(syntax: SyntaxNode) -> Option<Self> {
if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }
}
fn syntax(&self) -> &SyntaxNode { &self.syntax }
}
#variants
#adt
#(#traits)*