1 //! Transforms syntax into `Path` objects, ideally with accounting for hygiene
5 use crate::intern::Interned;
13 use syntax::ast::{self, AstNode, TypeBoundsOwner};
15 use super::AssociatedTypeBinding;
18 path::{GenericArg, GenericArgs, ModPath, Path, PathKind},
19 type_ref::{LifetimeRef, TypeBound, TypeRef},
22 pub(super) use lower_use::lower_use_tree;
24 /// Converts an `ast::Path` to `Path`. Works with use trees.
25 /// It correctly handles `$crate` based path from macro call.
26 pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
27 let mut kind = PathKind::Plain;
28 let mut type_anchor = None;
29 let mut segments = Vec::new();
30 let mut generic_args = Vec::new();
31 let ctx = LowerCtx::with_hygiene(hygiene);
33 let segment = path.segment()?;
35 if segment.coloncolon_token().is_some() {
39 match segment.kind()? {
40 ast::PathSegmentKind::Name(name_ref) => {
41 // FIXME: this should just return name
42 match hygiene.name_ref_to_name(name_ref) {
43 Either::Left(name) => {
46 .and_then(|it| lower_generic_args(&ctx, it))
48 lower_generic_args_from_fn_path(
56 generic_args.push(args)
58 Either::Right(crate_id) => {
59 kind = PathKind::DollarCrate(crate_id);
64 ast::PathSegmentKind::Type { type_ref, trait_ref } => {
65 assert!(path.qualifier().is_none()); // this can only occur at the first segment
67 let self_type = TypeRef::from_ast(&ctx, type_ref?);
72 type_anchor = Some(Interned::new(self_type));
73 kind = PathKind::Plain;
75 // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
77 let path = Path::from_src(trait_ref.path()?, hygiene)?;
78 let mod_path = (*path.mod_path).clone();
79 let num_segments = path.mod_path.segments.len();
82 let mut prefix_segments = mod_path.segments;
83 prefix_segments.reverse();
84 segments.extend(prefix_segments);
86 let mut prefix_args = path.generic_args;
87 prefix_args.reverse();
88 generic_args.extend(prefix_args);
90 // Insert the type reference (T in the above example) as Self parameter for the trait
92 generic_args.iter_mut().rev().nth(num_segments.saturating_sub(1))?;
93 if last_segment.is_none() {
94 *last_segment = Some(Arc::new(GenericArgs::empty()));
96 let args = last_segment.as_mut().unwrap();
97 let mut args_inner = Arc::make_mut(args);
98 args_inner.has_self_type = true;
99 args_inner.args.insert(0, GenericArg::Type(self_type));
103 ast::PathSegmentKind::CrateKw => {
104 kind = PathKind::Crate;
107 ast::PathSegmentKind::SelfKw => {
108 // don't break out if `self` is the last segment of a path, this mean we got an
109 // use tree like `foo::{self}` which we want to resolve as `foo`
110 if !segments.is_empty() {
111 kind = PathKind::Super(0);
115 ast::PathSegmentKind::SuperKw => {
116 let nested_super_count = if let PathKind::Super(n) = kind { n } else { 0 };
117 kind = PathKind::Super(nested_super_count + 1);
120 path = match qualifier(&path) {
126 generic_args.reverse();
128 if segments.is_empty() && kind == PathKind::Plain && type_anchor.is_none() {
129 // plain empty paths don't exist, this means we got a single `self` segment as our path
130 kind = PathKind::Super(0);
133 // handle local_inner_macros :
134 // Basically, even in rustc it is quite hacky:
135 // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456
136 // We follow what it did anyway :)
137 if segments.len() == 1 && kind == PathKind::Plain {
138 if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) {
139 if let Some(crate_id) = hygiene.local_inner_macros(path) {
140 kind = PathKind::DollarCrate(crate_id);
145 let mod_path = Interned::new(ModPath::from_segments(kind, segments));
146 return Some(Path { type_anchor, mod_path, generic_args });
148 fn qualifier(path: &ast::Path) -> Option<ast::Path> {
149 if let Some(q) = path.qualifier() {
152 // FIXME: this bottom up traversal is not too precise.
153 // Should we handle do a top-down analysis, recording results?
154 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
155 let use_tree = use_tree_list.parent_use_tree();
160 pub(super) fn lower_generic_args(
161 lower_ctx: &LowerCtx,
162 node: ast::GenericArgList,
163 ) -> Option<GenericArgs> {
164 let mut args = Vec::new();
165 let mut bindings = Vec::new();
166 for generic_arg in node.generic_args() {
168 ast::GenericArg::TypeArg(type_arg) => {
169 let type_ref = TypeRef::from_ast_opt(lower_ctx, type_arg.ty());
170 args.push(GenericArg::Type(type_ref));
172 ast::GenericArg::AssocTypeArg(assoc_type_arg) => {
173 if let Some(name_ref) = assoc_type_arg.name_ref() {
174 let name = name_ref.as_name();
175 let type_ref = assoc_type_arg.ty().map(|it| TypeRef::from_ast(lower_ctx, it));
176 let bounds = if let Some(l) = assoc_type_arg.type_bound_list() {
177 l.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)).collect()
181 bindings.push(AssociatedTypeBinding { name, type_ref, bounds });
184 ast::GenericArg::LifetimeArg(lifetime_arg) => {
185 if let Some(lifetime) = lifetime_arg.lifetime() {
186 let lifetime_ref = LifetimeRef::new(&lifetime);
187 args.push(GenericArg::Lifetime(lifetime_ref))
190 // constants are ignored for now.
191 ast::GenericArg::ConstArg(_) => (),
195 if args.is_empty() && bindings.is_empty() {
198 Some(GenericArgs { args, has_self_type: false, bindings })
201 /// Collect `GenericArgs` from the parts of a fn-like path, i.e. `Fn(X, Y)
202 /// -> Z` (which desugars to `Fn<(X, Y), Output=Z>`).
203 fn lower_generic_args_from_fn_path(
205 params: Option<ast::ParamList>,
206 ret_type: Option<ast::RetType>,
207 ) -> Option<GenericArgs> {
208 let mut args = Vec::new();
209 let mut bindings = Vec::new();
210 if let Some(params) = params {
211 let mut param_types = Vec::new();
212 for param in params.params() {
213 let type_ref = TypeRef::from_ast_opt(&ctx, param.ty());
214 param_types.push(type_ref);
216 let arg = GenericArg::Type(TypeRef::Tuple(param_types));
219 if let Some(ret_type) = ret_type {
220 let type_ref = TypeRef::from_ast_opt(&ctx, ret_type.ty());
221 bindings.push(AssociatedTypeBinding {
223 type_ref: Some(type_ref),
227 if args.is_empty() && bindings.is_empty() {
230 Some(GenericArgs { args, has_self_type: false, bindings })