c2rust-refactor 0.15.0

C2Rust refactoring tool implementation
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Functions for building AST representations of higher-level values.
use c2rust_ast_builder::mk;
use rustc::hir;
use rustc::hir::def::DefKind;
use rustc::hir::def_id::{DefId, LOCAL_CRATE};
use rustc::hir::map::definitions::DefPathData;
use rustc::hir::map::Map as HirMap;
use rustc::hir::Node;
use rustc::ty::subst::Subst;
use rustc::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
use syntax::ast::*;
use syntax::ptr::P;
use syntax::source_map::DUMMY_SP;
use syntax::symbol::kw;

use std::collections::HashMap;

use crate::ast_manip::MutVisitNodes;
use crate::command::{DriverCommand, Registry};
use crate::context::RefactorCtxt;
use crate::driver::Phase;

pub struct Reflector<'a, 'tcx> {
    tcx: TyCtxt<'tcx>,

    /// Mapping from old DefId to new DefId for defs that have been replaced
    /// after types were resolved.
    def_mapping: Option<&'a HashMap<DefId, (Option<QSelf>, Path)>>,
}

impl<'a, 'tcx> Reflector<'a, 'tcx> {
    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
        Self {
            tcx,
            def_mapping: None,
        }
    }

    /// Create a Reflector that uses `def_mapping` to look up new paths for
    /// replaced defs.
    pub fn new_with_mapping(tcx: TyCtxt<'tcx>, def_mapping: &'a HashMap<DefId, (Option<QSelf>, Path)>) -> Self {
        Self {
            tcx,
            def_mapping: Some(def_mapping),
        }
    }

    /// Build an AST representing a `ty::Ty`.
    pub fn reflect_ty(&self, ty: ty::Ty<'tcx>) -> P<Ty> {
        self.reflect_ty_inner(ty, false)
    }

    fn reflect_ty_inner(&self, ty: ty::Ty<'tcx>, infer_args: bool) -> P<Ty> {
        use rustc::ty::TyKind::*;
        match ty.kind {
            Bool => mk().ident_ty("bool"),
            Char => mk().ident_ty("char"),
            Int(ity) => mk().ident_ty(ity.name()),
            Uint(uty) => mk().ident_ty(uty.name()),
            Float(fty) => mk().ident_ty(fty.name()),
            Adt(def, substs) => {
                if infer_args {
                    let (qself, path) = self.reflect_def_path_inner(def.did, None);
                    mk().qpath_ty(qself, path)
                } else {
                    let substs = substs.types().collect::<Vec<_>>();
                    let (qself, path) = self.reflect_def_path_inner(def.did, Some(&substs));
                    mk().qpath_ty(qself, path)
                }
            }
            Foreign(did) => {
                let (qself, path) = self.reflect_def_path_inner(did, None);
                mk().qpath_ty(qself, path)
            }
            Str => mk().ident_ty("str"),
            Array(ty, len) => mk().array_ty(
                self.reflect_ty(ty),
                mk().lit_expr(mk().int_lit(len.eval_usize(self.tcx, ty::ParamEnv::empty()) as u128, "usize")),
            ),
            Slice(ty) => mk().slice_ty(self.reflect_ty(ty)),
            RawPtr(mty) => mk()
                .set_mutbl(mty.mutbl)
                .ptr_ty(self.reflect_ty(mty.ty)),
            Ref(_, ty, m) => mk().set_mutbl(m).ref_ty(self.reflect_ty(ty)),
            FnDef(_, _) => mk().infer_ty(), // unsupported (type cannot be named)
            FnPtr(poly_fn_sig) => if let Some(fn_sig) = poly_fn_sig.no_bound_vars() {
                let inputs = fn_sig.inputs().iter().map(|input| {
                    mk().arg(self.reflect_ty(input), mk().wild_pat())
                }).collect();
                let output = FunctionRetTy::Ty(self.reflect_ty(fn_sig.output()));
                mk()
                    .unsafety(fn_sig.unsafety)
                    .extern_(fn_sig.abi)
                    .barefn_ty(mk().fn_decl(inputs, output))
            } else {
                mk().infer_ty()    // TODO higher-rank lifetimes (for<'a> fn(...) -> ...)
            },
            Dynamic(_, _) => mk().infer_ty(), // TODO (dyn Trait)
            Closure(_, _) => mk().infer_ty(), // unsupported (type cannot be named)
            Generator(_, _, _) => mk().infer_ty(), // unsupported (type cannot be named)
            GeneratorWitness(_) => mk().infer_ty(), // unsupported (type cannot be named)
            Never => mk().never_ty(),
            Tuple(tys) => mk().tuple_ty(tys.types().map(|ty| self.reflect_ty(&ty)).collect()),
            Projection(..) => mk().infer_ty(),             // TODO
            UnnormalizedProjection(..) => mk().infer_ty(), // TODO
            Opaque(..) => mk().infer_ty(),                 // TODO (impl Trait)
            Param(param) => {
                if infer_args {
                    mk().infer_ty()
                } else {
                    mk().ident_ty(param.name)
                }
            }
            // `Bound` is "used only when preparing a trait query", so hopefully we never actually
            // encouter one.
            Bound(..) => mk().infer_ty(),
            // No idea what `Placeholder` is, but it sounds like something rustc-internal.
            Placeholder(..) => mk().infer_ty(),
            Infer(_) => mk().infer_ty(),
            Error => mk().infer_ty(), // unsupported
        }
    }

    /// Build a path referring to a specific def.
    fn reflect_def_path_inner(
        &self,
        id: DefId,
        opt_substs: Option<&[ty::Ty<'tcx>]>
    ) -> (Option<QSelf>, Path) {
        if let Some(mapping) = self.def_mapping {
            if let Some(new_path) = mapping.get(&id) {
                return new_path.clone();
            }
        }

        let mut segments = Vec::new();
        let mut qself = None;

        // Build the path in reverse order.  Push the name of the current def first, then the name of
        // its parent, and so on.  We flip the path around at the end.
        let mut id = id;
        let mut opt_substs = opt_substs;
        loop {
            let dk = self.tcx.def_key(id);
            match dk.disambiguated_data.data {
                DefPathData::CrateRoot => {
                    if id.krate == LOCAL_CRATE {
                        segments.push(mk().path_segment(kw::Crate));
                        break;
                    } else {
                        // Write `::crate_name` as the name of the crate. This is
                        // now correct in Rust 2018, regardless of whether we have
                        // an `extern crate`.
                        segments.push(mk().path_segment(self.tcx.crate_name(id.krate)));
                        segments.push(mk().path_segment(kw::PathRoot));
                        break;
                    }
                }

                // No idea what this is, but it doesn't have a name, so let's ignore it.
                DefPathData::Misc => {}

                DefPathData::Impl => {
                    let ty = self.tcx.type_of(id);
                    let gen = self.tcx.generics_of(id);
                    let num_params = gen.params.len();

                    // Reflect the type.  If we have substs available, apply them to the type first.
                    let ast_ty = if let Some(substs) = opt_substs {
                        let start = substs.len() - num_params;
                        let tcx_substs = substs[start..]
                            .iter()
                            .map(|&t| t.into())
                            .collect::<Vec<_>>();
                        let ty = ty.subst(self.tcx, &tcx_substs);
                        reflect_tcx_ty(self.tcx, ty)
                    } else {
                        self.reflect_ty_inner(ty, true)
                    };

                    match ast_ty.kind {
                        TyKind::Path(ref ty_qself, ref ty_path) => {
                            qself = ty_qself.clone();
                            segments.extend(ty_path.segments.iter().rev().cloned());
                        }
                        _ => {
                            qself = Some(QSelf {
                                ty: ast_ty.clone(),
                                path_span: DUMMY_SP,
                                position: 0,
                            });
                        }
                    }

                    break;
                }

                DefPathData::ValueNs(name) => {
                    if segments.is_empty() {
                        if name.as_str() != "" {
                            segments.push(mk().path_segment(name));
                        }
                    } else {
                        // This is a function, which the original DefId was inside of.  `::f::g` is not
                        // a valid path if `f` is a function.  Instead, we stop now, leaving `g` as the
                        // path.  This is not an absolute path, but it should be valid inside of `f`,
                        // which is the only place `g` is visible.
                        break;
                    }
                }

                DefPathData::TypeNs(name) => {
                    if name.as_str() != "" {
                        segments.push(mk().path_segment(name));
                    }
                }

                DefPathData::LifetimeNs(_)
                    | DefPathData::MacroNs(_)
                    | DefPathData::ClosureExpr
                    | DefPathData::Ctor
                    | DefPathData::AnonConst
                    | DefPathData::ImplTrait => {}
            }

            // Special logic for certain node kinds
            if let DefPathData::Ctor = dk.disambiguated_data.data {
                // The parent of the struct ctor in `visible_parent_map` is the parent of the
                // struct.  But we want to visit the struct first, so we can add its name.
                if let Some(parent_id) = self.tcx.parent(id) {
                    id = parent_id;
                    continue;
                } else {
                    break;
                }
            }
            match self.tcx.def_kind(id) {
                // If we query for generics_of non-local defs, we may get a
                // panic if the def cannot be generic. This is a list of
                // DefKinds that can have generic type params.
                Some(DefKind::Struct) | Some(DefKind::Union) | Some(DefKind::Enum)
                    | Some(DefKind::Variant) | Some(DefKind::Trait) | Some(DefKind::OpaqueTy)
                    | Some(DefKind::TyAlias) | Some(DefKind::ForeignTy) | Some(DefKind::TraitAlias)
                    | Some(DefKind::AssocTy) | Some(DefKind::AssocOpaqueTy)
                    | Some(DefKind::TyParam) | Some(DefKind::Fn) | Some(DefKind::Method)
                    | Some(DefKind::Ctor(..)) => {
                        let gen = self.tcx.generics_of(id);
                        let num_params = gen
                            .params
                            .iter()
                            .filter(|x| match x.kind {
                                GenericParamDefKind::Lifetime { .. } => false,
                                GenericParamDefKind::Type { .. } => true,
                                GenericParamDefKind::Const => false,
                            })
                            .count();
                        if let Some(substs) = opt_substs {
                            if !substs.is_empty() {
                                assert!(substs.len() >= num_params);
                                let start = substs.len() - num_params;
                                let tys = substs[start..]
                                    .iter()
                                    .map(|ty| self.reflect_ty(ty))
                                    .collect::<Vec<_>>();
                                let abpd = mk().angle_bracketed_args(tys);
                                segments.last_mut().unwrap().args = abpd.into();
                                opt_substs = Some(&substs[..start]);
                            }
                        }
                    }
                _ => {}
            }

            let visible_parent_map = self.tcx.visible_parent_map(LOCAL_CRATE);
            if let Some(&parent_id) = visible_parent_map.get(&id) {
                id = parent_id;
            } else if let Some(parent_id) = self.tcx.parent(id) {
                id = parent_id;
            } else {
                break;
            }
        }

        segments.reverse();
        (qself, mk().path(segments))
    }

}

/// Build an AST representing a `ty::Ty`.
pub fn reflect_tcx_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'tcx>, ty: ty::Ty<'tcx>) -> P<Ty> {
    Reflector::new(tcx).reflect_ty(ty)
}

pub fn anon_const_to_expr(hir_map: &HirMap, def_id: DefId) -> P<Expr> {
    let node = hir_map.get_if_local(def_id).unwrap();
    let ac = expect!([node] Node::AnonConst(ac) => ac);
    let body_id = ac.body;
    let body = hir_map.krate().body(body_id);
    hir_expr_to_expr(&body.value)
}

fn hir_expr_to_expr(e: &hir::Expr) -> P<Expr> {
    use rustc::hir::ExprKind::*;
    match e.kind {
        Binary(op, ref a, ref b) => {
            let op: BinOpKind = op.node.into();
            mk().binary_expr(op, hir_expr_to_expr(a), hir_expr_to_expr(b))
        }
        Unary(op, ref a) => mk().unary_expr(op.as_str(), hir_expr_to_expr(a)),
        Lit(ref l) => mk().lit_expr(l.clone()),
        ref k => panic!("unsupported variant in hir_expr_to_expr: {:?}", k),
    }
}

/// Build a path referring to a specific def.
pub fn reflect_def_path(tcx: TyCtxt, id: DefId) -> (Option<QSelf>, Path) {
    Reflector::new(tcx).reflect_def_path_inner(id, None)
}

/// Wrapper around `reflect_path` that checks first to ensure its argument is the sort of def that
/// has a path.  `reflect_path` will panic if called on a def with no path.
pub fn can_reflect_path(cx: &RefactorCtxt, id: NodeId) -> bool {
    let node = match cx.hir_map().find(id) {
        Some(x) => x,
        None => return false,
    };
    match node {
        Node::Item(_)
        | Node::ForeignItem(_)
        | Node::TraitItem(_)
        | Node::ImplItem(_)
        | Node::Variant(_)
        | Node::Field(_)
        | Node::Binding(_)
        | Node::Local(_)
        | Node::MacroDef(_)
        | Node::Ctor(_)
        | Node::GenericParam(_) => true,

        Node::AnonConst(_)
        | Node::Expr(_)
        | Node::Stmt(_)
        | Node::PathSegment(_)
        | Node::Ty(_)
        | Node::TraitRef(_)
        | Node::Pat(_)
        | Node::Arm(_)
        | Node::Param(_)
        | Node::Block(_)
        | Node::Lifetime(_)
        | Node::Visibility(_)
        | Node::Crate => false,
    }
}

/// # `test_reflect` Command
///
/// Test command - not intended for general use.
///
/// Usage: `test_reflect`
///
/// Applies path and ty reflection on every expr in the program.
fn register_test_reflect(reg: &mut Registry) {
    reg.register("test_reflect", |_args| {
        Box::new(DriverCommand::new(Phase::Phase3, move |st, cx| {
            let reflector = Reflector::new(cx.ty_ctxt());
            st.map_krate(|krate| {
                use rustc::ty::TyKind;

                MutVisitNodes::visit(krate, |e: &mut P<Expr>| {
                    let ty = cx.node_type(e.id);

                    let new_expr = if let TyKind::FnDef(def_id, ref substs) = ty.kind {
                        let substs = substs.types().collect::<Vec<_>>();
                        let (qself, path) = reflector
                            .reflect_def_path_inner(def_id, Some(&substs));
                        mk().qpath_expr(qself, path)
                    } else if let Some(def_id) = cx.try_resolve_expr(&e) {
                        let parent = cx
                            .hir_map()
                            .get_parent_item(cx.hir_map().node_to_hir_id(e.id));
                        let parent_body = cx.hir_map().body_owned_by(parent);
                        let tables = cx.ty_ctxt().body_tables(parent_body);
                        let hir_id = cx.hir_map().node_to_hir_id(e.id);
                        let substs = tables.node_substs(hir_id);
                        let substs = substs.types().collect::<Vec<_>>();
                        let (qself, path) = reflector
                            .reflect_def_path_inner(def_id, Some(&substs));
                        mk().qpath_expr(qself, path)
                    } else {
                        e.clone()
                    };

                    *e = mk().type_expr(new_expr, reflect_tcx_ty(cx.ty_ctxt(), ty));
                });
            });
        }))
    });
}

pub fn register_commands(reg: &mut Registry) {
    register_test_reflect(reg);
}