]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/mod.rs
Rollup merge of #60220 - euclio:rustdoc-test-fatal-parsing-errors, r=QuietMisdreavus
[rust.git] / src / librustc_mir / borrow_check / nll / mod.rs
1 use crate::borrow_check::borrow_set::BorrowSet;
2 use crate::borrow_check::location::{LocationIndex, LocationTable};
3 use crate::borrow_check::nll::facts::AllFactsExt;
4 use crate::borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints};
5 use crate::borrow_check::nll::region_infer::values::RegionValueElements;
6 use crate::dataflow::indexes::BorrowIndex;
7 use crate::dataflow::move_paths::MoveData;
8 use crate::dataflow::FlowAtLocation;
9 use crate::dataflow::MaybeInitializedPlaces;
10 use crate::transform::MirSource;
11 use crate::borrow_check::Upvar;
12 use rustc::hir::def_id::DefId;
13 use rustc::infer::InferCtxt;
14 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
15 use rustc::ty::{self, RegionKind, RegionVid};
16 use rustc_errors::Diagnostic;
17 use std::fmt::Debug;
18 use std::env;
19 use std::io;
20 use std::path::PathBuf;
21 use std::rc::Rc;
22 use std::str::FromStr;
23
24 use self::mir_util::PassWhere;
25 use polonius_engine::{Algorithm, Output};
26 use crate::util as mir_util;
27 use crate::util::pretty;
28
29 mod constraint_generation;
30 pub mod explain_borrow;
31 mod facts;
32 mod invalidation;
33 crate mod region_infer;
34 mod renumber;
35 crate mod type_check;
36 mod universal_regions;
37
38 mod constraints;
39
40 use self::facts::AllFacts;
41 use self::region_infer::RegionInferenceContext;
42 use self::universal_regions::UniversalRegions;
43
44 /// Rewrites the regions in the MIR to use NLL variables, also
45 /// scraping out the set of universal regions (e.g., region parameters)
46 /// declared on the function. That set will need to be given to
47 /// `compute_regions`.
48 pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
49     infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
50     def_id: DefId,
51     param_env: ty::ParamEnv<'tcx>,
52     mir: &mut Mir<'tcx>,
53 ) -> UniversalRegions<'tcx> {
54     debug!("replace_regions_in_mir(def_id={:?})", def_id);
55
56     // Compute named region information. This also renumbers the inputs/outputs.
57     let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
58
59     // Replace all remaining regions with fresh inference variables.
60     renumber::renumber_mir(infcx, mir);
61
62     let source = MirSource::item(def_id);
63     mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
64
65     universal_regions
66 }
67
68 /// Computes the (non-lexical) regions from the input MIR.
69 ///
70 /// This may result in errors being reported.
71 pub(in crate::borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
72     infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
73     def_id: DefId,
74     universal_regions: UniversalRegions<'tcx>,
75     mir: &Mir<'tcx>,
76     upvars: &[Upvar],
77     location_table: &LocationTable,
78     param_env: ty::ParamEnv<'gcx>,
79     flow_inits: &mut FlowAtLocation<'tcx, MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
80     move_data: &MoveData<'tcx>,
81     borrow_set: &BorrowSet<'tcx>,
82     errors_buffer: &mut Vec<Diagnostic>,
83 ) -> (
84     RegionInferenceContext<'tcx>,
85     Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
86     Option<ClosureRegionRequirements<'gcx>>,
87 ) {
88     let mut all_facts = if AllFacts::enabled(infcx.tcx) {
89         Some(AllFacts::default())
90     } else {
91         None
92     };
93
94     let universal_regions = Rc::new(universal_regions);
95
96     let elements = &Rc::new(RegionValueElements::new(mir));
97
98     // Run the MIR type-checker.
99     let MirTypeckResults {
100         constraints,
101         universal_region_relations,
102     } = type_check::type_check(
103         infcx,
104         param_env,
105         mir,
106         def_id,
107         &universal_regions,
108         location_table,
109         borrow_set,
110         &mut all_facts,
111         flow_inits,
112         move_data,
113         elements,
114     );
115
116     if let Some(all_facts) = &mut all_facts {
117         all_facts
118             .universal_region
119             .extend(universal_regions.universal_regions());
120     }
121
122     // Create the region inference context, taking ownership of the
123     // region inference data that was contained in `infcx`, and the
124     // base constraints generated by the type-check.
125     let var_origins = infcx.take_region_var_origins();
126     let MirTypeckRegionConstraints {
127         placeholder_indices,
128         placeholder_index_to_region: _,
129         mut liveness_constraints,
130         outlives_constraints,
131         closure_bounds_mapping,
132         type_tests,
133     } = constraints;
134     let placeholder_indices = Rc::new(placeholder_indices);
135
136     constraint_generation::generate_constraints(
137         infcx,
138         &mut liveness_constraints,
139         &mut all_facts,
140         location_table,
141         &mir,
142         borrow_set,
143     );
144
145     let mut regioncx = RegionInferenceContext::new(
146         var_origins,
147         universal_regions,
148         placeholder_indices,
149         universal_region_relations,
150         mir,
151         outlives_constraints,
152         closure_bounds_mapping,
153         type_tests,
154         liveness_constraints,
155         elements,
156     );
157
158     // Generate various additional constraints.
159     invalidation::generate_invalidates(
160         infcx.tcx,
161         &mut all_facts,
162         location_table,
163         &mir,
164         borrow_set,
165     );
166
167     // Dump facts if requested.
168     let polonius_output = all_facts.and_then(|all_facts| {
169         if infcx.tcx.sess.opts.debugging_opts.nll_facts {
170             let def_path = infcx.tcx.hir().def_path(def_id);
171             let dir_path =
172                 PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
173             all_facts.write_to_dir(dir_path, location_table).unwrap();
174         }
175
176         if infcx.tcx.sess.opts.debugging_opts.polonius {
177             let algorithm = env::var("POLONIUS_ALGORITHM")
178                 .unwrap_or_else(|_| String::from("Hybrid"));
179             let algorithm = Algorithm::from_str(&algorithm).unwrap();
180             debug!("compute_regions: using polonius algorithm {:?}", algorithm);
181             Some(Rc::new(Output::compute(
182                 &all_facts,
183                 algorithm,
184                 false,
185             )))
186         } else {
187             None
188         }
189     });
190
191     // Solve the region constraints.
192     let closure_region_requirements =
193         regioncx.solve(infcx, &mir, upvars, def_id, errors_buffer);
194
195     // Dump MIR results into a file, if that is enabled. This let us
196     // write unit-tests, as well as helping with debugging.
197     dump_mir_results(
198         infcx,
199         MirSource::item(def_id),
200         &mir,
201         &regioncx,
202         &closure_region_requirements,
203     );
204
205     // We also have a `#[rustc_nll]` annotation that causes us to dump
206     // information
207     dump_annotation(infcx, &mir, def_id, &regioncx, &closure_region_requirements, errors_buffer);
208
209     (regioncx, polonius_output, closure_region_requirements)
210 }
211
212 fn dump_mir_results<'a, 'gcx, 'tcx>(
213     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
214     source: MirSource<'tcx>,
215     mir: &Mir<'tcx>,
216     regioncx: &RegionInferenceContext<'_>,
217     closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
218 ) {
219     if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
220         return;
221     }
222
223     mir_util::dump_mir(
224         infcx.tcx,
225         None,
226         "nll",
227         &0,
228         source,
229         mir,
230         |pass_where, out| {
231             match pass_where {
232                 // Before the CFG, dump out the values for each region variable.
233                 PassWhere::BeforeCFG => {
234                     regioncx.dump_mir(out)?;
235                     writeln!(out, "|")?;
236
237                     if let Some(closure_region_requirements) = closure_region_requirements {
238                         writeln!(out, "| Free Region Constraints")?;
239                         for_each_region_constraint(closure_region_requirements, &mut |msg| {
240                             writeln!(out, "| {}", msg)
241                         })?;
242                         writeln!(out, "|")?;
243                     }
244                 }
245
246                 PassWhere::BeforeLocation(_) => {
247                 }
248
249                 PassWhere::AfterTerminator(_) => {
250                 }
251
252                 PassWhere::BeforeBlock(_) | PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
253             }
254             Ok(())
255         },
256     );
257
258     // Also dump the inference graph constraints as a graphviz file.
259     let _: io::Result<()> = try {
260         let mut file =
261             pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
262         regioncx.dump_graphviz_raw_constraints(&mut file)?;
263     };
264
265     // Also dump the inference graph constraints as a graphviz file.
266     let _: io::Result<()> = try {
267         let mut file =
268             pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
269         regioncx.dump_graphviz_scc_constraints(&mut file)?;
270     };
271 }
272
273 fn dump_annotation<'a, 'gcx, 'tcx>(
274     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
275     mir: &Mir<'tcx>,
276     mir_def_id: DefId,
277     regioncx: &RegionInferenceContext<'tcx>,
278     closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
279     errors_buffer: &mut Vec<Diagnostic>,
280 ) {
281     let tcx = infcx.tcx;
282     let base_def_id = tcx.closure_base_def_id(mir_def_id);
283     if !tcx.has_attr(base_def_id, "rustc_regions") {
284         return;
285     }
286
287     // When the enclosing function is tagged with `#[rustc_regions]`,
288     // we dump out various bits of state as warnings. This is useful
289     // for verifying that the compiler is behaving as expected.  These
290     // warnings focus on the closure region requirements -- for
291     // viewing the intraprocedural state, the -Zdump-mir output is
292     // better.
293
294     if let Some(closure_region_requirements) = closure_region_requirements {
295         let mut err = tcx
296             .sess
297             .diagnostic()
298             .span_note_diag(mir.span, "External requirements");
299
300         regioncx.annotate(tcx, &mut err);
301
302         err.note(&format!(
303             "number of external vids: {}",
304             closure_region_requirements.num_external_vids
305         ));
306
307         // Dump the region constraints we are imposing *between* those
308         // newly created variables.
309         for_each_region_constraint(closure_region_requirements, &mut |msg| {
310             err.note(msg);
311             Ok(())
312         }).unwrap();
313
314         err.buffer(errors_buffer);
315     } else {
316         let mut err = tcx
317             .sess
318             .diagnostic()
319             .span_note_diag(mir.span, "No external requirements");
320         regioncx.annotate(tcx, &mut err);
321
322         err.buffer(errors_buffer);
323     }
324 }
325
326 fn for_each_region_constraint(
327     closure_region_requirements: &ClosureRegionRequirements<'_>,
328     with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
329 ) -> io::Result<()> {
330     for req in &closure_region_requirements.outlives_requirements {
331         let subject: &dyn Debug = match &req.subject {
332             ClosureOutlivesSubject::Region(subject) => subject,
333             ClosureOutlivesSubject::Ty(ty) => ty,
334         };
335         with_msg(&format!(
336             "where {:?}: {:?}",
337             subject, req.outlived_free_region,
338         ))?;
339     }
340     Ok(())
341 }
342
343 /// Right now, we piggy back on the `ReVar` to store our NLL inference
344 /// regions. These are indexed with `RegionVid`. This method will
345 /// assert that the region is a `ReVar` and extract its internal index.
346 /// This is reasonable because in our MIR we replace all universal regions
347 /// with inference variables.
348 pub trait ToRegionVid {
349     fn to_region_vid(self) -> RegionVid;
350 }
351
352 impl<'tcx> ToRegionVid for &'tcx RegionKind {
353     fn to_region_vid(self) -> RegionVid {
354         if let ty::ReVar(vid) = self {
355             *vid
356         } else {
357             bug!("region is not an ReVar: {:?}", self)
358         }
359     }
360 }
361
362 impl ToRegionVid for RegionVid {
363     fn to_region_vid(self) -> RegionVid {
364         self
365     }
366 }
367
368 crate trait ConstraintDescription {
369     fn description(&self) -> &'static str;
370 }