frontend 0.4.0

rustc's frontend with no LLVM and no std: parsing through MIR, as a library
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use core::mem;

use crate::rustc_ast::visit::Visitor;
use crate::rustc_ast::{Attribute, Crate, EnumDef, ast, visit};
use crate::rustc_data_structures::fx::FxHashSet;
use crate::rustc_hir::def::{DefKind, Res};
use crate::rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
use crate::rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
use crate::rustc_middle::ty::Visibility;
use crate::rustc_span::def_id::{CRATE_MOD_ID, LocalModId};
use crate::rustc_span::sym;
use tracing::info;

use crate::rustc_resolve::{Decl, DeclKind, Resolver};

#[derive(Clone, Copy)]
enum ParentId<'ra> {
    Def(LocalDefId),
    Import(Decl<'ra>),
}

impl ParentId<'_> {
    fn level(self) -> Level {
        match self {
            ParentId::Def(_) => Level::Direct,
            ParentId::Import(_) => Level::Reexported,
        }
    }
}

pub(crate) struct EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
    r: &'a mut Resolver<'ra, 'tcx>,
    def_effective_visibilities: EffectiveVisibilities,
    /// While walking import chains we need to track effective visibilities per-decl, and def id
    /// keys in `Resolver::effective_visibilities` are not enough for that, because multiple
    /// declarations can correspond to a single def id in imports. So we keep a separate table.
    import_effective_visibilities: EffectiveVisibilities<Decl<'ra>>,
    // It's possible to recalculate this at any point, but it's relatively expensive.
    current_private_vis: Visibility,
    /// A set of pairs corresponding to modules, where the first module is
    /// reachable via a macro that's defined in the second module. This cannot
    /// be represented as reachable because it can't handle the following case:
    ///
    /// pub mod n {                         // Should be `Public`
    ///     pub(crate) mod p {              // Should *not* be accessible
    ///         pub fn f() -> i32 { 12 }    // Must be `Reachable`
    ///     }
    /// }
    /// pub macro m() {
    ///     n::p::f()
    /// }
    macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>,
    changed: bool,
}

impl Resolver<'_, '_> {
    fn private_vis_decl(&self, decl: Decl<'_>) -> Visibility {
        Visibility::Restricted(
            decl.parent_module.map_or(CRATE_MOD_ID, |m| m.nearest_parent_mod().expect_local()),
        )
    }

    fn private_vis_def(&self, def_id: LocalDefId) -> Visibility {
        // For mod items `normal_mod_id` will be equal to `def_id`, but we actually need its parent.
        let normal_mod_id = self
            .get_nearest_non_block_module(def_id.to_def_id())
            .nearest_parent_mod()
            .expect_local();
        if normal_mod_id.to_local_def_id() == def_id {
            Visibility::Restricted(LocalModId::new_unchecked(self.tcx.local_parent(def_id)))
        } else {
            Visibility::Restricted(normal_mod_id)
        }
    }
}

impl<'a, 'ra, 'tcx> EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
    /// Fills the `Resolver::effective_visibilities` table with public & exported items
    /// For now, this doesn't resolve macros (FIXME) and cannot resolve Impl, as we
    /// need access to a TyCtxt for that. Returns the set of ambiguous re-exports.
    pub(crate) fn compute_effective_visibilities<'c>(
        r: &'a mut Resolver<'ra, 'tcx>,
        krate: &'c Crate,
    ) -> FxHashSet<Decl<'ra>> {
        let mut visitor = EffectiveVisibilitiesVisitor {
            r,
            def_effective_visibilities: Default::default(),
            import_effective_visibilities: Default::default(),
            current_private_vis: Visibility::Restricted(CRATE_MOD_ID),
            macro_reachable: Default::default(),
            changed: true,
        };

        visitor.def_effective_visibilities.update_root();
        visitor.set_bindings_effective_visibilities(CRATE_DEF_ID);

        while visitor.changed {
            visitor.changed = false;
            visit::walk_crate(&mut visitor, krate);
        }
        visitor.r.effective_visibilities = visitor.def_effective_visibilities;

        let mut exported_ambiguities = FxHashSet::default();

        // Update visibilities for import def ids. These are not used during the
        // `EffectiveVisibilitiesVisitor` pass, because we have more detailed declaration-based
        // information, but are used by later passes. Effective visibility of an import def id
        // is the maximum value among visibilities of declarations corresponding to that def id.
        for (decl, eff_vis) in visitor.import_effective_visibilities.iter() {
            let DeclKind::Import { import, .. } = decl.kind else { unreachable!() };
            if let Some(def_id) = import.def_id() {
                r.effective_visibilities.update_eff_vis(def_id, eff_vis, r.tcx)
            }
            if decl.ambiguity.get().is_some() && eff_vis.is_public_at_level(Level::Reexported) {
                exported_ambiguities.insert(*decl);
            }
        }

        info!("resolve::effective_visibilities: {:#?}", r.effective_visibilities);

        exported_ambiguities
    }

    /// Update effective visibilities of name declarations in the given module,
    /// including their whole reexport chains.
    fn set_bindings_effective_visibilities(&mut self, module_id: LocalDefId) {
        let module = self.r.expect_module(module_id.to_def_id());
        for (_, name_resolution) in self.r.resolutions(module).iter() {
            let Some(decl) = name_resolution.borrow(self.r).best_decl() else {
                continue;
            };
            self.update_decl_chain(decl, ParentId::Def(module_id), &mut FxHashSet::default());
        }
    }

    /// Update effective visibilities for the whole reexport chain of a declaration.
    /// Set the given effective visibility level to `Level::Direct` and
    /// sets the rest of the `use` chain to `Level::Reexported` until
    /// we hit the actual exported item.
    fn update_decl_chain(
        &mut self,
        mut decl: Decl<'ra>,
        mut parent_id: ParentId<'ra>,
        seen_most_visible: &mut FxHashSet<Decl<'ra>>,
    ) {
        let priv_vis = |this: &Self, parent_id, decl| match parent_id {
            ParentId::Def(_) => this.current_private_vis,
            ParentId::Import(_) => this.r.private_vis_decl(decl),
        };
        while let DeclKind::Import { source_decl, .. } = decl.kind {
            self.update_import(decl, parent_id, priv_vis(self, parent_id, decl));
            // `ambiguity_vis_max` can cycle on mutual globs; follow each once.
            if let Some(most_visible) = decl.ambiguity_vis_max.get()
                && seen_most_visible.insert(most_visible)
            {
                self.update_decl_chain(most_visible, parent_id, seen_most_visible);
            }
            parent_id = ParentId::Import(decl);
            decl = source_decl;
        }
        if let Some(def_id) = decl.res().opt_def_id().and_then(|id| id.as_local()) {
            let priv_vis = priv_vis(self, parent_id, decl);
            self.update_def(def_id, decl.vis().expect_local(), parent_id, priv_vis);
        }
    }

    fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility {
        // Private nodes are only added to the table for caching, they could be added or removed at
        // any moment without consequences, so we don't set `changed` to true when adding them.
        *match parent_id {
            ParentId::Def(def_id) => self
                .def_effective_visibilities
                .effective_vis_or_private(def_id, || self.r.private_vis_def(def_id)),
            ParentId::Import(binding) => self
                .import_effective_visibilities
                .effective_vis_or_private(binding, || self.r.private_vis_decl(binding)),
        }
    }

    /// All effective visibilities for a node are larger or equal than private visibility
    /// for that node (see `check_invariants` in middle/privacy.rs).
    /// So if either parent or nominal visibility is the same as private visibility, then
    /// `min(parent_vis, nominal_vis) <= priv_vis`, and the update logic is guaranteed
    /// to not update anything and we can skip it.
    fn may_update(
        &self,
        nominal_vis: Visibility,
        parent_id: ParentId<'_>,
        priv_vis: Visibility,
    ) -> bool {
        nominal_vis != priv_vis
            && match parent_id {
                ParentId::Def(def_id) => self.r.tcx.local_visibility(def_id),
                ParentId::Import(decl) => decl.vis().expect_local(),
            } != priv_vis
    }

    fn update_import(&mut self, decl: Decl<'ra>, parent_id: ParentId<'ra>, priv_vis: Visibility) {
        let nominal_vis = decl.vis().expect_local();
        if !self.may_update(nominal_vis, parent_id, priv_vis) {
            return;
        };
        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
        let tcx = self.r.tcx;
        self.changed |= self.import_effective_visibilities.update(
            decl,
            Some(nominal_vis),
            priv_vis,
            inherited_eff_vis,
            parent_id.level(),
            tcx,
        );
    }

    fn update_def(
        &mut self,
        def_id: LocalDefId,
        nominal_vis: Visibility,
        parent_id: ParentId<'ra>,
        priv_vis: Visibility,
    ) {
        if !self.may_update(nominal_vis, parent_id, priv_vis) {
            return;
        };
        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
        let tcx = self.r.tcx;
        self.changed |= self.def_effective_visibilities.update(
            def_id,
            Some(nominal_vis),
            priv_vis,
            inherited_eff_vis,
            parent_id.level(),
            tcx,
        );
    }

    fn update_field(&mut self, def_id: LocalDefId, parent_id: LocalDefId) {
        let nominal_vis = self.r.tcx.local_visibility(def_id);
        self.update_def(def_id, nominal_vis, ParentId::Def(parent_id), self.current_private_vis);
    }

    fn update_macro(&mut self, def_id: LocalDefId, inherited_effective_vis: EffectiveVisibility) {
        let max_vis = Some(self.r.tcx.local_visibility(def_id));
        let priv_vis = if def_id == CRATE_DEF_ID {
            Visibility::Restricted(CRATE_MOD_ID)
        } else {
            self.r.private_vis_def(def_id)
        };
        self.changed |= self.def_effective_visibilities.update(
            def_id,
            max_vis,
            priv_vis,
            inherited_effective_vis,
            Level::Reachable,
            self.r.tcx,
        );
    }

    // We have to make sure that the items that macros might reference
    // are reachable, since they might be exported transitively.
    fn update_reachability_from_macro(
        &mut self,
        local_def_id: LocalDefId,
        md: &ast::MacroDef,
        attrs: &[Attribute],
    ) {
        // Non-opaque macros cannot make other items more accessible than they already are.
        if crate::rustc_ast::attr::find_by_name(attrs, sym::rustc_macro_transparency)
            .map_or(md.macro_rules, |attr| attr.value_str() != Some(sym::opaque))
        {
            return;
        }

        let macro_module_def_id = self.r.tcx.local_parent(local_def_id);
        if self.r.tcx.def_kind(macro_module_def_id) != DefKind::Mod {
            // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
            return;
        }

        let Some(macro_ev) = self
            .def_effective_visibilities
            .effective_vis(local_def_id)
            .filter(|ev| ev.public_at_level().is_some())
            .copied()
        else {
            return;
        };

        // Since we are starting from an externally visible module,
        // all the parents in the loop below are also guaranteed to be modules.
        let mut module_def_id = macro_module_def_id;
        loop {
            self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
            if module_def_id == CRATE_DEF_ID {
                break;
            }
            module_def_id = self.r.tcx.local_parent(module_def_id);
        }
    }

    /// Updates the item as being reachable through a macro defined in the given
    /// module. Returns `true` if the level has changed.
    fn update_macro_reachable(
        &mut self,
        module_def_id: LocalDefId,
        defining_mod: LocalDefId,
        macro_ev: EffectiveVisibility,
    ) {
        if self.macro_reachable.insert((module_def_id, defining_mod)) {
            let module = self.r.expect_module(module_def_id.to_def_id());
            for (_, name_resolution) in self.r.resolutions(module).iter() {
                let Some(decl) = name_resolution.borrow(self.r).best_decl() else {
                    continue;
                };

                if let Res::Def(def_kind, def_id) = decl.res()
                    && let Some(def_id) = def_id.as_local()
                    // FIXME: defs should be checked with `EffectiveVisibilities::is_reachable`.
                    && decl.vis().is_accessible_from(defining_mod, self.r.tcx)
                {
                    let vis = self.r.tcx.local_visibility(def_id);
                    self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod, macro_ev);
                }
            }
        }
    }

    fn update_macro_reachable_def(
        &mut self,
        def_id: LocalDefId,
        def_kind: DefKind,
        vis: Visibility,
        module: LocalDefId,
        macro_ev: EffectiveVisibility,
    ) {
        self.update_macro(def_id, macro_ev);

        match def_kind {
            DefKind::Mod => {
                if vis.is_accessible_from(module, self.r.tcx) {
                    self.update_macro_reachable(def_id, module, macro_ev);
                }
            }
            DefKind::Struct | DefKind::Union => {
                self.r.macro_reachable_adts.entry(def_id).or_default().insert(module);
            }
            _ => {}
        }
    }
}

impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
    type Result = ();

    fn visit_item(&mut self, item: &'a ast::Item) {
        let def_id = self.r.owner_def_id(item.id);
        // Update effective visibilities of nested items.
        // If it's a mod, also make the visitor walk all of its items
        match &item.kind {
            // Resolved in rustc_privacy when types are available
            ast::ItemKind::Impl(..) => return,

            // Should be unreachable at this stage
            ast::ItemKind::MacCall(..) | ast::ItemKind::DelegationMac(..) => panic!(
                "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"
            ),

            ast::ItemKind::Mod(..) => {
                let prev_private_vis = mem::replace(
                    &mut self.current_private_vis,
                    Visibility::Restricted(LocalModId::new_unchecked(def_id)),
                );
                self.set_bindings_effective_visibilities(def_id);
                visit::walk_item(self, item);
                self.current_private_vis = prev_private_vis;
            }

            ast::ItemKind::Enum(_, _, EnumDef { variants }) => {
                self.set_bindings_effective_visibilities(def_id);
                for variant in variants {
                    let variant_def_id = self.r.child_def_id(item.id, variant.id);
                    for field in variant.data.fields() {
                        self.update_field(self.r.child_def_id(item.id, field.id), variant_def_id);
                    }
                }
            }

            ast::ItemKind::Struct(_, _, def) | ast::ItemKind::Union(_, _, def) => {
                for field in def.fields() {
                    self.update_field(self.r.child_def_id(item.id, field.id), def_id);
                }
            }

            ast::ItemKind::Trait(..) => {
                self.set_bindings_effective_visibilities(def_id);
            }

            ast::ItemKind::MacroDef(_, macro_def) => {
                self.update_reachability_from_macro(def_id, macro_def, &item.attrs);
            }

            ast::ItemKind::ExternCrate(..)
            | ast::ItemKind::Use(..)
            | ast::ItemKind::Static(..)
            | ast::ItemKind::Const(..)
            | ast::ItemKind::ConstBlock(..)
            | ast::ItemKind::GlobalAsm(..)
            | ast::ItemKind::TyAlias(..)
            | ast::ItemKind::TraitAlias(..)
            | ast::ItemKind::ForeignMod(..)
            | ast::ItemKind::Fn(..)
            | ast::ItemKind::Delegation(..)
            | ast::ItemKind::TestBinderConstraints(..) => return,
        }
    }
}