1 //! Transforms syntax into `Path` objects, ideally with accounting for hygiene
12 use syntax::ast::{self, AstNode, TypeBoundsOwner};
14 use super::AssociatedTypeBinding;
17 path::{GenericArg, GenericArgs, ModPath, Path, PathKind},
18 type_ref::{LifetimeRef, TypeBound, TypeRef},
21 pub(super) use lower_use::lower_use_tree;
23 /// Converts an `ast::Path` to `Path`. Works with use trees.
24 /// It correctly handles `$crate` based path from macro call.
25 pub(super) fn lower_path(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
26 let mut kind = PathKind::Plain;
27 let mut type_anchor = None;
28 let mut segments = Vec::new();
29 let mut generic_args = Vec::new();
30 let ctx = LowerCtx::with_hygiene(hygiene);
32 let segment = path.segment()?;
34 if segment.coloncolon_token().is_some() {
38 match segment.kind()? {
39 ast::PathSegmentKind::Name(name_ref) => {
40 // FIXME: this should just return name
41 match hygiene.name_ref_to_name(name_ref) {
42 Either::Left(name) => {
45 .and_then(|it| lower_generic_args(&ctx, it))
47 lower_generic_args_from_fn_path(
55 generic_args.push(args)
57 Either::Right(crate_id) => {
58 kind = PathKind::DollarCrate(crate_id);
63 ast::PathSegmentKind::Type { type_ref, trait_ref } => {
64 assert!(path.qualifier().is_none()); // this can only occur at the first segment
66 let self_type = TypeRef::from_ast(&ctx, type_ref?);
71 type_anchor = Some(Box::new(self_type));
72 kind = PathKind::Plain;
74 // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
76 let path = Path::from_src(trait_ref.path()?, hygiene)?;
77 kind = path.mod_path.kind;
79 let mut prefix_segments = path.mod_path.segments;
80 prefix_segments.reverse();
81 segments.extend(prefix_segments);
83 let mut prefix_args = path.generic_args;
84 prefix_args.reverse();
85 generic_args.extend(prefix_args);
87 // Insert the type reference (T in the above example) as Self parameter for the trait
88 let last_segment = generic_args.last_mut()?;
89 if last_segment.is_none() {
90 *last_segment = Some(Arc::new(GenericArgs::empty()));
92 let args = last_segment.as_mut().unwrap();
93 let mut args_inner = Arc::make_mut(args);
94 args_inner.has_self_type = true;
95 args_inner.args.insert(0, GenericArg::Type(self_type));
99 ast::PathSegmentKind::CrateKw => {
100 kind = PathKind::Crate;
103 ast::PathSegmentKind::SelfKw => {
104 kind = PathKind::Super(0);
107 ast::PathSegmentKind::SuperKw => {
108 let nested_super_count = if let PathKind::Super(n) = kind { n } else { 0 };
109 kind = PathKind::Super(nested_super_count + 1);
112 path = match qualifier(&path) {
118 generic_args.reverse();
120 // handle local_inner_macros :
121 // Basically, even in rustc it is quite hacky:
122 // https://github.com/rust-lang/rust/blob/614f273e9388ddd7804d5cbc80b8865068a3744e/src/librustc_resolve/macros.rs#L456
123 // We follow what it did anyway :)
124 if segments.len() == 1 && kind == PathKind::Plain {
125 if let Some(_macro_call) = path.syntax().parent().and_then(ast::MacroCall::cast) {
126 if let Some(crate_id) = hygiene.local_inner_macros(path) {
127 kind = PathKind::DollarCrate(crate_id);
132 let mod_path = ModPath { kind, segments };
133 return Some(Path { type_anchor, mod_path, generic_args });
135 fn qualifier(path: &ast::Path) -> Option<ast::Path> {
136 if let Some(q) = path.qualifier() {
139 // FIXME: this bottom up traversal is not too precise.
140 // Should we handle do a top-down analysis, recording results?
141 let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
142 let use_tree = use_tree_list.parent_use_tree();
147 pub(super) fn lower_generic_args(
148 lower_ctx: &LowerCtx,
149 node: ast::GenericArgList,
150 ) -> Option<GenericArgs> {
151 let mut args = Vec::new();
152 let mut bindings = Vec::new();
153 for generic_arg in node.generic_args() {
155 ast::GenericArg::TypeArg(type_arg) => {
156 let type_ref = TypeRef::from_ast_opt(lower_ctx, type_arg.ty());
157 args.push(GenericArg::Type(type_ref));
159 ast::GenericArg::AssocTypeArg(assoc_type_arg) => {
160 if let Some(name_ref) = assoc_type_arg.name_ref() {
161 let name = name_ref.as_name();
162 let type_ref = assoc_type_arg.ty().map(|it| TypeRef::from_ast(lower_ctx, it));
163 let bounds = if let Some(l) = assoc_type_arg.type_bound_list() {
164 l.bounds().map(|it| TypeBound::from_ast(lower_ctx, it)).collect()
168 bindings.push(AssociatedTypeBinding { name, type_ref, bounds });
171 ast::GenericArg::LifetimeArg(lifetime_arg) => {
172 if let Some(lifetime) = lifetime_arg.lifetime() {
173 let lifetime_ref = LifetimeRef::new(&lifetime);
174 args.push(GenericArg::Lifetime(lifetime_ref))
177 // constants are ignored for now.
178 ast::GenericArg::ConstArg(_) => (),
182 if args.is_empty() && bindings.is_empty() {
185 Some(GenericArgs { args, has_self_type: false, bindings })
188 /// Collect `GenericArgs` from the parts of a fn-like path, i.e. `Fn(X, Y)
189 /// -> Z` (which desugars to `Fn<(X, Y), Output=Z>`).
190 fn lower_generic_args_from_fn_path(
192 params: Option<ast::ParamList>,
193 ret_type: Option<ast::RetType>,
194 ) -> Option<GenericArgs> {
195 let mut args = Vec::new();
196 let mut bindings = Vec::new();
197 if let Some(params) = params {
198 let mut param_types = Vec::new();
199 for param in params.params() {
200 let type_ref = TypeRef::from_ast_opt(&ctx, param.ty());
201 param_types.push(type_ref);
203 let arg = GenericArg::Type(TypeRef::Tuple(param_types));
206 if let Some(ret_type) = ret_type {
207 let type_ref = TypeRef::from_ast_opt(&ctx, ret_type.ty());
208 bindings.push(AssociatedTypeBinding {
210 type_ref: Some(type_ref),
214 if args.is_empty() && bindings.is_empty() {
217 Some(GenericArgs { args, has_self_type: false, bindings })