aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_db/src/ty_filter.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide_db/src/ty_filter.rs')
-rw-r--r--crates/ide_db/src/ty_filter.rs58
1 files changed, 58 insertions, 0 deletions
diff --git a/crates/ide_db/src/ty_filter.rs b/crates/ide_db/src/ty_filter.rs
new file mode 100644
index 000000000..63a945282
--- /dev/null
+++ b/crates/ide_db/src/ty_filter.rs
@@ -0,0 +1,58 @@
1//! This module contains structures for filtering the expected types.
2//! Use case for structures in this module is, for example, situation when you need to process
3//! only certain `Enum`s.
4
5use crate::RootDatabase;
6use hir::{Adt, Semantics, Type};
7use std::iter;
8use syntax::ast::{self, make};
9
10/// Enum types that implement `std::ops::Try` trait.
11#[derive(Clone, Copy)]
12pub enum TryEnum {
13 Result,
14 Option,
15}
16
17impl TryEnum {
18 const ALL: [TryEnum; 2] = [TryEnum::Option, TryEnum::Result];
19
20 /// Returns `Some(..)` if the provided type is an enum that implements `std::ops::Try`.
21 pub fn from_ty(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<TryEnum> {
22 let enum_ = match ty.as_adt() {
23 Some(Adt::Enum(it)) => it,
24 _ => return None,
25 };
26 TryEnum::ALL.iter().find_map(|&var| {
27 if &enum_.name(sema.db).to_string() == var.type_name() {
28 return Some(var);
29 }
30 None
31 })
32 }
33
34 pub fn happy_case(self) -> &'static str {
35 match self {
36 TryEnum::Result => "Ok",
37 TryEnum::Option => "Some",
38 }
39 }
40
41 pub fn sad_pattern(self) -> ast::Pat {
42 match self {
43 TryEnum::Result => make::tuple_struct_pat(
44 make::path_unqualified(make::path_segment(make::name_ref("Err"))),
45 iter::once(make::wildcard_pat().into()),
46 )
47 .into(),
48 TryEnum::Option => make::ident_pat(make::name("None")).into(),
49 }
50 }
51
52 fn type_name(self) -> &'static str {
53 match self {
54 TryEnum::Result => "Result",
55 TryEnum::Option => "Option",
56 }
57 }
58}