]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/path/lower.rs
Move incorrect case diagnostic things into their module
[rust.git] / crates / hir_def / src / path / lower.rs
1 //! Transforms syntax into `Path` objects, ideally with accounting for hygiene
2
3 mod lower_use;
4
5 use crate::intern::Interned;
6
7 use either::Either;
8 use hir_expand::name::{name, AsName};
9 use syntax::ast::{self, AstNode, HasTypeBounds};
10
11 use super::AssociatedTypeBinding;
12 use crate::{
13     body::LowerCtx,
14     path::{GenericArg, GenericArgs, ModPath, Path, PathKind},
15     type_ref::{LifetimeRef, TypeBound, TypeRef},
16 };
17
18 pub(super) use lower_use::convert_path;
19
20 /// Converts an `ast::Path` to `Path`. Works with use trees.
21 /// It correctly handles `$crate` based path from macro call.
22 pub(super) fn lower_path(mut path: ast::Path, ctx: &LowerCtx) -> Option<Path> {
23     let mut kind = PathKind::Plain;
24     let mut type_anchor = None;
25     let mut segments = Vec::new();
26     let mut generic_args = Vec::new();
27     let hygiene = ctx.hygiene();
28     loop {
29         let segment = path.segment()?;
30
31         if segment.coloncolon_token().is_some() {
32             kind = PathKind::Abs;
33         }
34
35         match segment.kind()? {
36             ast::PathSegmentKind::Name(name_ref) => {
37                 // FIXME: this should just return name
38                 match hygiene.name_ref_to_name(ctx.db.upcast(), name_ref) {
39                     Either::Left(name) => {
40                         let args = segment
41                             .generic_arg_list()
42                             .and_then(|it| lower_generic_args(ctx, it))
43                             .or_else(|| {
44                                 lower_generic_args_from_fn_path(
45                                     ctx,
46                                     segment.param_list(),
47                                     segment.ret_type(),
48                                 )
49                             })
50                             .map(Interned::new);
51                         segments.push(name);
52                         generic_args.push(args)
53                     }
54                     Either::Right(crate_id) => {
55                         kind = PathKind::DollarCrate(crate_id);
56                         break;
57                     }
58                 }
59             }
60             ast::PathSegmentKind::Type { type_ref, trait_ref } => {
61                 assert!(path.qualifier().is_none()); // this can only occur at the first segment
62
63                 let self_type = TypeRef::from_ast(ctx, type_ref?);
64
65                 match trait_ref {
66                     // <T>::foo
67                     None => {
68                         type_anchor = Some(Interned::new(self_type));
69                         kind = PathKind::Plain;
70                     }
71                     // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
72                     Some(trait_ref) => {
73                         let Path { mod_path, generic_args: path_generic_args, .. } =
74                             Path::from_src(trait_ref.path()?, ctx)?;
75                         let num_segments = mod_path.segments.len();
76                         kind = mod_path.kind;
77
78                         segments.extend(mod_path.segments.iter().cloned().rev());
79                         generic_args.extend(Vec::from(path_generic_args).into_iter().rev());
80
81                         // Insert the type reference (T in the above example) as Self parameter for the trait
82                         let last_segment =
83                             generic_args.iter_mut().rev().nth(num_segments.saturating_sub(1))?;
84                         let mut args_inner = match last_segment {
85                             Some(it) => it.as_ref().clone(),
86                             None => GenericArgs::empty(),
87                         };
88                         args_inner.has_self_type = true;
89                         args_inner.args.insert(0, GenericArg::Type(self_type));
90                         *last_segment = Some(Interned::new(args_inner));
91                     }
92                 }
93             }
94             ast::PathSegmentKind::CrateKw => {
95                 kind = PathKind::Crate;
96                 break;
97             }
98             ast::PathSegmentKind::SelfKw => {
99                 // don't break out if `self` is the last segment of a path, this mean we got a
100                 // use tree like `foo::{self}` which we want to resolve as `foo`
101                 if !segments.is_empty() {
102                     kind = PathKind::Super(0);
103                     break;
104                 }
105             }
106             ast::PathSegmentKind::SuperKw => {
107                 let nested_super_count = if let PathKind::Super(n) = kind { n } else { 0 };
108                 kind = PathKind::Super(nested_super_count + 1);
109             }
110         }
111         path = match qualifier(&path) {
112             Some(it) => it,
113             None => break,
114         };
115     }
116     segments.reverse();
117     generic_args.reverse();
118
119     if segments.is_empty() && kind == PathKind::Plain && type_anchor.is_none() {
120         // plain empty paths don't exist, this means we got a single `self` segment as our path
121         kind = PathKind::Super(0);
122     }
123
124     // handle local_inner_macros :
125     // Basically, even in rustc it is quite hacky:
126     // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456
127     // We follow what it did anyway :)
128     if segments.len() == 1 && kind == PathKind::Plain {
129         if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) {
130             if let Some(crate_id) = hygiene.local_inner_macros(ctx.db.upcast(), path) {
131                 kind = PathKind::DollarCrate(crate_id);
132             }
133         }
134     }
135
136     let mod_path = Interned::new(ModPath::from_segments(kind, segments));
137     return Some(Path { type_anchor, mod_path, generic_args: generic_args.into() });
138
139     fn qualifier(path: &ast::Path) -> Option<ast::Path> {
140         if let Some(q) = path.qualifier() {
141             return Some(q);
142         }
143         // FIXME: this bottom up traversal is not too precise.
144         // Should we handle do a top-down analysis, recording results?
145         let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
146         let use_tree = use_tree_list.parent_use_tree();
147         use_tree.path()
148     }
149 }
150
151 pub(super) fn lower_generic_args(
152     lower_ctx: &LowerCtx,
153     node: ast::GenericArgList,
154 ) -> Option<GenericArgs> {
155     let mut args = Vec::new();
156     let mut bindings = Vec::new();
157     for generic_arg in node.generic_args() {
158         match generic_arg {
159             ast::GenericArg::TypeArg(type_arg) => {
160                 let type_ref = TypeRef::from_ast_opt(lower_ctx, type_arg.ty());
161                 args.push(GenericArg::Type(type_ref));
162             }
163             ast::GenericArg::AssocTypeArg(assoc_type_arg) => {
164                 if let Some(name_ref) = assoc_type_arg.name_ref() {
165                     let name = name_ref.as_name();
166                     let type_ref = assoc_type_arg.ty().map(|it| TypeRef::from_ast(lower_ctx, it));
167                     let bounds = if let Some(l) = assoc_type_arg.type_bound_list() {
168                         l.bounds()
169                             .map(|it| Interned::new(TypeBound::from_ast(lower_ctx, it)))
170                             .collect()
171                     } else {
172                         Vec::new()
173                     };
174                     bindings.push(AssociatedTypeBinding { name, type_ref, bounds });
175                 }
176             }
177             ast::GenericArg::LifetimeArg(lifetime_arg) => {
178                 if let Some(lifetime) = lifetime_arg.lifetime() {
179                     let lifetime_ref = LifetimeRef::new(&lifetime);
180                     args.push(GenericArg::Lifetime(lifetime_ref))
181                 }
182             }
183             // constants are ignored for now.
184             ast::GenericArg::ConstArg(_) => (),
185         }
186     }
187
188     if args.is_empty() && bindings.is_empty() {
189         return None;
190     }
191     Some(GenericArgs { args, has_self_type: false, bindings, desugared_from_fn: false })
192 }
193
194 /// Collect `GenericArgs` from the parts of a fn-like path, i.e. `Fn(X, Y)
195 /// -> Z` (which desugars to `Fn<(X, Y), Output=Z>`).
196 fn lower_generic_args_from_fn_path(
197     ctx: &LowerCtx,
198     params: Option<ast::ParamList>,
199     ret_type: Option<ast::RetType>,
200 ) -> Option<GenericArgs> {
201     let mut args = Vec::new();
202     let mut bindings = Vec::new();
203     let params = params?;
204     let mut param_types = Vec::new();
205     for param in params.params() {
206         let type_ref = TypeRef::from_ast_opt(ctx, param.ty());
207         param_types.push(type_ref);
208     }
209     let arg = GenericArg::Type(TypeRef::Tuple(param_types));
210     args.push(arg);
211     if let Some(ret_type) = ret_type {
212         let type_ref = TypeRef::from_ast_opt(ctx, ret_type.ty());
213         bindings.push(AssociatedTypeBinding {
214             name: name![Output],
215             type_ref: Some(type_ref),
216             bounds: Vec::new(),
217         });
218     } else {
219         // -> ()
220         let type_ref = TypeRef::Tuple(Vec::new());
221         bindings.push(AssociatedTypeBinding {
222             name: name![Output],
223             type_ref: Some(type_ref),
224             bounds: Vec::new(),
225         });
226     }
227     Some(GenericArgs { args, has_self_type: false, bindings, desugared_from_fn: true })
228 }