1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! `fold_resolved_paths` function, for rewriting paths based on their resolved `DefId`.
use rustc::hir;
use rustc::hir::def::Def;
use smallvec::SmallVec;
use syntax::ast::*;
use syntax::mut_visit::{self, MutVisitor};
use syntax::ptr::P;
use syntax::util::map_in_place::MapInPlace;

use crate::ast_manip::util::split_uses;
use crate::ast_manip::MutVisit;
use crate::RefactorCtxt;

struct ResolvedPathFolder<'a, 'tcx: 'a, F>
where
    F: FnMut(NodeId, Option<QSelf>, Path, &Def) -> (Option<QSelf>, Path),
{
    cx: &'a RefactorCtxt<'a, 'tcx>,
    callback: F,
}

impl<'a, 'tcx, F> ResolvedPathFolder<'a, 'tcx, F>
where
    F: FnMut(NodeId, Option<QSelf>, Path, &Def) -> (Option<QSelf>, Path),
{
    // Some helper functions that get both the AST node and its HIR equivalent.

    pub fn alter_pat_path(&mut self, p: &mut P<Pat>, hir: &hir::Pat) {
        let id = p.id;
        match hir.node {
            hir::PatKind::Struct(ref qpath, _, _) => {
                unpack!([&mut p.node] PatKind::Struct(path, _fields, _dotdot));
                let (new_qself, new_path) = self.handle_qpath(id, None, path.clone(), qpath);
                assert!(
                    new_qself.is_none(),
                    "can't insert QSelf at this location (PatKind::Struct)"
                );
                *path = new_path;
            }

            hir::PatKind::TupleStruct(ref qpath, _, _) => {
                unpack!([&mut p.node] PatKind::TupleStruct(path, _fields, _dotdot_pos));
                let (new_qself, new_path) = self.handle_qpath(id, None, path.clone(), qpath);
                assert!(
                    new_qself.is_none(),
                    "can't insert QSelf at this location (PatKind::TupleStruct)"
                );
                *path = new_path;
            }

            hir::PatKind::Path(ref qpath) => {
                let (qself, path) = match &mut p.node {
                    PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
                        (None, Path::from_ident(*ident))
                    }
                    PatKind::Path(qself, path) => (qself.clone(), path.clone()),
                    _ => panic!("expected PatKind::Ident or PatKind::Path"),
                };
                let (new_qself, new_path) = self.handle_qpath(id, qself, path, qpath);

                // If it's a single-element path like `None`, emit PatKind::Ident instead of
                // PatKind::Path.  The parser treats `None` as an Ident, so if we emit Paths
                // instead, we run into "new and reparsed ASTs don't match" during rewriting.
                if new_qself.is_none() && new_path.segments.len() == 1 {
                    p.node = PatKind::Ident(
                        BindingMode::ByValue(Mutability::Immutable),
                        new_path.segments[0].ident,
                        None,
                    );
                } else {
                    p.node = PatKind::Path(new_qself, new_path);
                };
            }

            _ => {}
        }
    }

    pub fn alter_expr_path(&mut self, e: &mut P<Expr>, hir: &hir::Expr) {
        let id = e.id;
        match hir.node {
            hir::ExprKind::Path(ref qpath) => {
                unpack!([&mut e.node] ExprKind::Path(qself, path));
                let (new_qself, new_path) =
                    self.handle_qpath(id, qself.clone(), path.clone(), qpath);
                e.node = ExprKind::Path(new_qself, new_path);
            }

            hir::ExprKind::Struct(ref qpath, _, _) => {
                // Bail out early if it's not really a path type in the original AST.
                match e.node {
                    // Technically still a struct expression, but the struct to use is referenced
                    // via lang item, not by name.
                    ExprKind::Range(_, _, _) => return,
                    _ => {}
                }

                unpack!([&mut e.node] ExprKind::Struct(path, _fields, _base));
                let (new_qself, new_path) = self.handle_qpath(id, None, path.clone(), qpath);
                assert!(
                    new_qself.is_none(),
                    "can't insert QSelf at this location (ExprKind::Struct)"
                );
                *path = new_path;
            }

            _ => {}
        }
    }

    pub fn alter_ty_path(&mut self, t: &mut P<Ty>, hir: &hir::Ty) {
        let id = t.id;
        match hir.node {
            hir::TyKind::Path(ref qpath) => {
                // Bail out early if it's not really a path type in the original AST.
                match t.node {
                    TyKind::ImplicitSelf => return,
                    _ => {}
                }

                unpack!([&mut t.node] TyKind::Path(qself, path));
                let (new_qself, new_path) =
                    self.handle_qpath(id, qself.clone(), path.clone(), qpath);
                *qself = new_qself;
                *path = new_path;
            }

            _ => {}
        }
    }

    pub fn alter_use_path(&mut self, item: &mut P<Item>, hir: &hir::Item) {
        // We are ignoring the extra namespaces in the Simple case. If we
        // need to handle these we can look up HIR nodes with the other
        // NodeIds in Simple().
        let id = item.id;
        unpack!([&mut item.node] ItemKind::Use(tree));
        if let hir::ItemKind::Use(ref hir_path, _) = hir.node {
            debug!("{:?}", hir_path);
            let (_, new_path) = (self.callback)(id, None, tree.prefix.clone(), &hir_path.def);
            tree.prefix = new_path;
        }
    }

    /// Common implementation of path rewriting.  If the resolved `Def` of the path is available,
    /// rewrites the path using `self.callback`.  Otherwise the path is left unchanged.
    fn handle_qpath(
        &mut self,
        id: NodeId,
        qself: Option<QSelf>,
        path: Path,
        hir_qpath: &hir::QPath,
    ) -> (Option<QSelf>, Path) {
        match *hir_qpath {
            hir::QPath::Resolved(_, ref hir_path) => {
                (self.callback)(id, qself, path, &hir_path.def)
            }

            hir::QPath::TypeRelative(ref hir_ty, _) => {
                // If the path is type-relative, then no `DefId` is available for the whole path.
                // However, we might still be able to do something with the base `Ty`.  Pop off the
                // last segment, which is the name of the associated item, and recursively try to
                // process the `Ty`.
                let mut path = path;
                let tail = path.segments.pop().unwrap();
                let (new_qself, mut new_path) = self.handle_relative_path(id, qself, path, hir_ty);
                new_path.segments.push(tail);
                (new_qself, new_path)
            }
        }
    }

    /// Handle the base of a type-relative path.
    fn handle_relative_path(
        &mut self,
        id: NodeId,
        qself: Option<QSelf>,
        path: Path,
        hir_ty: &hir::Ty,
    ) -> (Option<QSelf>, Path) {
        match hir_ty.node {
            hir::TyKind::Path(ref qpath) => self.handle_qpath(id, qself, path, qpath),

            _ => (qself, path),
        }
    }
}

impl<'a, 'tcx, F> MutVisitor for ResolvedPathFolder<'a, 'tcx, F>
where
    F: FnMut(NodeId, Option<QSelf>, Path, &Def) -> (Option<QSelf>, Path),
{
    // There are several places in the AST that a `Path` can appear:
    //  - PatKind::Ident (single-element paths only)
    //  - PatKind::Struct
    //  - PatKind::TupleStruct
    //  - PatKind::Path
    //  - ExprKind::Path
    //  - ExprKind::Struct
    //  - Mac_.path
    //  - TyKind::Path
    //  - ViewPath_ (all variants)
    //  - Attribute.path
    //  - TraitRef.path
    //  - Visibility::Restricted.path
    //  - UseTree.prefix
    //
    // We currently support the PatKind, ExprKind, and TyKind cases.  The rest are NYI.

    fn visit_pat(&mut self, p: &mut P<Pat>) {
        if let Some(node) = self.cx.hir_map().find(p.id) {
            let hir = expect!([node]
                              hir::Node::Pat(pat) => pat,
                              hir::Node::Binding(pat) => pat);

            self.alter_pat_path(p, hir);
        }

        mut_visit::noop_visit_pat(p, self)
    }

    fn visit_expr(&mut self, e: &mut P<Expr>) {
        if let Some(node) = self.cx.hir_map().find(e.id) {
            let hir = expect!([node]
                              hir::Node::Expr(expr) => expr);

            self.alter_expr_path(e, hir);
        }

        mut_visit::noop_visit_expr(e, self)
    }

    fn visit_ty(&mut self, t: &mut P<Ty>) {
        if let Some(node) = self.cx.hir_map().find(t.id) {
            let hir = expect!([node]
                              hir::Node::Ty(ty) => ty);

            self.alter_ty_path(t, hir);
        }

        mut_visit::noop_visit_ty(t, self)
    }

    fn flat_map_item(&mut self, item: P<Item>) -> SmallVec<[P<Item>; 1]> {
        let mut v = match item.node {
            ItemKind::Use(..) => {
                // We split nested uses into simple uses to make path rewriting
                // of use statements simpler.
                let mut uses = split_uses(item);
                for item in uses.iter_mut() {
                    if let Some(node) = self.cx.hir_map().find(item.id) {
                        let hir = expect!([node] hir::Node::Item(i) => i);
                        self.alter_use_path(item, hir)
                    }
                }
                uses
            }
            _ => smallvec![item],
        };

        v.flat_map_in_place(|item| mut_visit::noop_flat_map_item(item, self));
        v
    }
}

/// Rewrite paths, with access to their resolved `Def`s in the callback.
pub fn fold_resolved_paths<T, F>(target: &mut T, cx: &RefactorCtxt, mut callback: F)
where
    T: MutVisit,
    F: FnMut(Option<QSelf>, Path, &Def) -> (Option<QSelf>, Path),
{
    let mut f = ResolvedPathFolder {
        cx: cx,
        callback: |_, q, p, d| callback(q, p, d),
    };
    target.visit(&mut f)
}

/// Like `fold_resolved_paths`, but also passes the `NodeId` of the AST node containing the path.
/// (Paths don't have `NodeId`s of their own.)
pub fn fold_resolved_paths_with_id<T, F>(target: &mut T, cx: &RefactorCtxt, callback: F)
where
    T: MutVisit,
    F: FnMut(NodeId, Option<QSelf>, Path, &Def) -> (Option<QSelf>, Path),
{
    let mut f = ResolvedPathFolder {
        cx: cx,
        callback: callback,
    };
    target.visit(&mut f)
}