diff options
author | bors[bot] <26634292+bors[bot]@users.noreply.github.com> | 2019-10-30 15:07:12 +0000 |
---|---|---|
committer | GitHub <[email protected]> | 2019-10-30 15:07:12 +0000 |
commit | 5806195bc1cdb1ca3fa257e99fd6e0dd897713a9 (patch) | |
tree | 92b54891047977e6483e430a467d8e561ea3bc53 /crates/ra_hir | |
parent | f996b6019bd2f388bd9994ea83f25487eb111560 (diff) | |
parent | e34e71c62d9b4cf0ab237969e03ecde893ab347b (diff) |
Merge #2128
2128: move raw_items to hir_def r=matklad a=matklad
Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/ra_hir')
34 files changed, 116 insertions, 1444 deletions
diff --git a/crates/ra_hir/src/adt.rs b/crates/ra_hir/src/adt.rs index 3e9cd3c63..d16b3a1cc 100644 --- a/crates/ra_hir/src/adt.rs +++ b/crates/ra_hir/src/adt.rs | |||
@@ -3,13 +3,13 @@ | |||
3 | 3 | ||
4 | use std::sync::Arc; | 4 | use std::sync::Arc; |
5 | 5 | ||
6 | use hir_def::{name::AsName, type_ref::TypeRef}; | ||
6 | use ra_arena::{impl_arena_id, Arena, RawId}; | 7 | use ra_arena::{impl_arena_id, Arena, RawId}; |
7 | use ra_syntax::ast::{self, NameOwner, StructKind, TypeAscriptionOwner}; | 8 | use ra_syntax::ast::{self, NameOwner, StructKind, TypeAscriptionOwner}; |
8 | 9 | ||
9 | use crate::{ | 10 | use crate::{ |
10 | db::{AstDatabase, DefDatabase, HirDatabase}, | 11 | db::{AstDatabase, DefDatabase, HirDatabase}, |
11 | type_ref::TypeRef, | 12 | Enum, EnumVariant, FieldSource, HasSource, Module, Name, Source, Struct, StructField, |
12 | AsName, Enum, EnumVariant, FieldSource, HasSource, Module, Name, Source, Struct, StructField, | ||
13 | }; | 13 | }; |
14 | 14 | ||
15 | impl Struct { | 15 | impl Struct { |
diff --git a/crates/ra_hir/src/attr.rs b/crates/ra_hir/src/attr.rs deleted file mode 100644 index bd159a566..000000000 --- a/crates/ra_hir/src/attr.rs +++ /dev/null | |||
@@ -1,90 +0,0 @@ | |||
1 | //! A higher level attributes based on TokenTree, with also some shortcuts. | ||
2 | |||
3 | use std::sync::Arc; | ||
4 | |||
5 | use mbe::ast_to_token_tree; | ||
6 | use ra_cfg::CfgOptions; | ||
7 | use ra_syntax::{ | ||
8 | ast::{self, AstNode, AttrsOwner}, | ||
9 | SmolStr, | ||
10 | }; | ||
11 | use tt::Subtree; | ||
12 | |||
13 | use crate::{db::AstDatabase, path::Path, HirFileId, Source}; | ||
14 | |||
15 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
16 | pub(crate) struct Attr { | ||
17 | pub(crate) path: Path, | ||
18 | pub(crate) input: Option<AttrInput>, | ||
19 | } | ||
20 | |||
21 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
22 | pub enum AttrInput { | ||
23 | Literal(SmolStr), | ||
24 | TokenTree(Subtree), | ||
25 | } | ||
26 | |||
27 | impl Attr { | ||
28 | pub(crate) fn from_src( | ||
29 | Source { file_id, ast }: Source<ast::Attr>, | ||
30 | db: &impl AstDatabase, | ||
31 | ) -> Option<Attr> { | ||
32 | let path = Path::from_src(Source { file_id, ast: ast.path()? }, db)?; | ||
33 | let input = match ast.input() { | ||
34 | None => None, | ||
35 | Some(ast::AttrInput::Literal(lit)) => { | ||
36 | // FIXME: escape? raw string? | ||
37 | let value = lit.syntax().first_token()?.text().trim_matches('"').into(); | ||
38 | Some(AttrInput::Literal(value)) | ||
39 | } | ||
40 | Some(ast::AttrInput::TokenTree(tt)) => { | ||
41 | Some(AttrInput::TokenTree(ast_to_token_tree(&tt)?.0)) | ||
42 | } | ||
43 | }; | ||
44 | |||
45 | Some(Attr { path, input }) | ||
46 | } | ||
47 | |||
48 | pub(crate) fn from_attrs_owner( | ||
49 | file_id: HirFileId, | ||
50 | owner: &dyn AttrsOwner, | ||
51 | db: &impl AstDatabase, | ||
52 | ) -> Option<Arc<[Attr]>> { | ||
53 | let mut attrs = owner.attrs().peekable(); | ||
54 | if attrs.peek().is_none() { | ||
55 | // Avoid heap allocation | ||
56 | return None; | ||
57 | } | ||
58 | Some(attrs.flat_map(|ast| Attr::from_src(Source { file_id, ast }, db)).collect()) | ||
59 | } | ||
60 | |||
61 | pub(crate) fn is_simple_atom(&self, name: &str) -> bool { | ||
62 | // FIXME: Avoid cloning | ||
63 | self.path.as_ident().map_or(false, |s| s.to_string() == name) | ||
64 | } | ||
65 | |||
66 | // FIXME: handle cfg_attr :-) | ||
67 | pub(crate) fn as_cfg(&self) -> Option<&Subtree> { | ||
68 | if !self.is_simple_atom("cfg") { | ||
69 | return None; | ||
70 | } | ||
71 | match &self.input { | ||
72 | Some(AttrInput::TokenTree(subtree)) => Some(subtree), | ||
73 | _ => None, | ||
74 | } | ||
75 | } | ||
76 | |||
77 | pub(crate) fn as_path(&self) -> Option<&SmolStr> { | ||
78 | if !self.is_simple_atom("path") { | ||
79 | return None; | ||
80 | } | ||
81 | match &self.input { | ||
82 | Some(AttrInput::Literal(it)) => Some(it), | ||
83 | _ => None, | ||
84 | } | ||
85 | } | ||
86 | |||
87 | pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> Option<bool> { | ||
88 | cfg_options.is_cfg_enabled(self.as_cfg()?) | ||
89 | } | ||
90 | } | ||
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 1a790b2f3..d865c972e 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -5,8 +5,15 @@ pub(crate) mod docs; | |||
5 | 5 | ||
6 | use std::sync::Arc; | 6 | use std::sync::Arc; |
7 | 7 | ||
8 | use hir_def::{CrateModuleId, ModuleId}; | 8 | use hir_def::{ |
9 | use ra_db::{CrateId, Edition, FileId}; | 9 | name::{ |
10 | self, AsName, BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, | ||
11 | U16, U32, U64, U8, USIZE, | ||
12 | }, | ||
13 | type_ref::{Mutability, TypeRef}, | ||
14 | CrateModuleId, ModuleId, | ||
15 | }; | ||
16 | use ra_db::{CrateId, Edition}; | ||
10 | use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner}; | 17 | use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner}; |
11 | 18 | ||
12 | use crate::{ | 19 | use crate::{ |
@@ -20,10 +27,6 @@ use crate::{ | |||
20 | TypeAliasId, | 27 | TypeAliasId, |
21 | }, | 28 | }, |
22 | impl_block::ImplBlock, | 29 | impl_block::ImplBlock, |
23 | name::{ | ||
24 | BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, U16, U32, U64, | ||
25 | U8, USIZE, | ||
26 | }, | ||
27 | nameres::{ImportId, ModuleScope, Namespace}, | 30 | nameres::{ImportId, ModuleScope, Namespace}, |
28 | resolve::{Resolver, Scope, TypeNs}, | 31 | resolve::{Resolver, Scope, TypeNs}, |
29 | traits::TraitData, | 32 | traits::TraitData, |
@@ -31,9 +34,7 @@ use crate::{ | |||
31 | primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness}, | 34 | primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness}, |
32 | InferenceResult, TraitRef, | 35 | InferenceResult, TraitRef, |
33 | }, | 36 | }, |
34 | type_ref::Mutability, | 37 | Either, HasSource, Name, Ty, |
35 | type_ref::TypeRef, | ||
36 | AsName, AstId, Either, HasSource, Name, Ty, | ||
37 | }; | 38 | }; |
38 | 39 | ||
39 | /// hir::Crate describes a single crate. It's the main interface with which | 40 | /// hir::Crate describes a single crate. It's the main interface with which |
@@ -147,31 +148,7 @@ impl_froms!( | |||
147 | BuiltinType | 148 | BuiltinType |
148 | ); | 149 | ); |
149 | 150 | ||
150 | pub enum ModuleSource { | 151 | pub use hir_def::ModuleSource; |
151 | SourceFile(ast::SourceFile), | ||
152 | Module(ast::Module), | ||
153 | } | ||
154 | |||
155 | impl ModuleSource { | ||
156 | pub(crate) fn new( | ||
157 | db: &(impl DefDatabase + AstDatabase), | ||
158 | file_id: Option<FileId>, | ||
159 | decl_id: Option<AstId<ast::Module>>, | ||
160 | ) -> ModuleSource { | ||
161 | match (file_id, decl_id) { | ||
162 | (Some(file_id), _) => { | ||
163 | let source_file = db.parse(file_id).tree(); | ||
164 | ModuleSource::SourceFile(source_file) | ||
165 | } | ||
166 | (None, Some(item_id)) => { | ||
167 | let module = item_id.to_node(db); | ||
168 | assert!(module.item_list().is_some(), "expected inline module"); | ||
169 | ModuleSource::Module(module) | ||
170 | } | ||
171 | (None, None) => panic!(), | ||
172 | } | ||
173 | } | ||
174 | } | ||
175 | 152 | ||
176 | impl Module { | 153 | impl Module { |
177 | pub(crate) fn new(krate: Crate, crate_module_id: CrateModuleId) -> Module { | 154 | pub(crate) fn new(krate: Crate, crate_module_id: CrateModuleId) -> Module { |
@@ -922,9 +899,7 @@ impl Trait { | |||
922 | .where_predicates | 899 | .where_predicates |
923 | .iter() | 900 | .iter() |
924 | .filter_map(|pred| match &pred.type_ref { | 901 | .filter_map(|pred| match &pred.type_ref { |
925 | TypeRef::Path(p) if p.as_ident() == Some(&crate::name::SELF_TYPE) => { | 902 | TypeRef::Path(p) if p.as_ident() == Some(&name::SELF_TYPE) => pred.bound.as_path(), |
926 | pred.bound.as_path() | ||
927 | } | ||
928 | _ => None, | 903 | _ => None, |
929 | }) | 904 | }) |
930 | .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path) { | 905 | .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path) { |
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 8f6cb2da7..ebfd970eb 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -12,18 +12,21 @@ use crate::{ | |||
12 | ids, | 12 | ids, |
13 | impl_block::{ImplBlock, ImplSourceMap, ModuleImplBlocks}, | 13 | impl_block::{ImplBlock, ImplSourceMap, ModuleImplBlocks}, |
14 | lang_item::{LangItemTarget, LangItems}, | 14 | lang_item::{LangItemTarget, LangItems}, |
15 | nameres::{CrateDefMap, ImportSourceMap, Namespace, RawItems}, | 15 | nameres::{CrateDefMap, Namespace}, |
16 | traits::TraitData, | 16 | traits::TraitData, |
17 | ty::{ | 17 | ty::{ |
18 | method_resolution::CrateImplBlocks, traits::Impl, CallableDef, FnSig, GenericPredicate, | 18 | method_resolution::CrateImplBlocks, traits::Impl, CallableDef, FnSig, GenericPredicate, |
19 | InferenceResult, Substs, Ty, TypableDef, TypeCtor, | 19 | InferenceResult, Substs, Ty, TypableDef, TypeCtor, |
20 | }, | 20 | }, |
21 | type_alias::TypeAliasData, | 21 | type_alias::TypeAliasData, |
22 | Const, ConstData, Crate, DefWithBody, Enum, ExprScopes, FnData, Function, HirFileId, Module, | 22 | Const, ConstData, Crate, DefWithBody, Enum, ExprScopes, FnData, Function, Module, Static, |
23 | Static, Struct, StructField, Trait, TypeAlias, | 23 | Struct, StructField, Trait, TypeAlias, |
24 | }; | 24 | }; |
25 | 25 | ||
26 | pub use hir_def::db::{InternDatabase, InternDatabaseStorage}; | 26 | pub use hir_def::db::{ |
27 | DefDatabase2, DefDatabase2Storage, InternDatabase, InternDatabaseStorage, RawItemsQuery, | ||
28 | RawItemsWithSourceMapQuery, | ||
29 | }; | ||
27 | pub use hir_expand::db::{ | 30 | pub use hir_expand::db::{ |
28 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, | 31 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, |
29 | ParseMacroQuery, | 32 | ParseMacroQuery, |
@@ -32,7 +35,7 @@ pub use hir_expand::db::{ | |||
32 | // This database uses `AstDatabase` internally, | 35 | // This database uses `AstDatabase` internally, |
33 | #[salsa::query_group(DefDatabaseStorage)] | 36 | #[salsa::query_group(DefDatabaseStorage)] |
34 | #[salsa::requires(AstDatabase)] | 37 | #[salsa::requires(AstDatabase)] |
35 | pub trait DefDatabase: InternDatabase + HirDebugDatabase + AstDatabase { | 38 | pub trait DefDatabase: HirDebugDatabase + DefDatabase2 { |
36 | #[salsa::invoke(crate::adt::StructData::struct_data_query)] | 39 | #[salsa::invoke(crate::adt::StructData::struct_data_query)] |
37 | fn struct_data(&self, s: Struct) -> Arc<StructData>; | 40 | fn struct_data(&self, s: Struct) -> Arc<StructData>; |
38 | 41 | ||
@@ -45,15 +48,6 @@ pub trait DefDatabase: InternDatabase + HirDebugDatabase + AstDatabase { | |||
45 | #[salsa::invoke(crate::traits::TraitItemsIndex::trait_items_index)] | 48 | #[salsa::invoke(crate::traits::TraitItemsIndex::trait_items_index)] |
46 | fn trait_items_index(&self, module: Module) -> crate::traits::TraitItemsIndex; | 49 | fn trait_items_index(&self, module: Module) -> crate::traits::TraitItemsIndex; |
47 | 50 | ||
48 | #[salsa::invoke(RawItems::raw_items_with_source_map_query)] | ||
49 | fn raw_items_with_source_map( | ||
50 | &self, | ||
51 | file_id: HirFileId, | ||
52 | ) -> (Arc<RawItems>, Arc<ImportSourceMap>); | ||
53 | |||
54 | #[salsa::invoke(RawItems::raw_items_query)] | ||
55 | fn raw_items(&self, file_id: HirFileId) -> Arc<RawItems>; | ||
56 | |||
57 | #[salsa::invoke(CrateDefMap::crate_def_map_query)] | 51 | #[salsa::invoke(CrateDefMap::crate_def_map_query)] |
58 | fn crate_def_map(&self, krate: Crate) -> Arc<CrateDefMap>; | 52 | fn crate_def_map(&self, krate: Crate) -> Arc<CrateDefMap>; |
59 | 53 | ||
diff --git a/crates/ra_hir/src/either.rs b/crates/ra_hir/src/either.rs deleted file mode 100644 index 83583ef8b..000000000 --- a/crates/ra_hir/src/either.rs +++ /dev/null | |||
@@ -1,54 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
4 | pub enum Either<A, B> { | ||
5 | A(A), | ||
6 | B(B), | ||
7 | } | ||
8 | |||
9 | impl<A, B> Either<A, B> { | ||
10 | pub fn either<R, F1, F2>(self, f1: F1, f2: F2) -> R | ||
11 | where | ||
12 | F1: FnOnce(A) -> R, | ||
13 | F2: FnOnce(B) -> R, | ||
14 | { | ||
15 | match self { | ||
16 | Either::A(a) => f1(a), | ||
17 | Either::B(b) => f2(b), | ||
18 | } | ||
19 | } | ||
20 | pub fn map<U, V, F1, F2>(self, f1: F1, f2: F2) -> Either<U, V> | ||
21 | where | ||
22 | F1: FnOnce(A) -> U, | ||
23 | F2: FnOnce(B) -> V, | ||
24 | { | ||
25 | match self { | ||
26 | Either::A(a) => Either::A(f1(a)), | ||
27 | Either::B(b) => Either::B(f2(b)), | ||
28 | } | ||
29 | } | ||
30 | pub fn map_a<U, F>(self, f: F) -> Either<U, B> | ||
31 | where | ||
32 | F: FnOnce(A) -> U, | ||
33 | { | ||
34 | self.map(f, |it| it) | ||
35 | } | ||
36 | pub fn a(self) -> Option<A> { | ||
37 | match self { | ||
38 | Either::A(it) => Some(it), | ||
39 | Either::B(_) => None, | ||
40 | } | ||
41 | } | ||
42 | pub fn b(self) -> Option<B> { | ||
43 | match self { | ||
44 | Either::A(_) => None, | ||
45 | Either::B(it) => Some(it), | ||
46 | } | ||
47 | } | ||
48 | pub fn as_ref(&self) -> Either<&A, &B> { | ||
49 | match self { | ||
50 | Either::A(it) => Either::A(it), | ||
51 | Either::B(it) => Either::B(it), | ||
52 | } | ||
53 | } | ||
54 | } | ||
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs index d238741ba..6e23197a4 100644 --- a/crates/ra_hir/src/expr.rs +++ b/crates/ra_hir/src/expr.rs | |||
@@ -6,15 +6,17 @@ pub(crate) mod validation; | |||
6 | 6 | ||
7 | use std::{ops::Index, sync::Arc}; | 7 | use std::{ops::Index, sync::Arc}; |
8 | 8 | ||
9 | use hir_def::{ | ||
10 | path::GenericArgs, | ||
11 | type_ref::{Mutability, TypeRef}, | ||
12 | }; | ||
9 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; | 13 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; |
10 | use ra_syntax::{ast, AstPtr}; | 14 | use ra_syntax::{ast, AstPtr}; |
11 | use rustc_hash::FxHashMap; | 15 | use rustc_hash::FxHashMap; |
12 | 16 | ||
13 | use crate::{ | 17 | use crate::{ |
14 | db::HirDatabase, | 18 | db::HirDatabase, |
15 | path::GenericArgs, | ||
16 | ty::primitive::{UncertainFloatTy, UncertainIntTy}, | 19 | ty::primitive::{UncertainFloatTy, UncertainIntTy}, |
17 | type_ref::{Mutability, TypeRef}, | ||
18 | DefWithBody, Either, HasSource, Name, Path, Resolver, Source, | 20 | DefWithBody, Either, HasSource, Name, Path, Resolver, Source, |
19 | }; | 21 | }; |
20 | 22 | ||
diff --git a/crates/ra_hir/src/expr/lower.rs b/crates/ra_hir/src/expr/lower.rs index b3a9a2e6b..ad029b868 100644 --- a/crates/ra_hir/src/expr/lower.rs +++ b/crates/ra_hir/src/expr/lower.rs | |||
@@ -1,5 +1,10 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use hir_def::{ | ||
4 | name::{self, AsName, Name}, | ||
5 | path::GenericArgs, | ||
6 | type_ref::TypeRef, | ||
7 | }; | ||
3 | use ra_arena::Arena; | 8 | use ra_arena::Arena; |
4 | use ra_syntax::{ | 9 | use ra_syntax::{ |
5 | ast::{ | 10 | ast::{ |
@@ -12,10 +17,7 @@ use test_utils::tested_by; | |||
12 | 17 | ||
13 | use crate::{ | 18 | use crate::{ |
14 | db::HirDatabase, | 19 | db::HirDatabase, |
15 | name::{AsName, Name, SELF_PARAM}, | ||
16 | path::GenericArgs, | ||
17 | ty::primitive::{FloatTy, IntTy, UncertainFloatTy, UncertainIntTy}, | 20 | ty::primitive::{FloatTy, IntTy, UncertainFloatTy, UncertainIntTy}, |
18 | type_ref::TypeRef, | ||
19 | AstId, DefWithBody, Either, HirFileId, MacroCallLoc, MacroFileKind, Mutability, Path, Resolver, | 21 | AstId, DefWithBody, Either, HirFileId, MacroCallLoc, MacroFileKind, Mutability, Path, Resolver, |
20 | Source, | 22 | Source, |
21 | }; | 23 | }; |
@@ -78,7 +80,7 @@ where | |||
78 | let ptr = AstPtr::new(&self_param); | 80 | let ptr = AstPtr::new(&self_param); |
79 | let param_pat = self.alloc_pat( | 81 | let param_pat = self.alloc_pat( |
80 | Pat::Bind { | 82 | Pat::Bind { |
81 | name: SELF_PARAM, | 83 | name: name::SELF_PARAM, |
82 | mode: BindingAnnotation::Unannotated, | 84 | mode: BindingAnnotation::Unannotated, |
83 | subpat: None, | 85 | subpat: None, |
84 | }, | 86 | }, |
diff --git a/crates/ra_hir/src/expr/validation.rs b/crates/ra_hir/src/expr/validation.rs index 1aa853c3e..c685edda1 100644 --- a/crates/ra_hir/src/expr/validation.rs +++ b/crates/ra_hir/src/expr/validation.rs | |||
@@ -2,6 +2,7 @@ | |||
2 | 2 | ||
3 | use std::sync::Arc; | 3 | use std::sync::Arc; |
4 | 4 | ||
5 | use hir_def::path::known; | ||
5 | use ra_syntax::ast; | 6 | use ra_syntax::ast; |
6 | use rustc_hash::FxHashSet; | 7 | use rustc_hash::FxHashSet; |
7 | 8 | ||
@@ -9,7 +10,6 @@ use crate::{ | |||
9 | db::HirDatabase, | 10 | db::HirDatabase, |
10 | diagnostics::{DiagnosticSink, MissingFields, MissingOkInTailExpr}, | 11 | diagnostics::{DiagnosticSink, MissingFields, MissingOkInTailExpr}, |
11 | expr::AstPtr, | 12 | expr::AstPtr, |
12 | path::known, | ||
13 | ty::{ApplicationTy, InferenceResult, Ty, TypeCtor}, | 13 | ty::{ApplicationTy, InferenceResult, Ty, TypeCtor}, |
14 | Adt, Function, Name, Path, | 14 | Adt, Function, Name, Path, |
15 | }; | 15 | }; |
diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index 93713bb14..b9fbaa367 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs | |||
@@ -1,16 +1,11 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use ra_db::{FileId, FilePosition}; | 3 | use hir_def::name::AsName; |
4 | use ra_syntax::{ | 4 | use ra_syntax::ast::{self, AstNode, NameOwner}; |
5 | algo::find_node_at_offset, | ||
6 | ast::{self, AstNode, NameOwner}, | ||
7 | SyntaxNode, | ||
8 | }; | ||
9 | 5 | ||
10 | use crate::{ | 6 | use crate::{ |
11 | db::{AstDatabase, DefDatabase, HirDatabase}, | 7 | db::{AstDatabase, DefDatabase, HirDatabase}, |
12 | ids::{AstItemDef, LocationCtx}, | 8 | ids::{AstItemDef, LocationCtx}, |
13 | name::AsName, | ||
14 | AstId, Const, Crate, Enum, EnumVariant, FieldSource, Function, HasSource, ImplBlock, Module, | 9 | AstId, Const, Crate, Enum, EnumVariant, FieldSource, Function, HasSource, ImplBlock, Module, |
15 | ModuleSource, Source, Static, Struct, StructField, Trait, TypeAlias, Union, VariantDef, | 10 | ModuleSource, Source, Static, Struct, StructField, Trait, TypeAlias, Union, VariantDef, |
16 | }; | 11 | }; |
@@ -129,41 +124,6 @@ impl FromSource for StructField { | |||
129 | } | 124 | } |
130 | } | 125 | } |
131 | 126 | ||
132 | // FIXME: simplify it | ||
133 | impl ModuleSource { | ||
134 | pub fn from_position( | ||
135 | db: &(impl DefDatabase + AstDatabase), | ||
136 | position: FilePosition, | ||
137 | ) -> ModuleSource { | ||
138 | let parse = db.parse(position.file_id); | ||
139 | match &find_node_at_offset::<ast::Module>(parse.tree().syntax(), position.offset) { | ||
140 | Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()), | ||
141 | _ => { | ||
142 | let source_file = parse.tree(); | ||
143 | ModuleSource::SourceFile(source_file) | ||
144 | } | ||
145 | } | ||
146 | } | ||
147 | |||
148 | pub fn from_child_node( | ||
149 | db: &(impl DefDatabase + AstDatabase), | ||
150 | file_id: FileId, | ||
151 | child: &SyntaxNode, | ||
152 | ) -> ModuleSource { | ||
153 | if let Some(m) = child.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi()) { | ||
154 | ModuleSource::Module(m) | ||
155 | } else { | ||
156 | let source_file = db.parse(file_id).tree(); | ||
157 | ModuleSource::SourceFile(source_file) | ||
158 | } | ||
159 | } | ||
160 | |||
161 | pub fn from_file_id(db: &(impl DefDatabase + AstDatabase), file_id: FileId) -> ModuleSource { | ||
162 | let source_file = db.parse(file_id).tree(); | ||
163 | ModuleSource::SourceFile(source_file) | ||
164 | } | ||
165 | } | ||
166 | |||
167 | impl Module { | 127 | impl Module { |
168 | pub fn from_declaration(db: &impl HirDatabase, src: Source<ast::Module>) -> Option<Self> { | 128 | pub fn from_declaration(db: &impl HirDatabase, src: Source<ast::Module>) -> Option<Self> { |
169 | let src_parent = Source { | 129 | let src_parent = Source { |
diff --git a/crates/ra_hir/src/generics.rs b/crates/ra_hir/src/generics.rs index 4ce7551c3..9d5d18564 100644 --- a/crates/ra_hir/src/generics.rs +++ b/crates/ra_hir/src/generics.rs | |||
@@ -5,15 +5,17 @@ | |||
5 | 5 | ||
6 | use std::sync::Arc; | 6 | use std::sync::Arc; |
7 | 7 | ||
8 | use hir_def::{ | ||
9 | name::{self, AsName}, | ||
10 | path::Path, | ||
11 | type_ref::{TypeBound, TypeRef}, | ||
12 | }; | ||
8 | use ra_syntax::ast::{self, DefaultTypeParamOwner, NameOwner, TypeBoundsOwner, TypeParamsOwner}; | 13 | use ra_syntax::ast::{self, DefaultTypeParamOwner, NameOwner, TypeBoundsOwner, TypeParamsOwner}; |
9 | 14 | ||
10 | use crate::{ | 15 | use crate::{ |
11 | db::{AstDatabase, DefDatabase, HirDatabase}, | 16 | db::{AstDatabase, DefDatabase, HirDatabase}, |
12 | name::SELF_TYPE, | 17 | Adt, Const, Container, Enum, EnumVariant, Function, HasSource, ImplBlock, Name, Struct, Trait, |
13 | path::Path, | 18 | TypeAlias, Union, |
14 | type_ref::{TypeBound, TypeRef}, | ||
15 | Adt, AsName, Const, Container, Enum, EnumVariant, Function, HasSource, ImplBlock, Name, Struct, | ||
16 | Trait, TypeAlias, Union, | ||
17 | }; | 19 | }; |
18 | 20 | ||
19 | /// Data about a generic parameter (to a function, struct, impl, ...). | 21 | /// Data about a generic parameter (to a function, struct, impl, ...). |
@@ -94,11 +96,15 @@ impl GenericParams { | |||
94 | GenericDef::Adt(Adt::Enum(it)) => generics.fill(&it.source(db).ast, start), | 96 | GenericDef::Adt(Adt::Enum(it)) => generics.fill(&it.source(db).ast, start), |
95 | GenericDef::Trait(it) => { | 97 | GenericDef::Trait(it) => { |
96 | // traits get the Self type as an implicit first type parameter | 98 | // traits get the Self type as an implicit first type parameter |
97 | generics.params.push(GenericParam { idx: start, name: SELF_TYPE, default: None }); | 99 | generics.params.push(GenericParam { |
100 | idx: start, | ||
101 | name: name::SELF_TYPE, | ||
102 | default: None, | ||
103 | }); | ||
98 | generics.fill(&it.source(db).ast, start + 1); | 104 | generics.fill(&it.source(db).ast, start + 1); |
99 | // add super traits as bounds on Self | 105 | // add super traits as bounds on Self |
100 | // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar | 106 | // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar |
101 | let self_param = TypeRef::Path(SELF_TYPE.into()); | 107 | let self_param = TypeRef::Path(name::SELF_TYPE.into()); |
102 | generics.fill_bounds(&it.source(db).ast, self_param); | 108 | generics.fill_bounds(&it.source(db).ast, self_param); |
103 | } | 109 | } |
104 | GenericDef::TypeAlias(it) => generics.fill(&it.source(db).ast, start), | 110 | GenericDef::TypeAlias(it) => generics.fill(&it.source(db).ast, start), |
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs index 06f21fc33..518330713 100644 --- a/crates/ra_hir/src/impl_block.rs +++ b/crates/ra_hir/src/impl_block.rs | |||
@@ -3,6 +3,7 @@ | |||
3 | use rustc_hash::FxHashMap; | 3 | use rustc_hash::FxHashMap; |
4 | use std::sync::Arc; | 4 | use std::sync::Arc; |
5 | 5 | ||
6 | use hir_def::{attr::Attr, type_ref::TypeRef}; | ||
6 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; | 7 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; |
7 | use ra_cfg::CfgOptions; | 8 | use ra_cfg::CfgOptions; |
8 | use ra_syntax::{ | 9 | use ra_syntax::{ |
@@ -11,7 +12,6 @@ use ra_syntax::{ | |||
11 | }; | 12 | }; |
12 | 13 | ||
13 | use crate::{ | 14 | use crate::{ |
14 | attr::Attr, | ||
15 | code_model::{Module, ModuleSource}, | 15 | code_model::{Module, ModuleSource}, |
16 | db::{AstDatabase, DefDatabase, HirDatabase}, | 16 | db::{AstDatabase, DefDatabase, HirDatabase}, |
17 | generics::HasGenericParams, | 17 | generics::HasGenericParams, |
@@ -19,7 +19,6 @@ use crate::{ | |||
19 | ids::MacroCallLoc, | 19 | ids::MacroCallLoc, |
20 | resolve::Resolver, | 20 | resolve::Resolver, |
21 | ty::Ty, | 21 | ty::Ty, |
22 | type_ref::TypeRef, | ||
23 | AssocItem, AstId, Const, Function, HasSource, HirFileId, MacroFileKind, Path, Source, TraitRef, | 22 | AssocItem, AstId, Const, Function, HasSource, HirFileId, MacroFileKind, Path, Source, TraitRef, |
24 | TypeAlias, | 23 | TypeAlias, |
25 | }; | 24 | }; |
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index 0f2d233bb..f765490b0 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs | |||
@@ -26,24 +26,19 @@ macro_rules! impl_froms { | |||
26 | } | 26 | } |
27 | } | 27 | } |
28 | 28 | ||
29 | mod either; | ||
30 | pub mod debug; | 29 | pub mod debug; |
31 | 30 | ||
32 | pub mod db; | 31 | pub mod db; |
33 | #[macro_use] | 32 | #[macro_use] |
34 | pub mod mock; | 33 | pub mod mock; |
35 | mod path; | ||
36 | pub mod source_binder; | 34 | pub mod source_binder; |
37 | 35 | ||
38 | mod ids; | 36 | mod ids; |
39 | mod name; | ||
40 | mod nameres; | 37 | mod nameres; |
41 | mod adt; | 38 | mod adt; |
42 | mod traits; | 39 | mod traits; |
43 | mod type_alias; | 40 | mod type_alias; |
44 | mod type_ref; | ||
45 | mod ty; | 41 | mod ty; |
46 | mod attr; | ||
47 | mod impl_block; | 42 | mod impl_block; |
48 | mod expr; | 43 | mod expr; |
49 | mod lang_item; | 44 | mod lang_item; |
@@ -59,30 +54,23 @@ pub mod from_source; | |||
59 | #[cfg(test)] | 54 | #[cfg(test)] |
60 | mod marks; | 55 | mod marks; |
61 | 56 | ||
62 | use hir_expand::{ | 57 | use hir_expand::AstId; |
63 | ast_id_map::{AstIdMap, FileAstId}, | ||
64 | AstId, | ||
65 | }; | ||
66 | 58 | ||
67 | use crate::{ids::MacroFileKind, name::AsName, resolve::Resolver}; | 59 | use crate::{ids::MacroFileKind, resolve::Resolver}; |
68 | 60 | ||
69 | pub use crate::{ | 61 | pub use crate::{ |
70 | adt::VariantDef, | 62 | adt::VariantDef, |
71 | either::Either, | ||
72 | expr::ExprScopes, | 63 | expr::ExprScopes, |
73 | from_source::FromSource, | 64 | from_source::FromSource, |
74 | generics::{GenericDef, GenericParam, GenericParams, HasGenericParams}, | 65 | generics::{GenericDef, GenericParam, GenericParams, HasGenericParams}, |
75 | ids::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile}, | 66 | ids::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile}, |
76 | impl_block::ImplBlock, | 67 | impl_block::ImplBlock, |
77 | name::Name, | ||
78 | nameres::{ImportId, Namespace, PerNs}, | 68 | nameres::{ImportId, Namespace, PerNs}, |
79 | path::{Path, PathKind}, | ||
80 | resolve::ScopeDef, | 69 | resolve::ScopeDef, |
81 | source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, | 70 | source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, |
82 | ty::{ | 71 | ty::{ |
83 | display::HirDisplay, ApplicationTy, CallableDef, Substs, TraitRef, Ty, TypeCtor, TypeWalk, | 72 | display::HirDisplay, ApplicationTy, CallableDef, Substs, TraitRef, Ty, TypeCtor, TypeWalk, |
84 | }, | 73 | }, |
85 | type_ref::Mutability, | ||
86 | }; | 74 | }; |
87 | 75 | ||
88 | pub use self::code_model::{ | 76 | pub use self::code_model::{ |
@@ -92,3 +80,10 @@ pub use self::code_model::{ | |||
92 | Enum, EnumVariant, FieldSource, FnData, Function, HasBody, MacroDef, Module, ModuleDef, | 80 | Enum, EnumVariant, FieldSource, FnData, Function, HasBody, MacroDef, Module, ModuleDef, |
93 | ModuleSource, Static, Struct, StructField, Trait, TypeAlias, Union, | 81 | ModuleSource, Static, Struct, StructField, Trait, TypeAlias, Union, |
94 | }; | 82 | }; |
83 | |||
84 | pub use hir_def::{ | ||
85 | either::Either, | ||
86 | name::Name, | ||
87 | path::{Path, PathKind}, | ||
88 | type_ref::Mutability, | ||
89 | }; | ||
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir/src/marks.rs index 79af24b20..b423489a1 100644 --- a/crates/ra_hir/src/marks.rs +++ b/crates/ra_hir/src/marks.rs | |||
@@ -2,6 +2,7 @@ | |||
2 | 2 | ||
3 | test_utils::marks!( | 3 | test_utils::marks!( |
4 | bogus_paths | 4 | bogus_paths |
5 | // FIXME: restore this mark once hir is split | ||
5 | name_res_works_for_broken_modules | 6 | name_res_works_for_broken_modules |
6 | can_import_enum_variant | 7 | can_import_enum_variant |
7 | type_var_cycles_resolve_completely | 8 | type_var_cycles_resolve_completely |
diff --git a/crates/ra_hir/src/mock.rs b/crates/ra_hir/src/mock.rs index 0b278deb3..35dfaf3ba 100644 --- a/crates/ra_hir/src/mock.rs +++ b/crates/ra_hir/src/mock.rs | |||
@@ -22,6 +22,7 @@ pub const WORKSPACE: SourceRootId = SourceRootId(0); | |||
22 | db::InternDatabaseStorage, | 22 | db::InternDatabaseStorage, |
23 | db::AstDatabaseStorage, | 23 | db::AstDatabaseStorage, |
24 | db::DefDatabaseStorage, | 24 | db::DefDatabaseStorage, |
25 | db::DefDatabase2Storage, | ||
25 | db::HirDatabaseStorage | 26 | db::HirDatabaseStorage |
26 | )] | 27 | )] |
27 | #[derive(Debug)] | 28 | #[derive(Debug)] |
diff --git a/crates/ra_hir/src/name.rs b/crates/ra_hir/src/name.rs deleted file mode 100644 index 1e0b8c350..000000000 --- a/crates/ra_hir/src/name.rs +++ /dev/null | |||
@@ -1,142 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | use ra_syntax::{ast, SmolStr}; | ||
6 | |||
7 | /// `Name` is a wrapper around string, which is used in hir for both references | ||
8 | /// and declarations. In theory, names should also carry hygiene info, but we are | ||
9 | /// not there yet! | ||
10 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] | ||
11 | pub struct Name(Repr); | ||
12 | |||
13 | #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] | ||
14 | enum Repr { | ||
15 | Text(SmolStr), | ||
16 | TupleField(usize), | ||
17 | } | ||
18 | |||
19 | impl fmt::Display for Name { | ||
20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
21 | match &self.0 { | ||
22 | Repr::Text(text) => fmt::Display::fmt(&text, f), | ||
23 | Repr::TupleField(idx) => fmt::Display::fmt(&idx, f), | ||
24 | } | ||
25 | } | ||
26 | } | ||
27 | |||
28 | impl Name { | ||
29 | /// Note: this is private to make creating name from random string hard. | ||
30 | /// Hopefully, this should allow us to integrate hygiene cleaner in the | ||
31 | /// future, and to switch to interned representation of names. | ||
32 | const fn new_text(text: SmolStr) -> Name { | ||
33 | Name(Repr::Text(text)) | ||
34 | } | ||
35 | |||
36 | pub(crate) fn new_tuple_field(idx: usize) -> Name { | ||
37 | Name(Repr::TupleField(idx)) | ||
38 | } | ||
39 | |||
40 | /// Shortcut to create inline plain text name | ||
41 | const fn new_inline_ascii(len: usize, text: &[u8]) -> Name { | ||
42 | Name::new_text(SmolStr::new_inline_from_ascii(len, text)) | ||
43 | } | ||
44 | |||
45 | /// Resolve a name from the text of token. | ||
46 | fn resolve(raw_text: &SmolStr) -> Name { | ||
47 | let raw_start = "r#"; | ||
48 | if raw_text.as_str().starts_with(raw_start) { | ||
49 | Name::new_text(SmolStr::new(&raw_text[raw_start.len()..])) | ||
50 | } else { | ||
51 | Name::new_text(raw_text.clone()) | ||
52 | } | ||
53 | } | ||
54 | |||
55 | pub(crate) fn missing() -> Name { | ||
56 | Name::new_text("[missing name]".into()) | ||
57 | } | ||
58 | |||
59 | pub(crate) fn as_tuple_index(&self) -> Option<usize> { | ||
60 | match self.0 { | ||
61 | Repr::TupleField(idx) => Some(idx), | ||
62 | _ => None, | ||
63 | } | ||
64 | } | ||
65 | } | ||
66 | |||
67 | pub(crate) trait AsName { | ||
68 | fn as_name(&self) -> Name; | ||
69 | } | ||
70 | |||
71 | impl AsName for ast::NameRef { | ||
72 | fn as_name(&self) -> Name { | ||
73 | match self.as_tuple_field() { | ||
74 | Some(idx) => Name::new_tuple_field(idx), | ||
75 | None => Name::resolve(self.text()), | ||
76 | } | ||
77 | } | ||
78 | } | ||
79 | |||
80 | impl AsName for ast::Name { | ||
81 | fn as_name(&self) -> Name { | ||
82 | Name::resolve(self.text()) | ||
83 | } | ||
84 | } | ||
85 | |||
86 | impl AsName for ast::FieldKind { | ||
87 | fn as_name(&self) -> Name { | ||
88 | match self { | ||
89 | ast::FieldKind::Name(nr) => nr.as_name(), | ||
90 | ast::FieldKind::Index(idx) => Name::new_tuple_field(idx.text().parse().unwrap()), | ||
91 | } | ||
92 | } | ||
93 | } | ||
94 | |||
95 | impl AsName for ra_db::Dependency { | ||
96 | fn as_name(&self) -> Name { | ||
97 | Name::new_text(self.name.clone()) | ||
98 | } | ||
99 | } | ||
100 | |||
101 | // Primitives | ||
102 | pub(crate) const ISIZE: Name = Name::new_inline_ascii(5, b"isize"); | ||
103 | pub(crate) const I8: Name = Name::new_inline_ascii(2, b"i8"); | ||
104 | pub(crate) const I16: Name = Name::new_inline_ascii(3, b"i16"); | ||
105 | pub(crate) const I32: Name = Name::new_inline_ascii(3, b"i32"); | ||
106 | pub(crate) const I64: Name = Name::new_inline_ascii(3, b"i64"); | ||
107 | pub(crate) const I128: Name = Name::new_inline_ascii(4, b"i128"); | ||
108 | pub(crate) const USIZE: Name = Name::new_inline_ascii(5, b"usize"); | ||
109 | pub(crate) const U8: Name = Name::new_inline_ascii(2, b"u8"); | ||
110 | pub(crate) const U16: Name = Name::new_inline_ascii(3, b"u16"); | ||
111 | pub(crate) const U32: Name = Name::new_inline_ascii(3, b"u32"); | ||
112 | pub(crate) const U64: Name = Name::new_inline_ascii(3, b"u64"); | ||
113 | pub(crate) const U128: Name = Name::new_inline_ascii(4, b"u128"); | ||
114 | pub(crate) const F32: Name = Name::new_inline_ascii(3, b"f32"); | ||
115 | pub(crate) const F64: Name = Name::new_inline_ascii(3, b"f64"); | ||
116 | pub(crate) const BOOL: Name = Name::new_inline_ascii(4, b"bool"); | ||
117 | pub(crate) const CHAR: Name = Name::new_inline_ascii(4, b"char"); | ||
118 | pub(crate) const STR: Name = Name::new_inline_ascii(3, b"str"); | ||
119 | |||
120 | // Special names | ||
121 | pub(crate) const SELF_PARAM: Name = Name::new_inline_ascii(4, b"self"); | ||
122 | pub(crate) const SELF_TYPE: Name = Name::new_inline_ascii(4, b"Self"); | ||
123 | pub(crate) const MACRO_RULES: Name = Name::new_inline_ascii(11, b"macro_rules"); | ||
124 | |||
125 | // Components of known path (value or mod name) | ||
126 | pub(crate) const STD: Name = Name::new_inline_ascii(3, b"std"); | ||
127 | pub(crate) const ITER: Name = Name::new_inline_ascii(4, b"iter"); | ||
128 | pub(crate) const OPS: Name = Name::new_inline_ascii(3, b"ops"); | ||
129 | pub(crate) const FUTURE: Name = Name::new_inline_ascii(6, b"future"); | ||
130 | pub(crate) const RESULT: Name = Name::new_inline_ascii(6, b"result"); | ||
131 | pub(crate) const BOXED: Name = Name::new_inline_ascii(5, b"boxed"); | ||
132 | |||
133 | // Components of known path (type name) | ||
134 | pub(crate) const INTO_ITERATOR_TYPE: Name = Name::new_inline_ascii(12, b"IntoIterator"); | ||
135 | pub(crate) const ITEM_TYPE: Name = Name::new_inline_ascii(4, b"Item"); | ||
136 | pub(crate) const TRY_TYPE: Name = Name::new_inline_ascii(3, b"Try"); | ||
137 | pub(crate) const OK_TYPE: Name = Name::new_inline_ascii(2, b"Ok"); | ||
138 | pub(crate) const FUTURE_TYPE: Name = Name::new_inline_ascii(6, b"Future"); | ||
139 | pub(crate) const RESULT_TYPE: Name = Name::new_inline_ascii(6, b"Result"); | ||
140 | pub(crate) const OUTPUT_TYPE: Name = Name::new_inline_ascii(6, b"Output"); | ||
141 | pub(crate) const TARGET_TYPE: Name = Name::new_inline_ascii(6, b"Target"); | ||
142 | pub(crate) const BOX_TYPE: Name = Name::new_inline_ascii(3, b"Box"); | ||
diff --git a/crates/ra_hir/src/nameres.rs b/crates/ra_hir/src/nameres.rs index b325979f5..39f585b44 100644 --- a/crates/ra_hir/src/nameres.rs +++ b/crates/ra_hir/src/nameres.rs | |||
@@ -48,7 +48,6 @@ | |||
48 | //! on the result | 48 | //! on the result |
49 | 49 | ||
50 | mod per_ns; | 50 | mod per_ns; |
51 | mod raw; | ||
52 | mod collector; | 51 | mod collector; |
53 | mod mod_resolution; | 52 | mod mod_resolution; |
54 | #[cfg(test)] | 53 | #[cfg(test)] |
@@ -74,12 +73,9 @@ use crate::{ | |||
74 | Trait, | 73 | Trait, |
75 | }; | 74 | }; |
76 | 75 | ||
77 | pub(crate) use self::raw::{ImportSourceMap, RawItems}; | 76 | pub use self::per_ns::{Namespace, PerNs}; |
78 | 77 | ||
79 | pub use self::{ | 78 | pub use hir_def::nameres::raw::ImportId; |
80 | per_ns::{Namespace, PerNs}, | ||
81 | raw::ImportId, | ||
82 | }; | ||
83 | 79 | ||
84 | /// Contains all top-level defs from a macro-expanded crate | 80 | /// Contains all top-level defs from a macro-expanded crate |
85 | #[derive(Debug, PartialEq, Eq)] | 81 | #[derive(Debug, PartialEq, Eq)] |
@@ -328,7 +324,8 @@ impl CrateDefMap { | |||
328 | ) -> ResolvePathResult { | 324 | ) -> ResolvePathResult { |
329 | let mut segments = path.segments.iter().enumerate(); | 325 | let mut segments = path.segments.iter().enumerate(); |
330 | let mut curr_per_ns: PerNs = match path.kind { | 326 | let mut curr_per_ns: PerNs = match path.kind { |
331 | PathKind::DollarCrate(krate) => { | 327 | PathKind::DollarCrate(crate_id) => { |
328 | let krate = Crate { crate_id }; | ||
332 | if krate == self.krate { | 329 | if krate == self.krate { |
333 | tested_by!(macro_dollar_crate_self); | 330 | tested_by!(macro_dollar_crate_self); |
334 | PerNs::types(Module::new(self.krate, self.root).into()) | 331 | PerNs::types(Module::new(self.krate, self.root).into()) |
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs index a94a0554c..2f342870b 100644 --- a/crates/ra_hir/src/nameres/collector.rs +++ b/crates/ra_hir/src/nameres/collector.rs | |||
@@ -1,5 +1,6 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use hir_def::{attr::Attr, name, nameres::raw}; | ||
3 | use ra_cfg::CfgOptions; | 4 | use ra_cfg::CfgOptions; |
4 | use ra_db::FileId; | 5 | use ra_db::FileId; |
5 | use ra_syntax::{ast, SmolStr}; | 6 | use ra_syntax::{ast, SmolStr}; |
@@ -7,12 +8,10 @@ use rustc_hash::FxHashMap; | |||
7 | use test_utils::tested_by; | 8 | use test_utils::tested_by; |
8 | 9 | ||
9 | use crate::{ | 10 | use crate::{ |
10 | attr::Attr, | ||
11 | db::DefDatabase, | 11 | db::DefDatabase, |
12 | ids::{AstItemDef, LocationCtx, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind}, | 12 | ids::{AstItemDef, LocationCtx, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind}, |
13 | name::MACRO_RULES, | ||
14 | nameres::{ | 13 | nameres::{ |
15 | diagnostics::DefDiagnostic, mod_resolution::ModDir, raw, Crate, CrateDefMap, CrateModuleId, | 14 | diagnostics::DefDiagnostic, mod_resolution::ModDir, Crate, CrateDefMap, CrateModuleId, |
16 | ModuleData, ModuleDef, PerNs, ReachedFixedPoint, Resolution, ResolveMode, | 15 | ModuleData, ModuleDef, PerNs, ReachedFixedPoint, Resolution, ResolveMode, |
17 | }, | 16 | }, |
18 | Adt, AstId, Const, Enum, Function, HirFileId, MacroDef, Module, Name, Path, PathKind, Static, | 17 | Adt, AstId, Const, Enum, Function, HirFileId, MacroDef, Module, Name, Path, PathKind, Static, |
@@ -725,7 +724,7 @@ where | |||
725 | } | 724 | } |
726 | 725 | ||
727 | fn is_macro_rules(path: &Path) -> bool { | 726 | fn is_macro_rules(path: &Path) -> bool { |
728 | path.as_ident() == Some(&MACRO_RULES) | 727 | path.as_ident() == Some(&name::MACRO_RULES) |
729 | } | 728 | } |
730 | 729 | ||
731 | #[cfg(test)] | 730 | #[cfg(test)] |
diff --git a/crates/ra_hir/src/nameres/raw.rs b/crates/ra_hir/src/nameres/raw.rs deleted file mode 100644 index 57f2929c3..000000000 --- a/crates/ra_hir/src/nameres/raw.rs +++ /dev/null | |||
@@ -1,403 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::{ops::Index, sync::Arc}; | ||
4 | |||
5 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; | ||
6 | use ra_syntax::{ | ||
7 | ast::{self, AttrsOwner, NameOwner}, | ||
8 | AstNode, AstPtr, SourceFile, | ||
9 | }; | ||
10 | use test_utils::tested_by; | ||
11 | |||
12 | use crate::{ | ||
13 | attr::Attr, | ||
14 | db::{AstDatabase, DefDatabase}, | ||
15 | AsName, AstIdMap, Either, FileAstId, HirFileId, ModuleSource, Name, Path, Source, | ||
16 | }; | ||
17 | |||
18 | /// `RawItems` is a set of top-level items in a file (except for impls). | ||
19 | /// | ||
20 | /// It is the input to name resolution algorithm. `RawItems` are not invalidated | ||
21 | /// on most edits. | ||
22 | #[derive(Debug, Default, PartialEq, Eq)] | ||
23 | pub struct RawItems { | ||
24 | modules: Arena<Module, ModuleData>, | ||
25 | imports: Arena<ImportId, ImportData>, | ||
26 | defs: Arena<Def, DefData>, | ||
27 | macros: Arena<Macro, MacroData>, | ||
28 | /// items for top-level module | ||
29 | items: Vec<RawItem>, | ||
30 | } | ||
31 | |||
32 | #[derive(Debug, Default, PartialEq, Eq)] | ||
33 | pub struct ImportSourceMap { | ||
34 | map: ArenaMap<ImportId, ImportSourcePtr>, | ||
35 | } | ||
36 | |||
37 | type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>; | ||
38 | type ImportSource = Either<ast::UseTree, ast::ExternCrateItem>; | ||
39 | |||
40 | impl ImportSourcePtr { | ||
41 | fn to_node(self, file: &SourceFile) -> ImportSource { | ||
42 | self.map(|ptr| ptr.to_node(file.syntax()), |ptr| ptr.to_node(file.syntax())) | ||
43 | } | ||
44 | } | ||
45 | |||
46 | impl ImportSourceMap { | ||
47 | fn insert(&mut self, import: ImportId, ptr: ImportSourcePtr) { | ||
48 | self.map.insert(import, ptr) | ||
49 | } | ||
50 | |||
51 | pub(crate) fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource { | ||
52 | let file = match source { | ||
53 | ModuleSource::SourceFile(file) => file.clone(), | ||
54 | ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(), | ||
55 | }; | ||
56 | |||
57 | self.map[import].to_node(&file) | ||
58 | } | ||
59 | } | ||
60 | |||
61 | impl RawItems { | ||
62 | pub(crate) fn raw_items_query( | ||
63 | db: &(impl DefDatabase + AstDatabase), | ||
64 | file_id: HirFileId, | ||
65 | ) -> Arc<RawItems> { | ||
66 | db.raw_items_with_source_map(file_id).0 | ||
67 | } | ||
68 | |||
69 | pub(crate) fn raw_items_with_source_map_query( | ||
70 | db: &(impl DefDatabase + AstDatabase), | ||
71 | file_id: HirFileId, | ||
72 | ) -> (Arc<RawItems>, Arc<ImportSourceMap>) { | ||
73 | let mut collector = RawItemsCollector { | ||
74 | raw_items: RawItems::default(), | ||
75 | source_ast_id_map: db.ast_id_map(file_id), | ||
76 | source_map: ImportSourceMap::default(), | ||
77 | file_id, | ||
78 | db, | ||
79 | }; | ||
80 | if let Some(node) = db.parse_or_expand(file_id) { | ||
81 | if let Some(source_file) = ast::SourceFile::cast(node.clone()) { | ||
82 | collector.process_module(None, source_file); | ||
83 | } else if let Some(item_list) = ast::MacroItems::cast(node) { | ||
84 | collector.process_module(None, item_list); | ||
85 | } | ||
86 | } | ||
87 | (Arc::new(collector.raw_items), Arc::new(collector.source_map)) | ||
88 | } | ||
89 | |||
90 | pub(super) fn items(&self) -> &[RawItem] { | ||
91 | &self.items | ||
92 | } | ||
93 | } | ||
94 | |||
95 | impl Index<Module> for RawItems { | ||
96 | type Output = ModuleData; | ||
97 | fn index(&self, idx: Module) -> &ModuleData { | ||
98 | &self.modules[idx] | ||
99 | } | ||
100 | } | ||
101 | |||
102 | impl Index<ImportId> for RawItems { | ||
103 | type Output = ImportData; | ||
104 | fn index(&self, idx: ImportId) -> &ImportData { | ||
105 | &self.imports[idx] | ||
106 | } | ||
107 | } | ||
108 | |||
109 | impl Index<Def> for RawItems { | ||
110 | type Output = DefData; | ||
111 | fn index(&self, idx: Def) -> &DefData { | ||
112 | &self.defs[idx] | ||
113 | } | ||
114 | } | ||
115 | |||
116 | impl Index<Macro> for RawItems { | ||
117 | type Output = MacroData; | ||
118 | fn index(&self, idx: Macro) -> &MacroData { | ||
119 | &self.macros[idx] | ||
120 | } | ||
121 | } | ||
122 | |||
123 | // Avoid heap allocation on items without attributes. | ||
124 | type Attrs = Option<Arc<[Attr]>>; | ||
125 | |||
126 | #[derive(Debug, PartialEq, Eq, Clone)] | ||
127 | pub(super) struct RawItem { | ||
128 | attrs: Attrs, | ||
129 | pub(super) kind: RawItemKind, | ||
130 | } | ||
131 | |||
132 | impl RawItem { | ||
133 | pub(super) fn attrs(&self) -> &[Attr] { | ||
134 | self.attrs.as_ref().map_or(&[], |it| &*it) | ||
135 | } | ||
136 | } | ||
137 | |||
138 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] | ||
139 | pub(super) enum RawItemKind { | ||
140 | Module(Module), | ||
141 | Import(ImportId), | ||
142 | Def(Def), | ||
143 | Macro(Macro), | ||
144 | } | ||
145 | |||
146 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
147 | pub(super) struct Module(RawId); | ||
148 | impl_arena_id!(Module); | ||
149 | |||
150 | #[derive(Debug, PartialEq, Eq)] | ||
151 | pub(super) enum ModuleData { | ||
152 | Declaration { name: Name, ast_id: FileAstId<ast::Module> }, | ||
153 | Definition { name: Name, ast_id: FileAstId<ast::Module>, items: Vec<RawItem> }, | ||
154 | } | ||
155 | |||
156 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
157 | pub struct ImportId(RawId); | ||
158 | impl_arena_id!(ImportId); | ||
159 | |||
160 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
161 | pub struct ImportData { | ||
162 | pub(super) path: Path, | ||
163 | pub(super) alias: Option<Name>, | ||
164 | pub(super) is_glob: bool, | ||
165 | pub(super) is_prelude: bool, | ||
166 | pub(super) is_extern_crate: bool, | ||
167 | pub(super) is_macro_use: bool, | ||
168 | } | ||
169 | |||
170 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
171 | pub(super) struct Def(RawId); | ||
172 | impl_arena_id!(Def); | ||
173 | |||
174 | #[derive(Debug, PartialEq, Eq)] | ||
175 | pub(super) struct DefData { | ||
176 | pub(super) name: Name, | ||
177 | pub(super) kind: DefKind, | ||
178 | } | ||
179 | |||
180 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] | ||
181 | pub(super) enum DefKind { | ||
182 | Function(FileAstId<ast::FnDef>), | ||
183 | Struct(FileAstId<ast::StructDef>), | ||
184 | Union(FileAstId<ast::StructDef>), | ||
185 | Enum(FileAstId<ast::EnumDef>), | ||
186 | Const(FileAstId<ast::ConstDef>), | ||
187 | Static(FileAstId<ast::StaticDef>), | ||
188 | Trait(FileAstId<ast::TraitDef>), | ||
189 | TypeAlias(FileAstId<ast::TypeAliasDef>), | ||
190 | } | ||
191 | |||
192 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
193 | pub(super) struct Macro(RawId); | ||
194 | impl_arena_id!(Macro); | ||
195 | |||
196 | #[derive(Debug, PartialEq, Eq)] | ||
197 | pub(super) struct MacroData { | ||
198 | pub(super) ast_id: FileAstId<ast::MacroCall>, | ||
199 | pub(super) path: Path, | ||
200 | pub(super) name: Option<Name>, | ||
201 | pub(super) export: bool, | ||
202 | } | ||
203 | |||
204 | struct RawItemsCollector<DB> { | ||
205 | raw_items: RawItems, | ||
206 | source_ast_id_map: Arc<AstIdMap>, | ||
207 | source_map: ImportSourceMap, | ||
208 | file_id: HirFileId, | ||
209 | db: DB, | ||
210 | } | ||
211 | |||
212 | impl<DB: AstDatabase> RawItemsCollector<&DB> { | ||
213 | fn process_module(&mut self, current_module: Option<Module>, body: impl ast::ModuleItemOwner) { | ||
214 | for item_or_macro in body.items_with_macros() { | ||
215 | match item_or_macro { | ||
216 | ast::ItemOrMacro::Macro(m) => self.add_macro(current_module, m), | ||
217 | ast::ItemOrMacro::Item(item) => self.add_item(current_module, item), | ||
218 | } | ||
219 | } | ||
220 | } | ||
221 | |||
222 | fn add_item(&mut self, current_module: Option<Module>, item: ast::ModuleItem) { | ||
223 | let attrs = self.parse_attrs(&item); | ||
224 | let (kind, name) = match item { | ||
225 | ast::ModuleItem::Module(module) => { | ||
226 | self.add_module(current_module, module); | ||
227 | return; | ||
228 | } | ||
229 | ast::ModuleItem::UseItem(use_item) => { | ||
230 | self.add_use_item(current_module, use_item); | ||
231 | return; | ||
232 | } | ||
233 | ast::ModuleItem::ExternCrateItem(extern_crate) => { | ||
234 | self.add_extern_crate_item(current_module, extern_crate); | ||
235 | return; | ||
236 | } | ||
237 | ast::ModuleItem::ImplBlock(_) => { | ||
238 | // impls don't participate in name resolution | ||
239 | return; | ||
240 | } | ||
241 | ast::ModuleItem::StructDef(it) => { | ||
242 | let id = self.source_ast_id_map.ast_id(&it); | ||
243 | let name = it.name(); | ||
244 | if it.is_union() { | ||
245 | (DefKind::Union(id), name) | ||
246 | } else { | ||
247 | (DefKind::Struct(id), name) | ||
248 | } | ||
249 | } | ||
250 | ast::ModuleItem::EnumDef(it) => { | ||
251 | (DefKind::Enum(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
252 | } | ||
253 | ast::ModuleItem::FnDef(it) => { | ||
254 | (DefKind::Function(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
255 | } | ||
256 | ast::ModuleItem::TraitDef(it) => { | ||
257 | (DefKind::Trait(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
258 | } | ||
259 | ast::ModuleItem::TypeAliasDef(it) => { | ||
260 | (DefKind::TypeAlias(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
261 | } | ||
262 | ast::ModuleItem::ConstDef(it) => { | ||
263 | (DefKind::Const(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
264 | } | ||
265 | ast::ModuleItem::StaticDef(it) => { | ||
266 | (DefKind::Static(self.source_ast_id_map.ast_id(&it)), it.name()) | ||
267 | } | ||
268 | }; | ||
269 | if let Some(name) = name { | ||
270 | let name = name.as_name(); | ||
271 | let def = self.raw_items.defs.alloc(DefData { name, kind }); | ||
272 | self.push_item(current_module, attrs, RawItemKind::Def(def)); | ||
273 | } | ||
274 | } | ||
275 | |||
276 | fn add_module(&mut self, current_module: Option<Module>, module: ast::Module) { | ||
277 | let name = match module.name() { | ||
278 | Some(it) => it.as_name(), | ||
279 | None => return, | ||
280 | }; | ||
281 | let attrs = self.parse_attrs(&module); | ||
282 | |||
283 | let ast_id = self.source_ast_id_map.ast_id(&module); | ||
284 | if module.has_semi() { | ||
285 | let item = self.raw_items.modules.alloc(ModuleData::Declaration { name, ast_id }); | ||
286 | self.push_item(current_module, attrs, RawItemKind::Module(item)); | ||
287 | return; | ||
288 | } | ||
289 | |||
290 | if let Some(item_list) = module.item_list() { | ||
291 | let item = self.raw_items.modules.alloc(ModuleData::Definition { | ||
292 | name, | ||
293 | ast_id, | ||
294 | items: Vec::new(), | ||
295 | }); | ||
296 | self.process_module(Some(item), item_list); | ||
297 | self.push_item(current_module, attrs, RawItemKind::Module(item)); | ||
298 | return; | ||
299 | } | ||
300 | tested_by!(name_res_works_for_broken_modules); | ||
301 | } | ||
302 | |||
303 | fn add_use_item(&mut self, current_module: Option<Module>, use_item: ast::UseItem) { | ||
304 | // FIXME: cfg_attr | ||
305 | let is_prelude = use_item.has_atom_attr("prelude_import"); | ||
306 | let attrs = self.parse_attrs(&use_item); | ||
307 | |||
308 | Path::expand_use_item( | ||
309 | Source { ast: use_item, file_id: self.file_id }, | ||
310 | self.db, | ||
311 | |path, use_tree, is_glob, alias| { | ||
312 | let import_data = ImportData { | ||
313 | path, | ||
314 | alias, | ||
315 | is_glob, | ||
316 | is_prelude, | ||
317 | is_extern_crate: false, | ||
318 | is_macro_use: false, | ||
319 | }; | ||
320 | self.push_import( | ||
321 | current_module, | ||
322 | attrs.clone(), | ||
323 | import_data, | ||
324 | Either::A(AstPtr::new(use_tree)), | ||
325 | ); | ||
326 | }, | ||
327 | ) | ||
328 | } | ||
329 | |||
330 | fn add_extern_crate_item( | ||
331 | &mut self, | ||
332 | current_module: Option<Module>, | ||
333 | extern_crate: ast::ExternCrateItem, | ||
334 | ) { | ||
335 | if let Some(name_ref) = extern_crate.name_ref() { | ||
336 | let path = Path::from_name_ref(&name_ref); | ||
337 | let alias = extern_crate.alias().and_then(|a| a.name()).map(|it| it.as_name()); | ||
338 | let attrs = self.parse_attrs(&extern_crate); | ||
339 | // FIXME: cfg_attr | ||
340 | let is_macro_use = extern_crate.has_atom_attr("macro_use"); | ||
341 | let import_data = ImportData { | ||
342 | path, | ||
343 | alias, | ||
344 | is_glob: false, | ||
345 | is_prelude: false, | ||
346 | is_extern_crate: true, | ||
347 | is_macro_use, | ||
348 | }; | ||
349 | self.push_import( | ||
350 | current_module, | ||
351 | attrs, | ||
352 | import_data, | ||
353 | Either::B(AstPtr::new(&extern_crate)), | ||
354 | ); | ||
355 | } | ||
356 | } | ||
357 | |||
358 | fn add_macro(&mut self, current_module: Option<Module>, m: ast::MacroCall) { | ||
359 | let attrs = self.parse_attrs(&m); | ||
360 | let path = match m | ||
361 | .path() | ||
362 | .and_then(|path| Path::from_src(Source { ast: path, file_id: self.file_id }, self.db)) | ||
363 | { | ||
364 | Some(it) => it, | ||
365 | _ => return, | ||
366 | }; | ||
367 | |||
368 | let name = m.name().map(|it| it.as_name()); | ||
369 | let ast_id = self.source_ast_id_map.ast_id(&m); | ||
370 | // FIXME: cfg_attr | ||
371 | let export = m.attrs().filter_map(|x| x.simple_name()).any(|name| name == "macro_export"); | ||
372 | |||
373 | let m = self.raw_items.macros.alloc(MacroData { ast_id, path, name, export }); | ||
374 | self.push_item(current_module, attrs, RawItemKind::Macro(m)); | ||
375 | } | ||
376 | |||
377 | fn push_import( | ||
378 | &mut self, | ||
379 | current_module: Option<Module>, | ||
380 | attrs: Attrs, | ||
381 | data: ImportData, | ||
382 | source: ImportSourcePtr, | ||
383 | ) { | ||
384 | let import = self.raw_items.imports.alloc(data); | ||
385 | self.source_map.insert(import, source); | ||
386 | self.push_item(current_module, attrs, RawItemKind::Import(import)) | ||
387 | } | ||
388 | |||
389 | fn push_item(&mut self, current_module: Option<Module>, attrs: Attrs, kind: RawItemKind) { | ||
390 | match current_module { | ||
391 | Some(module) => match &mut self.raw_items.modules[module] { | ||
392 | ModuleData::Definition { items, .. } => items, | ||
393 | ModuleData::Declaration { .. } => unreachable!(), | ||
394 | }, | ||
395 | None => &mut self.raw_items.items, | ||
396 | } | ||
397 | .push(RawItem { attrs, kind }) | ||
398 | } | ||
399 | |||
400 | fn parse_attrs(&self, item: &impl ast::AttrsOwner) -> Attrs { | ||
401 | Attr::from_attrs_owner(self.file_id, item, self.db) | ||
402 | } | ||
403 | } | ||
diff --git a/crates/ra_hir/src/nameres/tests/mod_resolution.rs b/crates/ra_hir/src/nameres/tests/mod_resolution.rs index f569aacdc..abfe8b1c3 100644 --- a/crates/ra_hir/src/nameres/tests/mod_resolution.rs +++ b/crates/ra_hir/src/nameres/tests/mod_resolution.rs | |||
@@ -2,7 +2,7 @@ use super::*; | |||
2 | 2 | ||
3 | #[test] | 3 | #[test] |
4 | fn name_res_works_for_broken_modules() { | 4 | fn name_res_works_for_broken_modules() { |
5 | covers!(name_res_works_for_broken_modules); | 5 | // covers!(name_res_works_for_broken_modules); |
6 | let map = def_map( | 6 | let map = def_map( |
7 | " | 7 | " |
8 | //- /lib.rs | 8 | //- /lib.rs |
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs deleted file mode 100644 index bbe536bcb..000000000 --- a/crates/ra_hir/src/path.rs +++ /dev/null | |||
@@ -1,422 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::{iter, sync::Arc}; | ||
4 | |||
5 | use ra_syntax::{ | ||
6 | ast::{self, NameOwner, TypeAscriptionOwner}, | ||
7 | AstNode, | ||
8 | }; | ||
9 | |||
10 | use crate::{db::AstDatabase, name, type_ref::TypeRef, AsName, Crate, Name, Source}; | ||
11 | |||
12 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
13 | pub struct Path { | ||
14 | pub kind: PathKind, | ||
15 | pub segments: Vec<PathSegment>, | ||
16 | } | ||
17 | |||
18 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
19 | pub struct PathSegment { | ||
20 | pub name: Name, | ||
21 | pub args_and_bindings: Option<Arc<GenericArgs>>, | ||
22 | } | ||
23 | |||
24 | /// Generic arguments to a path segment (e.g. the `i32` in `Option<i32>`). This | ||
25 | /// can (in the future) also include bindings of associated types, like in | ||
26 | /// `Iterator<Item = Foo>`. | ||
27 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
28 | pub struct GenericArgs { | ||
29 | pub args: Vec<GenericArg>, | ||
30 | /// This specifies whether the args contain a Self type as the first | ||
31 | /// element. This is the case for path segments like `<T as Trait>`, where | ||
32 | /// `T` is actually a type parameter for the path `Trait` specifying the | ||
33 | /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type | ||
34 | /// is left out. | ||
35 | pub has_self_type: bool, | ||
36 | /// Associated type bindings like in `Iterator<Item = T>`. | ||
37 | pub bindings: Vec<(Name, TypeRef)>, | ||
38 | } | ||
39 | |||
40 | /// A single generic argument. | ||
41 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
42 | pub enum GenericArg { | ||
43 | Type(TypeRef), | ||
44 | // or lifetime... | ||
45 | } | ||
46 | |||
47 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
48 | pub enum PathKind { | ||
49 | Plain, | ||
50 | Self_, | ||
51 | Super, | ||
52 | Crate, | ||
53 | // Absolute path | ||
54 | Abs, | ||
55 | // Type based path like `<T>::foo` | ||
56 | Type(Box<TypeRef>), | ||
57 | // `$crate` from macro expansion | ||
58 | DollarCrate(Crate), | ||
59 | } | ||
60 | |||
61 | impl Path { | ||
62 | /// Calls `cb` with all paths, represented by this use item. | ||
63 | pub fn expand_use_item( | ||
64 | item_src: Source<ast::UseItem>, | ||
65 | db: &impl AstDatabase, | ||
66 | mut cb: impl FnMut(Path, &ast::UseTree, bool, Option<Name>), | ||
67 | ) { | ||
68 | if let Some(tree) = item_src.ast.use_tree() { | ||
69 | expand_use_tree( | ||
70 | None, | ||
71 | tree, | ||
72 | &|| item_src.file_id.macro_crate(db).map(|crate_id| Crate { crate_id }), | ||
73 | &mut cb, | ||
74 | ); | ||
75 | } | ||
76 | } | ||
77 | |||
78 | pub fn from_simple_segments(kind: PathKind, segments: impl IntoIterator<Item = Name>) -> Path { | ||
79 | Path { | ||
80 | kind, | ||
81 | segments: segments | ||
82 | .into_iter() | ||
83 | .map(|name| PathSegment { name, args_and_bindings: None }) | ||
84 | .collect(), | ||
85 | } | ||
86 | } | ||
87 | |||
88 | /// Converts an `ast::Path` to `Path`. Works with use trees. | ||
89 | /// DEPRECATED: It does not handle `$crate` from macro call. | ||
90 | pub fn from_ast(path: ast::Path) -> Option<Path> { | ||
91 | Path::parse(path, &|| None) | ||
92 | } | ||
93 | |||
94 | /// Converts an `ast::Path` to `Path`. Works with use trees. | ||
95 | /// It correctly handles `$crate` based path from macro call. | ||
96 | pub fn from_src(source: Source<ast::Path>, db: &impl AstDatabase) -> Option<Path> { | ||
97 | let file_id = source.file_id; | ||
98 | Path::parse(source.ast, &|| file_id.macro_crate(db).map(|crate_id| Crate { crate_id })) | ||
99 | } | ||
100 | |||
101 | fn parse(mut path: ast::Path, macro_crate: &impl Fn() -> Option<Crate>) -> Option<Path> { | ||
102 | let mut kind = PathKind::Plain; | ||
103 | let mut segments = Vec::new(); | ||
104 | loop { | ||
105 | let segment = path.segment()?; | ||
106 | |||
107 | if segment.has_colon_colon() { | ||
108 | kind = PathKind::Abs; | ||
109 | } | ||
110 | |||
111 | match segment.kind()? { | ||
112 | ast::PathSegmentKind::Name(name) => { | ||
113 | if name.text() == "$crate" { | ||
114 | if let Some(macro_crate) = macro_crate() { | ||
115 | kind = PathKind::DollarCrate(macro_crate); | ||
116 | break; | ||
117 | } | ||
118 | } | ||
119 | |||
120 | let args = segment | ||
121 | .type_arg_list() | ||
122 | .and_then(GenericArgs::from_ast) | ||
123 | .or_else(|| { | ||
124 | GenericArgs::from_fn_like_path_ast( | ||
125 | segment.param_list(), | ||
126 | segment.ret_type(), | ||
127 | ) | ||
128 | }) | ||
129 | .map(Arc::new); | ||
130 | let segment = PathSegment { name: name.as_name(), args_and_bindings: args }; | ||
131 | segments.push(segment); | ||
132 | } | ||
133 | ast::PathSegmentKind::Type { type_ref, trait_ref } => { | ||
134 | assert!(path.qualifier().is_none()); // this can only occur at the first segment | ||
135 | |||
136 | let self_type = TypeRef::from_ast(type_ref?); | ||
137 | |||
138 | match trait_ref { | ||
139 | // <T>::foo | ||
140 | None => { | ||
141 | kind = PathKind::Type(Box::new(self_type)); | ||
142 | } | ||
143 | // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo | ||
144 | Some(trait_ref) => { | ||
145 | let path = Path::parse(trait_ref.path()?, macro_crate)?; | ||
146 | kind = path.kind; | ||
147 | let mut prefix_segments = path.segments; | ||
148 | prefix_segments.reverse(); | ||
149 | segments.extend(prefix_segments); | ||
150 | // Insert the type reference (T in the above example) as Self parameter for the trait | ||
151 | let mut last_segment = segments.last_mut()?; | ||
152 | if last_segment.args_and_bindings.is_none() { | ||
153 | last_segment.args_and_bindings = | ||
154 | Some(Arc::new(GenericArgs::empty())); | ||
155 | }; | ||
156 | let args = last_segment.args_and_bindings.as_mut().unwrap(); | ||
157 | let mut args_inner = Arc::make_mut(args); | ||
158 | args_inner.has_self_type = true; | ||
159 | args_inner.args.insert(0, GenericArg::Type(self_type)); | ||
160 | } | ||
161 | } | ||
162 | } | ||
163 | ast::PathSegmentKind::CrateKw => { | ||
164 | kind = PathKind::Crate; | ||
165 | break; | ||
166 | } | ||
167 | ast::PathSegmentKind::SelfKw => { | ||
168 | kind = PathKind::Self_; | ||
169 | break; | ||
170 | } | ||
171 | ast::PathSegmentKind::SuperKw => { | ||
172 | kind = PathKind::Super; | ||
173 | break; | ||
174 | } | ||
175 | } | ||
176 | path = match qualifier(&path) { | ||
177 | Some(it) => it, | ||
178 | None => break, | ||
179 | }; | ||
180 | } | ||
181 | segments.reverse(); | ||
182 | return Some(Path { kind, segments }); | ||
183 | |||
184 | fn qualifier(path: &ast::Path) -> Option<ast::Path> { | ||
185 | if let Some(q) = path.qualifier() { | ||
186 | return Some(q); | ||
187 | } | ||
188 | // FIXME: this bottom up traversal is not too precise. | ||
189 | // Should we handle do a top-down analysis, recording results? | ||
190 | let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?; | ||
191 | let use_tree = use_tree_list.parent_use_tree(); | ||
192 | use_tree.path() | ||
193 | } | ||
194 | } | ||
195 | |||
196 | /// Converts an `ast::NameRef` into a single-identifier `Path`. | ||
197 | pub fn from_name_ref(name_ref: &ast::NameRef) -> Path { | ||
198 | name_ref.as_name().into() | ||
199 | } | ||
200 | |||
201 | /// `true` is this path is a single identifier, like `foo` | ||
202 | pub fn is_ident(&self) -> bool { | ||
203 | self.kind == PathKind::Plain && self.segments.len() == 1 | ||
204 | } | ||
205 | |||
206 | /// `true` if this path is just a standalone `self` | ||
207 | pub fn is_self(&self) -> bool { | ||
208 | self.kind == PathKind::Self_ && self.segments.is_empty() | ||
209 | } | ||
210 | |||
211 | /// If this path is a single identifier, like `foo`, return its name. | ||
212 | pub fn as_ident(&self) -> Option<&Name> { | ||
213 | if self.kind != PathKind::Plain || self.segments.len() > 1 { | ||
214 | return None; | ||
215 | } | ||
216 | self.segments.first().map(|s| &s.name) | ||
217 | } | ||
218 | |||
219 | pub fn expand_macro_expr(&self) -> Option<Name> { | ||
220 | self.as_ident().and_then(|name| Some(name.clone())) | ||
221 | } | ||
222 | |||
223 | pub fn is_type_relative(&self) -> bool { | ||
224 | match self.kind { | ||
225 | PathKind::Type(_) => true, | ||
226 | _ => false, | ||
227 | } | ||
228 | } | ||
229 | } | ||
230 | |||
231 | impl GenericArgs { | ||
232 | pub(crate) fn from_ast(node: ast::TypeArgList) -> Option<GenericArgs> { | ||
233 | let mut args = Vec::new(); | ||
234 | for type_arg in node.type_args() { | ||
235 | let type_ref = TypeRef::from_ast_opt(type_arg.type_ref()); | ||
236 | args.push(GenericArg::Type(type_ref)); | ||
237 | } | ||
238 | // lifetimes ignored for now | ||
239 | let mut bindings = Vec::new(); | ||
240 | for assoc_type_arg in node.assoc_type_args() { | ||
241 | if let Some(name_ref) = assoc_type_arg.name_ref() { | ||
242 | let name = name_ref.as_name(); | ||
243 | let type_ref = TypeRef::from_ast_opt(assoc_type_arg.type_ref()); | ||
244 | bindings.push((name, type_ref)); | ||
245 | } | ||
246 | } | ||
247 | if args.is_empty() && bindings.is_empty() { | ||
248 | None | ||
249 | } else { | ||
250 | Some(GenericArgs { args, has_self_type: false, bindings }) | ||
251 | } | ||
252 | } | ||
253 | |||
254 | /// Collect `GenericArgs` from the parts of a fn-like path, i.e. `Fn(X, Y) | ||
255 | /// -> Z` (which desugars to `Fn<(X, Y), Output=Z>`). | ||
256 | pub(crate) fn from_fn_like_path_ast( | ||
257 | params: Option<ast::ParamList>, | ||
258 | ret_type: Option<ast::RetType>, | ||
259 | ) -> Option<GenericArgs> { | ||
260 | let mut args = Vec::new(); | ||
261 | let mut bindings = Vec::new(); | ||
262 | if let Some(params) = params { | ||
263 | let mut param_types = Vec::new(); | ||
264 | for param in params.params() { | ||
265 | let type_ref = TypeRef::from_ast_opt(param.ascribed_type()); | ||
266 | param_types.push(type_ref); | ||
267 | } | ||
268 | let arg = GenericArg::Type(TypeRef::Tuple(param_types)); | ||
269 | args.push(arg); | ||
270 | } | ||
271 | if let Some(ret_type) = ret_type { | ||
272 | let type_ref = TypeRef::from_ast_opt(ret_type.type_ref()); | ||
273 | bindings.push((name::OUTPUT_TYPE, type_ref)) | ||
274 | } | ||
275 | if args.is_empty() && bindings.is_empty() { | ||
276 | None | ||
277 | } else { | ||
278 | Some(GenericArgs { args, has_self_type: false, bindings }) | ||
279 | } | ||
280 | } | ||
281 | |||
282 | pub(crate) fn empty() -> GenericArgs { | ||
283 | GenericArgs { args: Vec::new(), has_self_type: false, bindings: Vec::new() } | ||
284 | } | ||
285 | } | ||
286 | |||
287 | impl From<Name> for Path { | ||
288 | fn from(name: Name) -> Path { | ||
289 | Path::from_simple_segments(PathKind::Plain, iter::once(name)) | ||
290 | } | ||
291 | } | ||
292 | |||
293 | fn expand_use_tree( | ||
294 | prefix: Option<Path>, | ||
295 | tree: ast::UseTree, | ||
296 | macro_crate: &impl Fn() -> Option<Crate>, | ||
297 | cb: &mut impl FnMut(Path, &ast::UseTree, bool, Option<Name>), | ||
298 | ) { | ||
299 | if let Some(use_tree_list) = tree.use_tree_list() { | ||
300 | let prefix = match tree.path() { | ||
301 | // E.g. use something::{{{inner}}}; | ||
302 | None => prefix, | ||
303 | // E.g. `use something::{inner}` (prefix is `None`, path is `something`) | ||
304 | // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`) | ||
305 | Some(path) => match convert_path(prefix, path, macro_crate) { | ||
306 | Some(it) => Some(it), | ||
307 | None => return, // FIXME: report errors somewhere | ||
308 | }, | ||
309 | }; | ||
310 | for child_tree in use_tree_list.use_trees() { | ||
311 | expand_use_tree(prefix.clone(), child_tree, macro_crate, cb); | ||
312 | } | ||
313 | } else { | ||
314 | let alias = tree.alias().and_then(|a| a.name()).map(|a| a.as_name()); | ||
315 | if let Some(ast_path) = tree.path() { | ||
316 | // Handle self in a path. | ||
317 | // E.g. `use something::{self, <...>}` | ||
318 | if ast_path.qualifier().is_none() { | ||
319 | if let Some(segment) = ast_path.segment() { | ||
320 | if segment.kind() == Some(ast::PathSegmentKind::SelfKw) { | ||
321 | if let Some(prefix) = prefix { | ||
322 | cb(prefix, &tree, false, alias); | ||
323 | return; | ||
324 | } | ||
325 | } | ||
326 | } | ||
327 | } | ||
328 | if let Some(path) = convert_path(prefix, ast_path, macro_crate) { | ||
329 | let is_glob = tree.has_star(); | ||
330 | cb(path, &tree, is_glob, alias) | ||
331 | } | ||
332 | // FIXME: report errors somewhere | ||
333 | // We get here if we do | ||
334 | } | ||
335 | } | ||
336 | } | ||
337 | |||
338 | fn convert_path( | ||
339 | prefix: Option<Path>, | ||
340 | path: ast::Path, | ||
341 | macro_crate: &impl Fn() -> Option<Crate>, | ||
342 | ) -> Option<Path> { | ||
343 | let prefix = if let Some(qual) = path.qualifier() { | ||
344 | Some(convert_path(prefix, qual, macro_crate)?) | ||
345 | } else { | ||
346 | prefix | ||
347 | }; | ||
348 | |||
349 | let segment = path.segment()?; | ||
350 | let res = match segment.kind()? { | ||
351 | ast::PathSegmentKind::Name(name) => { | ||
352 | if name.text() == "$crate" { | ||
353 | if let Some(krate) = macro_crate() { | ||
354 | return Some(Path::from_simple_segments( | ||
355 | PathKind::DollarCrate(krate), | ||
356 | iter::empty(), | ||
357 | )); | ||
358 | } | ||
359 | } | ||
360 | |||
361 | // no type args in use | ||
362 | let mut res = prefix | ||
363 | .unwrap_or_else(|| Path { kind: PathKind::Plain, segments: Vec::with_capacity(1) }); | ||
364 | res.segments.push(PathSegment { | ||
365 | name: name.as_name(), | ||
366 | args_and_bindings: None, // no type args in use | ||
367 | }); | ||
368 | res | ||
369 | } | ||
370 | ast::PathSegmentKind::CrateKw => { | ||
371 | if prefix.is_some() { | ||
372 | return None; | ||
373 | } | ||
374 | Path::from_simple_segments(PathKind::Crate, iter::empty()) | ||
375 | } | ||
376 | ast::PathSegmentKind::SelfKw => { | ||
377 | if prefix.is_some() { | ||
378 | return None; | ||
379 | } | ||
380 | Path::from_simple_segments(PathKind::Self_, iter::empty()) | ||
381 | } | ||
382 | ast::PathSegmentKind::SuperKw => { | ||
383 | if prefix.is_some() { | ||
384 | return None; | ||
385 | } | ||
386 | Path::from_simple_segments(PathKind::Super, iter::empty()) | ||
387 | } | ||
388 | ast::PathSegmentKind::Type { .. } => { | ||
389 | // not allowed in imports | ||
390 | return None; | ||
391 | } | ||
392 | }; | ||
393 | Some(res) | ||
394 | } | ||
395 | |||
396 | pub mod known { | ||
397 | use super::{Path, PathKind}; | ||
398 | use crate::name; | ||
399 | |||
400 | pub fn std_iter_into_iterator() -> Path { | ||
401 | Path::from_simple_segments( | ||
402 | PathKind::Abs, | ||
403 | vec![name::STD, name::ITER, name::INTO_ITERATOR_TYPE], | ||
404 | ) | ||
405 | } | ||
406 | |||
407 | pub fn std_ops_try() -> Path { | ||
408 | Path::from_simple_segments(PathKind::Abs, vec![name::STD, name::OPS, name::TRY_TYPE]) | ||
409 | } | ||
410 | |||
411 | pub fn std_result_result() -> Path { | ||
412 | Path::from_simple_segments(PathKind::Abs, vec![name::STD, name::RESULT, name::RESULT_TYPE]) | ||
413 | } | ||
414 | |||
415 | pub fn std_future_future() -> Path { | ||
416 | Path::from_simple_segments(PathKind::Abs, vec![name::STD, name::FUTURE, name::FUTURE_TYPE]) | ||
417 | } | ||
418 | |||
419 | pub fn std_boxed_box() -> Path { | ||
420 | Path::from_simple_segments(PathKind::Abs, vec![name::STD, name::BOXED, name::BOX_TYPE]) | ||
421 | } | ||
422 | } | ||
diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs index 8b6269407..2a783b61e 100644 --- a/crates/ra_hir/src/resolve.rs +++ b/crates/ra_hir/src/resolve.rs | |||
@@ -1,7 +1,11 @@ | |||
1 | //! Name resolution. | 1 | //! Name resolution. |
2 | use std::sync::Arc; | 2 | use std::sync::Arc; |
3 | 3 | ||
4 | use hir_def::CrateModuleId; | 4 | use hir_def::{ |
5 | name::{self, Name}, | ||
6 | path::{Path, PathKind}, | ||
7 | CrateModuleId, | ||
8 | }; | ||
5 | use rustc_hash::FxHashSet; | 9 | use rustc_hash::FxHashSet; |
6 | 10 | ||
7 | use crate::{ | 11 | use crate::{ |
@@ -13,9 +17,7 @@ use crate::{ | |||
13 | }, | 17 | }, |
14 | generics::GenericParams, | 18 | generics::GenericParams, |
15 | impl_block::ImplBlock, | 19 | impl_block::ImplBlock, |
16 | name::{Name, SELF_PARAM, SELF_TYPE}, | ||
17 | nameres::{CrateDefMap, PerNs}, | 20 | nameres::{CrateDefMap, PerNs}, |
18 | path::{Path, PathKind}, | ||
19 | Adt, BuiltinType, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct, | 21 | Adt, BuiltinType, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct, |
20 | Trait, TypeAlias, | 22 | Trait, TypeAlias, |
21 | }; | 23 | }; |
@@ -150,13 +152,13 @@ impl Resolver { | |||
150 | } | 152 | } |
151 | } | 153 | } |
152 | Scope::ImplBlockScope(impl_) => { | 154 | Scope::ImplBlockScope(impl_) => { |
153 | if first_name == &SELF_TYPE { | 155 | if first_name == &name::SELF_TYPE { |
154 | let idx = if path.segments.len() == 1 { None } else { Some(1) }; | 156 | let idx = if path.segments.len() == 1 { None } else { Some(1) }; |
155 | return Some((TypeNs::SelfType(*impl_), idx)); | 157 | return Some((TypeNs::SelfType(*impl_), idx)); |
156 | } | 158 | } |
157 | } | 159 | } |
158 | Scope::AdtScope(adt) => { | 160 | Scope::AdtScope(adt) => { |
159 | if first_name == &SELF_TYPE { | 161 | if first_name == &name::SELF_TYPE { |
160 | let idx = if path.segments.len() == 1 { None } else { Some(1) }; | 162 | let idx = if path.segments.len() == 1 { None } else { Some(1) }; |
161 | return Some((TypeNs::AdtSelfType(*adt), idx)); | 163 | return Some((TypeNs::AdtSelfType(*adt), idx)); |
162 | } | 164 | } |
@@ -205,7 +207,7 @@ impl Resolver { | |||
205 | return None; | 207 | return None; |
206 | } | 208 | } |
207 | let n_segments = path.segments.len(); | 209 | let n_segments = path.segments.len(); |
208 | let tmp = SELF_PARAM; | 210 | let tmp = name::SELF_PARAM; |
209 | let first_name = if path.is_self() { &tmp } else { &path.segments.first()?.name }; | 211 | let first_name = if path.is_self() { &tmp } else { &path.segments.first()?.name }; |
210 | let skip_to_mod = path.kind != PathKind::Plain && !path.is_self(); | 212 | let skip_to_mod = path.kind != PathKind::Plain && !path.is_self(); |
211 | for scope in self.scopes.iter().rev() { | 213 | for scope in self.scopes.iter().rev() { |
@@ -241,13 +243,13 @@ impl Resolver { | |||
241 | Scope::GenericParams(_) => continue, | 243 | Scope::GenericParams(_) => continue, |
242 | 244 | ||
243 | Scope::ImplBlockScope(impl_) if n_segments > 1 => { | 245 | Scope::ImplBlockScope(impl_) if n_segments > 1 => { |
244 | if first_name == &SELF_TYPE { | 246 | if first_name == &name::SELF_TYPE { |
245 | let ty = TypeNs::SelfType(*impl_); | 247 | let ty = TypeNs::SelfType(*impl_); |
246 | return Some(ResolveValueResult::Partial(ty, 1)); | 248 | return Some(ResolveValueResult::Partial(ty, 1)); |
247 | } | 249 | } |
248 | } | 250 | } |
249 | Scope::AdtScope(adt) if n_segments > 1 => { | 251 | Scope::AdtScope(adt) if n_segments > 1 => { |
250 | if first_name == &SELF_TYPE { | 252 | if first_name == &name::SELF_TYPE { |
251 | let ty = TypeNs::AdtSelfType(*adt); | 253 | let ty = TypeNs::AdtSelfType(*adt); |
252 | return Some(ResolveValueResult::Partial(ty, 1)); | 254 | return Some(ResolveValueResult::Partial(ty, 1)); |
253 | } | 255 | } |
@@ -459,10 +461,10 @@ impl Scope { | |||
459 | } | 461 | } |
460 | } | 462 | } |
461 | Scope::ImplBlockScope(i) => { | 463 | Scope::ImplBlockScope(i) => { |
462 | f(SELF_TYPE, ScopeDef::ImplSelfType(*i)); | 464 | f(name::SELF_TYPE, ScopeDef::ImplSelfType(*i)); |
463 | } | 465 | } |
464 | Scope::AdtScope(i) => { | 466 | Scope::AdtScope(i) => { |
465 | f(SELF_TYPE, ScopeDef::AdtSelfType(*i)); | 467 | f(name::SELF_TYPE, ScopeDef::AdtSelfType(*i)); |
466 | } | 468 | } |
467 | Scope::ExprScope(e) => { | 469 | Scope::ExprScope(e) => { |
468 | e.expr_scopes.entries(e.scope_id).iter().for_each(|e| { | 470 | e.expr_scopes.entries(e.scope_id).iter().for_each(|e| { |
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 730c33226..544433a0a 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs | |||
@@ -7,6 +7,7 @@ | |||
7 | //! purely for "IDE needs". | 7 | //! purely for "IDE needs". |
8 | use std::sync::Arc; | 8 | use std::sync::Arc; |
9 | 9 | ||
10 | use hir_def::{name::AsName, path::known}; | ||
10 | use ra_db::FileId; | 11 | use ra_db::FileId; |
11 | use ra_syntax::{ | 12 | use ra_syntax::{ |
12 | ast::{self, AstNode}, | 13 | ast::{self, AstNode}, |
@@ -24,11 +25,10 @@ use crate::{ | |||
24 | BodySourceMap, | 25 | BodySourceMap, |
25 | }, | 26 | }, |
26 | ids::LocationCtx, | 27 | ids::LocationCtx, |
27 | path::known, | ||
28 | resolve::{ScopeDef, TypeNs, ValueNs}, | 28 | resolve::{ScopeDef, TypeNs, ValueNs}, |
29 | ty::method_resolution::implements_trait, | 29 | ty::method_resolution::implements_trait, |
30 | AsName, Const, DefWithBody, Either, Enum, FromSource, Function, HasBody, HirFileId, MacroDef, | 30 | Const, DefWithBody, Either, Enum, FromSource, Function, HasBody, HirFileId, MacroDef, Module, |
31 | Module, Name, Path, Resolver, Static, Struct, Ty, | 31 | Name, Path, Resolver, Static, Struct, Ty, |
32 | }; | 32 | }; |
33 | 33 | ||
34 | fn try_get_resolver_for_node( | 34 | fn try_get_resolver_for_node( |
diff --git a/crates/ra_hir/src/traits.rs b/crates/ra_hir/src/traits.rs index 22f188049..514c813ab 100644 --- a/crates/ra_hir/src/traits.rs +++ b/crates/ra_hir/src/traits.rs | |||
@@ -1,14 +1,14 @@ | |||
1 | //! HIR for trait definitions. | 1 | //! HIR for trait definitions. |
2 | 2 | ||
3 | use rustc_hash::FxHashMap; | ||
4 | use std::sync::Arc; | 3 | use std::sync::Arc; |
5 | 4 | ||
5 | use hir_def::name::AsName; | ||
6 | use ra_syntax::ast::{self, NameOwner}; | 6 | use ra_syntax::ast::{self, NameOwner}; |
7 | use rustc_hash::FxHashMap; | ||
7 | 8 | ||
8 | use crate::{ | 9 | use crate::{ |
9 | db::{AstDatabase, DefDatabase}, | 10 | db::{AstDatabase, DefDatabase}, |
10 | ids::LocationCtx, | 11 | ids::LocationCtx, |
11 | name::AsName, | ||
12 | AssocItem, Const, Function, HasSource, Module, Name, Trait, TypeAlias, | 12 | AssocItem, Const, Function, HasSource, Module, Name, Trait, TypeAlias, |
13 | }; | 13 | }; |
14 | 14 | ||
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index cc9746f6d..d2bfcdc7d 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs | |||
@@ -17,8 +17,8 @@ use std::sync::Arc; | |||
17 | use std::{fmt, iter, mem}; | 17 | use std::{fmt, iter, mem}; |
18 | 18 | ||
19 | use crate::{ | 19 | use crate::{ |
20 | db::HirDatabase, expr::ExprId, type_ref::Mutability, util::make_mut_slice, Adt, Crate, | 20 | db::HirDatabase, expr::ExprId, util::make_mut_slice, Adt, Crate, DefWithBody, GenericParams, |
21 | DefWithBody, GenericParams, HasGenericParams, Name, Trait, TypeAlias, | 21 | HasGenericParams, Mutability, Name, Trait, TypeAlias, |
22 | }; | 22 | }; |
23 | use display::{HirDisplay, HirFormatter}; | 23 | use display::{HirDisplay, HirFormatter}; |
24 | 24 | ||
diff --git a/crates/ra_hir/src/ty/autoderef.rs b/crates/ra_hir/src/ty/autoderef.rs index 02492ca14..03c45546d 100644 --- a/crates/ra_hir/src/ty/autoderef.rs +++ b/crates/ra_hir/src/ty/autoderef.rs | |||
@@ -5,10 +5,11 @@ | |||
5 | 5 | ||
6 | use std::iter::successors; | 6 | use std::iter::successors; |
7 | 7 | ||
8 | use hir_def::name; | ||
8 | use log::{info, warn}; | 9 | use log::{info, warn}; |
9 | 10 | ||
10 | use super::{traits::Solution, Canonical, Substs, Ty, TypeWalk}; | 11 | use super::{traits::Solution, Canonical, Substs, Ty, TypeWalk}; |
11 | use crate::{db::HirDatabase, name, HasGenericParams, Resolver}; | 12 | use crate::{db::HirDatabase, HasGenericParams, Resolver}; |
12 | 13 | ||
13 | const AUTODEREF_RECURSION_LIMIT: usize = 10; | 14 | const AUTODEREF_RECURSION_LIMIT: usize = 10; |
14 | 15 | ||
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index ebaff998e..7466ee341 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs | |||
@@ -21,6 +21,11 @@ use std::sync::Arc; | |||
21 | use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; | 21 | use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; |
22 | use rustc_hash::FxHashMap; | 22 | use rustc_hash::FxHashMap; |
23 | 23 | ||
24 | use hir_def::{ | ||
25 | name, | ||
26 | path::known, | ||
27 | type_ref::{Mutability, TypeRef}, | ||
28 | }; | ||
24 | use ra_arena::map::ArenaMap; | 29 | use ra_arena::map::ArenaMap; |
25 | use ra_prof::profile; | 30 | use ra_prof::profile; |
26 | use test_utils::tested_by; | 31 | use test_utils::tested_by; |
@@ -37,11 +42,8 @@ use crate::{ | |||
37 | db::HirDatabase, | 42 | db::HirDatabase, |
38 | diagnostics::DiagnosticSink, | 43 | diagnostics::DiagnosticSink, |
39 | expr::{BindingAnnotation, Body, ExprId, PatId}, | 44 | expr::{BindingAnnotation, Body, ExprId, PatId}, |
40 | name, | ||
41 | path::known, | ||
42 | resolve::{Resolver, TypeNs}, | 45 | resolve::{Resolver, TypeNs}, |
43 | ty::infer::diagnostics::InferenceDiagnostic, | 46 | ty::infer::diagnostics::InferenceDiagnostic, |
44 | type_ref::{Mutability, TypeRef}, | ||
45 | Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Path, StructField, | 47 | Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Path, StructField, |
46 | }; | 48 | }; |
47 | 49 | ||
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs index 0429a9866..6ea135126 100644 --- a/crates/ra_hir/src/ty/infer/coerce.rs +++ b/crates/ra_hir/src/ty/infer/coerce.rs | |||
@@ -14,8 +14,7 @@ use crate::{ | |||
14 | lang_item::LangItemTarget, | 14 | lang_item::LangItemTarget, |
15 | resolve::Resolver, | 15 | resolve::Resolver, |
16 | ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk}, | 16 | ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk}, |
17 | type_ref::Mutability, | 17 | Adt, Mutability, |
18 | Adt, | ||
19 | }; | 18 | }; |
20 | 19 | ||
21 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | 20 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { |
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs index f8807c742..bc6437b44 100644 --- a/crates/ra_hir/src/ty/infer/expr.rs +++ b/crates/ra_hir/src/ty/infer/expr.rs | |||
@@ -3,14 +3,17 @@ | |||
3 | use std::iter::{repeat, repeat_with}; | 3 | use std::iter::{repeat, repeat_with}; |
4 | use std::sync::Arc; | 4 | use std::sync::Arc; |
5 | 5 | ||
6 | use hir_def::{ | ||
7 | name, | ||
8 | path::{GenericArg, GenericArgs}, | ||
9 | }; | ||
10 | |||
6 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | 11 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; |
7 | use crate::{ | 12 | use crate::{ |
8 | db::HirDatabase, | 13 | db::HirDatabase, |
9 | expr::{self, Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, | 14 | expr::{self, Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, |
10 | generics::{GenericParams, HasGenericParams}, | 15 | generics::{GenericParams, HasGenericParams}, |
11 | name, | ||
12 | nameres::Namespace, | 16 | nameres::Namespace, |
13 | path::{GenericArg, GenericArgs}, | ||
14 | ty::{ | 17 | ty::{ |
15 | autoderef, method_resolution, op, primitive, CallableDef, InferTy, Mutability, Obligation, | 18 | autoderef, method_resolution, op, primitive, CallableDef, InferTy, Mutability, Obligation, |
16 | ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk, | 19 | ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk, |
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir/src/ty/infer/path.rs index db979353a..77aa35ce1 100644 --- a/crates/ra_hir/src/ty/infer/path.rs +++ b/crates/ra_hir/src/ty/infer/path.rs | |||
@@ -1,5 +1,7 @@ | |||
1 | //! Path expression resolution. | 1 | //! Path expression resolution. |
2 | 2 | ||
3 | use hir_def::path::PathSegment; | ||
4 | |||
3 | use super::{ExprOrPatId, InferenceContext, TraitRef}; | 5 | use super::{ExprOrPatId, InferenceContext, TraitRef}; |
4 | use crate::{ | 6 | use crate::{ |
5 | db::HirDatabase, | 7 | db::HirDatabase, |
@@ -131,7 +133,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
131 | fn resolve_trait_assoc_item( | 133 | fn resolve_trait_assoc_item( |
132 | &mut self, | 134 | &mut self, |
133 | trait_ref: TraitRef, | 135 | trait_ref: TraitRef, |
134 | segment: &crate::path::PathSegment, | 136 | segment: &PathSegment, |
135 | id: ExprOrPatId, | 137 | id: ExprOrPatId, |
136 | ) -> Option<(ValueNs, Option<Substs>)> { | 138 | ) -> Option<(ValueNs, Option<Substs>)> { |
137 | let trait_ = trait_ref.trait_; | 139 | let trait_ = trait_ref.trait_; |
@@ -170,7 +172,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
170 | fn resolve_ty_assoc_item( | 172 | fn resolve_ty_assoc_item( |
171 | &mut self, | 173 | &mut self, |
172 | ty: Ty, | 174 | ty: Ty, |
173 | segment: &crate::path::PathSegment, | 175 | segment: &PathSegment, |
174 | id: ExprOrPatId, | 176 | id: ExprOrPatId, |
175 | ) -> Option<(ValueNs, Option<Substs>)> { | 177 | ) -> Option<(ValueNs, Option<Substs>)> { |
176 | if let Ty::Unknown = ty { | 178 | if let Ty::Unknown = ty { |
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs index 366556134..0f49a0e54 100644 --- a/crates/ra_hir/src/ty/lower.rs +++ b/crates/ra_hir/src/ty/lower.rs | |||
@@ -8,6 +8,11 @@ | |||
8 | use std::iter; | 8 | use std::iter; |
9 | use std::sync::Arc; | 9 | use std::sync::Arc; |
10 | 10 | ||
11 | use hir_def::{ | ||
12 | path::{GenericArg, PathSegment}, | ||
13 | type_ref::{TypeBound, TypeRef}, | ||
14 | }; | ||
15 | |||
11 | use super::{ | 16 | use super::{ |
12 | FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, | 17 | FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, |
13 | TypeWalk, | 18 | TypeWalk, |
@@ -18,10 +23,8 @@ use crate::{ | |||
18 | generics::HasGenericParams, | 23 | generics::HasGenericParams, |
19 | generics::{GenericDef, WherePredicate}, | 24 | generics::{GenericDef, WherePredicate}, |
20 | nameres::Namespace, | 25 | nameres::Namespace, |
21 | path::{GenericArg, PathSegment}, | ||
22 | resolve::{Resolver, TypeNs}, | 26 | resolve::{Resolver, TypeNs}, |
23 | ty::Adt, | 27 | ty::Adt, |
24 | type_ref::{TypeBound, TypeRef}, | ||
25 | util::make_mut_slice, | 28 | util::make_mut_slice, |
26 | BuiltinType, Const, Enum, EnumVariant, Function, ModuleDef, Path, Static, Struct, StructField, | 29 | BuiltinType, Const, Enum, EnumVariant, Function, ModuleDef, Path, Static, Struct, StructField, |
27 | Trait, TypeAlias, Union, | 30 | Trait, TypeAlias, Union, |
diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs index 50583a142..eb69344f6 100644 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ b/crates/ra_hir/src/ty/method_resolution.rs | |||
@@ -15,8 +15,7 @@ use crate::{ | |||
15 | resolve::Resolver, | 15 | resolve::Resolver, |
16 | ty::primitive::{FloatBitness, UncertainFloatTy, UncertainIntTy}, | 16 | ty::primitive::{FloatBitness, UncertainFloatTy, UncertainIntTy}, |
17 | ty::{Ty, TypeCtor}, | 17 | ty::{Ty, TypeCtor}, |
18 | type_ref::Mutability, | 18 | AssocItem, Crate, Function, Module, Mutability, Name, Trait, |
19 | AssocItem, Crate, Function, Module, Name, Trait, | ||
20 | }; | 19 | }; |
21 | 20 | ||
22 | /// This is used as a key for indexing impls. | 21 | /// This is used as a key for indexing impls. |
diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index ab66515be..2dd4c2fae 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs | |||
@@ -9,6 +9,7 @@ use chalk_ir::{ | |||
9 | }; | 9 | }; |
10 | use chalk_rust_ir::{AssociatedTyDatum, ImplDatum, StructDatum, TraitDatum}; | 10 | use chalk_rust_ir::{AssociatedTyDatum, ImplDatum, StructDatum, TraitDatum}; |
11 | 11 | ||
12 | use hir_def::name; | ||
12 | use ra_db::salsa::{InternId, InternKey}; | 13 | use ra_db::salsa::{InternId, InternKey}; |
13 | 14 | ||
14 | use super::{Canonical, ChalkContext, Impl, Obligation}; | 15 | use super::{Canonical, ChalkContext, Impl, Obligation}; |
@@ -734,7 +735,7 @@ fn closure_fn_trait_impl_datum( | |||
734 | substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), | 735 | substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), |
735 | }; | 736 | }; |
736 | 737 | ||
737 | let output_ty_id = fn_once_trait.associated_type_by_name(db, &crate::name::OUTPUT_TYPE)?; | 738 | let output_ty_id = fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?; |
738 | 739 | ||
739 | let output_ty_value = chalk_rust_ir::AssociatedTyValue { | 740 | let output_ty_value = chalk_rust_ir::AssociatedTyValue { |
740 | associated_ty_id: output_ty_id.to_chalk(db), | 741 | associated_ty_id: output_ty_id.to_chalk(db), |
diff --git a/crates/ra_hir/src/type_alias.rs b/crates/ra_hir/src/type_alias.rs index 674a46102..87126ee7f 100644 --- a/crates/ra_hir/src/type_alias.rs +++ b/crates/ra_hir/src/type_alias.rs | |||
@@ -2,12 +2,14 @@ | |||
2 | 2 | ||
3 | use std::sync::Arc; | 3 | use std::sync::Arc; |
4 | 4 | ||
5 | use hir_def::{ | ||
6 | name::{AsName, Name}, | ||
7 | type_ref::TypeRef, | ||
8 | }; | ||
5 | use ra_syntax::ast::NameOwner; | 9 | use ra_syntax::ast::NameOwner; |
6 | 10 | ||
7 | use crate::{ | 11 | use crate::{ |
8 | db::{AstDatabase, DefDatabase}, | 12 | db::{AstDatabase, DefDatabase}, |
9 | name::{AsName, Name}, | ||
10 | type_ref::TypeRef, | ||
11 | HasSource, TypeAlias, | 13 | HasSource, TypeAlias, |
12 | }; | 14 | }; |
13 | 15 | ||
diff --git a/crates/ra_hir/src/type_ref.rs b/crates/ra_hir/src/type_ref.rs deleted file mode 100644 index 2cf06b250..000000000 --- a/crates/ra_hir/src/type_ref.rs +++ /dev/null | |||
@@ -1,162 +0,0 @@ | |||
1 | //! HIR for references to types. Paths in these are not yet resolved. They can | ||
2 | //! be directly created from an ast::TypeRef, without further queries. | ||
3 | |||
4 | use ra_syntax::ast::{self, TypeAscriptionOwner, TypeBoundsOwner}; | ||
5 | |||
6 | use crate::Path; | ||
7 | |||
8 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | ||
9 | pub enum Mutability { | ||
10 | Shared, | ||
11 | Mut, | ||
12 | } | ||
13 | |||
14 | impl Mutability { | ||
15 | pub fn from_mutable(mutable: bool) -> Mutability { | ||
16 | if mutable { | ||
17 | Mutability::Mut | ||
18 | } else { | ||
19 | Mutability::Shared | ||
20 | } | ||
21 | } | ||
22 | |||
23 | pub fn as_keyword_for_ref(self) -> &'static str { | ||
24 | match self { | ||
25 | Mutability::Shared => "", | ||
26 | Mutability::Mut => "mut ", | ||
27 | } | ||
28 | } | ||
29 | |||
30 | pub fn as_keyword_for_ptr(self) -> &'static str { | ||
31 | match self { | ||
32 | Mutability::Shared => "const ", | ||
33 | Mutability::Mut => "mut ", | ||
34 | } | ||
35 | } | ||
36 | } | ||
37 | |||
38 | /// Compare ty::Ty | ||
39 | #[derive(Clone, PartialEq, Eq, Hash, Debug)] | ||
40 | pub enum TypeRef { | ||
41 | Never, | ||
42 | Placeholder, | ||
43 | Tuple(Vec<TypeRef>), | ||
44 | Path(Path), | ||
45 | RawPtr(Box<TypeRef>, Mutability), | ||
46 | Reference(Box<TypeRef>, Mutability), | ||
47 | Array(Box<TypeRef> /*, Expr*/), | ||
48 | Slice(Box<TypeRef>), | ||
49 | /// A fn pointer. Last element of the vector is the return type. | ||
50 | Fn(Vec<TypeRef>), | ||
51 | // For | ||
52 | ImplTrait(Vec<TypeBound>), | ||
53 | DynTrait(Vec<TypeBound>), | ||
54 | Error, | ||
55 | } | ||
56 | |||
57 | #[derive(Clone, PartialEq, Eq, Hash, Debug)] | ||
58 | pub enum TypeBound { | ||
59 | Path(Path), | ||
60 | // also for<> bounds | ||
61 | // also Lifetimes | ||
62 | Error, | ||
63 | } | ||
64 | |||
65 | impl TypeRef { | ||
66 | /// Converts an `ast::TypeRef` to a `hir::TypeRef`. | ||
67 | pub(crate) fn from_ast(node: ast::TypeRef) -> Self { | ||
68 | match node { | ||
69 | ast::TypeRef::ParenType(inner) => TypeRef::from_ast_opt(inner.type_ref()), | ||
70 | ast::TypeRef::TupleType(inner) => { | ||
71 | TypeRef::Tuple(inner.fields().map(TypeRef::from_ast).collect()) | ||
72 | } | ||
73 | ast::TypeRef::NeverType(..) => TypeRef::Never, | ||
74 | ast::TypeRef::PathType(inner) => { | ||
75 | // FIXME: Use `Path::from_src` | ||
76 | inner.path().and_then(Path::from_ast).map(TypeRef::Path).unwrap_or(TypeRef::Error) | ||
77 | } | ||
78 | ast::TypeRef::PointerType(inner) => { | ||
79 | let inner_ty = TypeRef::from_ast_opt(inner.type_ref()); | ||
80 | let mutability = Mutability::from_mutable(inner.is_mut()); | ||
81 | TypeRef::RawPtr(Box::new(inner_ty), mutability) | ||
82 | } | ||
83 | ast::TypeRef::ArrayType(inner) => { | ||
84 | TypeRef::Array(Box::new(TypeRef::from_ast_opt(inner.type_ref()))) | ||
85 | } | ||
86 | ast::TypeRef::SliceType(inner) => { | ||
87 | TypeRef::Slice(Box::new(TypeRef::from_ast_opt(inner.type_ref()))) | ||
88 | } | ||
89 | ast::TypeRef::ReferenceType(inner) => { | ||
90 | let inner_ty = TypeRef::from_ast_opt(inner.type_ref()); | ||
91 | let mutability = Mutability::from_mutable(inner.is_mut()); | ||
92 | TypeRef::Reference(Box::new(inner_ty), mutability) | ||
93 | } | ||
94 | ast::TypeRef::PlaceholderType(_inner) => TypeRef::Placeholder, | ||
95 | ast::TypeRef::FnPointerType(inner) => { | ||
96 | let ret_ty = TypeRef::from_ast_opt(inner.ret_type().and_then(|rt| rt.type_ref())); | ||
97 | let mut params = if let Some(pl) = inner.param_list() { | ||
98 | pl.params().map(|p| p.ascribed_type()).map(TypeRef::from_ast_opt).collect() | ||
99 | } else { | ||
100 | Vec::new() | ||
101 | }; | ||
102 | params.push(ret_ty); | ||
103 | TypeRef::Fn(params) | ||
104 | } | ||
105 | // for types are close enough for our purposes to the inner type for now... | ||
106 | ast::TypeRef::ForType(inner) => TypeRef::from_ast_opt(inner.type_ref()), | ||
107 | ast::TypeRef::ImplTraitType(inner) => { | ||
108 | TypeRef::ImplTrait(type_bounds_from_ast(inner.type_bound_list())) | ||
109 | } | ||
110 | ast::TypeRef::DynTraitType(inner) => { | ||
111 | TypeRef::DynTrait(type_bounds_from_ast(inner.type_bound_list())) | ||
112 | } | ||
113 | } | ||
114 | } | ||
115 | |||
116 | pub(crate) fn from_ast_opt(node: Option<ast::TypeRef>) -> Self { | ||
117 | if let Some(node) = node { | ||
118 | TypeRef::from_ast(node) | ||
119 | } else { | ||
120 | TypeRef::Error | ||
121 | } | ||
122 | } | ||
123 | |||
124 | pub fn unit() -> TypeRef { | ||
125 | TypeRef::Tuple(Vec::new()) | ||
126 | } | ||
127 | } | ||
128 | |||
129 | pub(crate) fn type_bounds_from_ast(type_bounds_opt: Option<ast::TypeBoundList>) -> Vec<TypeBound> { | ||
130 | if let Some(type_bounds) = type_bounds_opt { | ||
131 | type_bounds.bounds().map(TypeBound::from_ast).collect() | ||
132 | } else { | ||
133 | vec![] | ||
134 | } | ||
135 | } | ||
136 | |||
137 | impl TypeBound { | ||
138 | pub(crate) fn from_ast(node: ast::TypeBound) -> Self { | ||
139 | match node.kind() { | ||
140 | ast::TypeBoundKind::PathType(path_type) => { | ||
141 | let path = match path_type.path() { | ||
142 | Some(p) => p, | ||
143 | None => return TypeBound::Error, | ||
144 | }; | ||
145 | // FIXME: Use `Path::from_src` | ||
146 | let path = match Path::from_ast(path) { | ||
147 | Some(p) => p, | ||
148 | None => return TypeBound::Error, | ||
149 | }; | ||
150 | TypeBound::Path(path) | ||
151 | } | ||
152 | ast::TypeBoundKind::ForType(_) | ast::TypeBoundKind::Lifetime(_) => TypeBound::Error, | ||
153 | } | ||
154 | } | ||
155 | |||
156 | pub fn as_path(&self) -> Option<&Path> { | ||
157 | match self { | ||
158 | TypeBound::Path(p) => Some(p), | ||
159 | _ => None, | ||
160 | } | ||
161 | } | ||
162 | } | ||