2 use rustc::session::config::{Input, OutputFilenames, ErrorOutputType};
3 use rustc::session::{self, config, early_error, filesearch, Session, DiagnosticOutput};
4 use rustc::session::CrateDisambiguator;
7 use rustc_codegen_utils::codegen_backend::CodegenBackend;
8 #[cfg(parallel_compiler)]
9 use rustc_data_structures::jobserver;
10 use rustc_data_structures::sync::{Lock, Lrc};
11 use rustc_data_structures::stable_hasher::StableHasher;
12 use rustc_data_structures::fingerprint::Fingerprint;
13 use rustc_data_structures::thin_vec::ThinVec;
14 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
15 use rustc_errors::registry::Registry;
17 use rustc_metadata::dynamic_lib::DynamicLibrary;
25 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
26 use std::io::{self, Write};
28 use std::path::{Path, PathBuf};
29 use std::sync::atomic::{AtomicBool, Ordering};
30 use std::sync::{Arc, Mutex, Once};
31 use std::ops::DerefMut;
32 use smallvec::SmallVec;
34 use syntax::mut_visit::{*, MutVisitor, visit_clobber};
35 use syntax::ast::BlockCheckMode;
36 use syntax::util::lev_distance::find_best_match_for_name;
37 use syntax::source_map::{FileLoader, RealFileLoader, SourceMap};
38 use syntax::symbol::{Symbol, sym};
39 use syntax::{self, ast, attr};
40 use syntax_pos::edition::Edition;
41 #[cfg(not(parallel_compiler))]
42 use std::{thread, panic};
44 pub fn diagnostics_registry() -> Registry {
45 let mut all_errors = Vec::new();
46 all_errors.extend_from_slice(&rustc::error_codes::DIAGNOSTICS);
47 all_errors.extend_from_slice(&rustc_typeck::error_codes::DIAGNOSTICS);
48 all_errors.extend_from_slice(&rustc_resolve::error_codes::DIAGNOSTICS);
49 all_errors.extend_from_slice(&rustc_privacy::error_codes::DIAGNOSTICS);
50 // FIXME: need to figure out a way to get these back in here
51 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
52 all_errors.extend_from_slice(&rustc_metadata::error_codes::DIAGNOSTICS);
53 all_errors.extend_from_slice(&rustc_passes::error_codes::DIAGNOSTICS);
54 all_errors.extend_from_slice(&rustc_plugin::error_codes::DIAGNOSTICS);
55 all_errors.extend_from_slice(&rustc_mir::error_codes::DIAGNOSTICS);
56 all_errors.extend_from_slice(&syntax::error_codes::DIAGNOSTICS);
58 Registry::new(&all_errors)
61 /// Adds `target_feature = "..."` cfgs for a variety of platform
62 /// specific features (SSE, NEON etc.).
64 /// This is performed by checking whether a whitelisted set of
65 /// features is available on the target machine, by querying LLVM.
66 pub fn add_configuration(
67 cfg: &mut ast::CrateConfig,
69 codegen_backend: &dyn CodegenBackend,
71 let tf = sym::target_feature;
75 .target_features(sess)
77 .map(|feat| (tf, Some(feat))),
80 if sess.crt_static_feature() {
81 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
85 pub fn create_session(
86 sopts: config::Options,
87 cfg: FxHashSet<(String, Option<String>)>,
88 diagnostic_output: DiagnosticOutput,
89 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
90 input_path: Option<PathBuf>,
91 lint_caps: FxHashMap<lint::LintId, lint::Level>,
92 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>, Lrc<SourceMap>) {
93 let descriptions = diagnostics_registry();
95 let loader = file_loader.unwrap_or(box RealFileLoader);
96 let source_map = Lrc::new(SourceMap::with_file_loader(
98 sopts.file_path_mapping(),
100 let mut sess = session::build_session_with_source_map(
109 let codegen_backend = get_codegen_backend(&sess);
111 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
112 if sess.unstable_options() {
113 rustc_lint::register_internals(&mut sess.lint_store.borrow_mut(), Some(&sess));
116 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
117 add_configuration(&mut cfg, &sess, &*codegen_backend);
118 sess.parse_sess.config = cfg;
120 (Lrc::new(sess), Lrc::new(codegen_backend), source_map)
123 // Temporarily have stack size set to 32MB to deal with various crates with long method
124 // chains or deep syntax trees, except when on Haiku.
125 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
126 #[cfg(not(target_os = "haiku"))]
127 const STACK_SIZE: usize = 32 * 1024 * 1024;
129 #[cfg(target_os = "haiku")]
130 const STACK_SIZE: usize = 16 * 1024 * 1024;
132 fn get_stack_size() -> Option<usize> {
133 // FIXME: Hacks on hacks. If the env is trying to override the stack size
134 // then *don't* set it explicitly.
135 if env::var_os("RUST_MIN_STACK").is_none() {
142 struct Sink(Arc<Mutex<Vec<u8>>>);
143 impl Write for Sink {
144 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
145 Write::write(&mut *self.0.lock().unwrap(), data)
147 fn flush(&mut self) -> io::Result<()> { Ok(()) }
150 #[cfg(not(parallel_compiler))]
151 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
153 unsafe impl Send for Ptr {}
154 unsafe impl Sync for Ptr {}
157 let run = Ptr(&mut f as *mut _ as *mut ());
158 let mut result = None;
159 let result_ptr = Ptr(&mut result as *mut _ as *mut ());
161 let thread = cfg.spawn(move || {
162 let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
163 let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
164 *result = Some(run());
167 match thread.unwrap().join() {
168 Ok(()) => result.unwrap(),
169 Err(p) => panic::resume_unwind(p),
173 #[cfg(not(parallel_compiler))]
174 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
176 _threads: Option<usize>,
177 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
180 let mut cfg = thread::Builder::new().name("rustc".to_string());
182 if let Some(size) = get_stack_size() {
183 cfg = cfg.stack_size(size);
186 scoped_thread(cfg, || {
187 syntax::with_globals(edition, || {
188 ty::tls::GCX_PTR.set(&Lock::new(0), || {
189 if let Some(stderr) = stderr {
190 io::set_panic(Some(box Sink(stderr.clone())));
192 ty::tls::with_thread_locals(|| f())
198 #[cfg(parallel_compiler)]
199 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
201 threads: Option<usize>,
202 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
205 use rayon::{ThreadPool, ThreadPoolBuilder};
207 let gcx_ptr = &Lock::new(0);
209 let mut config = ThreadPoolBuilder::new()
210 .acquire_thread_handler(jobserver::acquire_thread)
211 .release_thread_handler(jobserver::release_thread)
212 .num_threads(Session::threads_from_count(threads))
213 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
215 if let Some(size) = get_stack_size() {
216 config = config.stack_size(size);
219 let with_pool = move |pool: &ThreadPool| pool.install(move || f());
221 syntax::with_globals(edition, || {
222 syntax::GLOBALS.with(|syntax_globals| {
223 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
224 // The main handler runs for each Rayon worker thread and sets up
225 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
226 // captured and set on the new threads. ty::tls::with_thread_locals sets up
227 // thread local callbacks from libsyntax
228 let main_handler = move |worker: &mut dyn FnMut()| {
229 syntax::GLOBALS.set(syntax_globals, || {
230 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
231 if let Some(stderr) = stderr {
232 io::set_panic(Some(box Sink(stderr.clone())));
234 ty::tls::with_thread_locals(|| {
235 ty::tls::GCX_PTR.set(gcx_ptr, || worker())
241 ThreadPool::scoped_pool(config, main_handler, with_pool).unwrap()
247 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
248 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
249 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
250 early_error(ErrorOutputType::default(), &err);
253 match lib.symbol("__rustc_codegen_backend") {
256 mem::transmute::<*mut u8, _>(f)
259 let err = format!("couldn't load codegen backend as it \
260 doesn't export the `__rustc_codegen_backend` \
262 early_error(ErrorOutputType::default(), &err);
268 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
269 static INIT: Once = Once::new();
271 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
274 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
275 .unwrap_or(&sess.target.target.options.codegen_backend);
276 let backend = match &codegen_name[..] {
277 filename if filename.contains(".") => {
278 load_backend_from_dylib(filename.as_ref())
280 codegen_name => get_codegen_sysroot(codegen_name),
287 let backend = unsafe { LOAD() };
292 // This is used for rustdoc, but it uses similar machinery to codegen backend
293 // loading, so we leave the code here. It is potentially useful for other tools
294 // that want to invoke the rustc binary while linking to rustc as well.
295 pub fn rustc_path<'a>() -> Option<&'a Path> {
296 static RUSTC_PATH: once_cell::sync::OnceCell<Option<PathBuf>> =
297 once_cell::sync::OnceCell::new();
299 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
301 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
304 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
305 sysroot_candidates().iter()
306 .filter_map(|sysroot| {
307 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
312 if candidate.exists() {
321 fn sysroot_candidates() -> Vec<PathBuf> {
322 let target = session::config::host_triple();
323 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
324 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
325 if let Some(dll) = path {
326 // use `parent` twice to chop off the file name and then also the
327 // directory containing the dll which should be either `lib` or `bin`.
328 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
329 // The original `path` pointed at the `rustc_driver` crate's dll.
330 // Now that dll should only be in one of two locations. The first is
331 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
332 // other is the target's libdir, for example
333 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
335 // We don't know which, so let's assume that if our `path` above
336 // ends in `$target` we *could* be in the target libdir, and always
337 // assume that we may be in the main libdir.
338 sysroot_candidates.push(path.to_owned());
340 if path.ends_with(target) {
341 sysroot_candidates.extend(path.parent() // chop off `$target`
342 .and_then(|p| p.parent()) // chop off `rustlib`
343 .and_then(|p| p.parent()) // chop off `lib`
344 .map(|s| s.to_owned()));
349 return sysroot_candidates;
352 fn current_dll_path() -> Option<PathBuf> {
353 use std::ffi::{OsStr, CStr};
354 use std::os::unix::prelude::*;
357 let addr = current_dll_path as usize as *mut _;
358 let mut info = mem::zeroed();
359 if libc::dladdr(addr, &mut info) == 0 {
360 info!("dladdr failed");
363 if info.dli_fname.is_null() {
364 info!("dladdr returned null pointer");
367 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
368 let os = OsStr::from_bytes(bytes);
369 Some(PathBuf::from(os))
374 fn current_dll_path() -> Option<PathBuf> {
375 use std::ffi::OsString;
376 use std::os::windows::prelude::*;
379 fn GetModuleHandleExW(dwFlags: u32,
381 phModule: *mut usize) -> i32;
382 fn GetModuleFileNameW(hModule: usize,
383 lpFilename: *mut u16,
387 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
391 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
392 current_dll_path as usize,
395 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
398 let mut space = Vec::with_capacity(1024);
399 let r = GetModuleFileNameW(module,
401 space.capacity() as u32);
403 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
407 if r >= space.capacity() {
408 info!("our buffer was too small? {}",
409 io::Error::last_os_error());
413 let os = OsString::from_wide(&space);
414 Some(PathBuf::from(os))
419 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
420 // For now we only allow this function to be called once as it'll dlopen a
421 // few things, which seems to work best if we only do that once. In
422 // general this assertion never trips due to the once guard in `get_codegen_backend`,
423 // but there's a few manual calls to this function in this file we protect
425 static LOADED: AtomicBool = AtomicBool::new(false);
426 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
427 "cannot load the default codegen backend twice");
429 let target = session::config::host_triple();
430 let sysroot_candidates = sysroot_candidates();
432 let sysroot = sysroot_candidates.iter()
434 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
435 sysroot.join(libdir).with_file_name(
436 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
439 info!("codegen backend candidate: {}", f.display());
443 let sysroot = sysroot.unwrap_or_else(|| {
444 let candidates = sysroot_candidates.iter()
445 .map(|p| p.display().to_string())
448 let err = format!("failed to find a `codegen-backends` folder \
449 in the sysroot candidates:\n* {}", candidates);
450 early_error(ErrorOutputType::default(), &err);
452 info!("probing {} for a codegen backend", sysroot.display());
454 let d = sysroot.read_dir().unwrap_or_else(|e| {
455 let err = format!("failed to load default codegen backend, couldn't \
456 read `{}`: {}", sysroot.display(), e);
457 early_error(ErrorOutputType::default(), &err);
460 let mut file: Option<PathBuf> = None;
462 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
463 for entry in d.filter_map(|e| e.ok()) {
464 let path = entry.path();
465 let filename = match path.file_name().and_then(|s| s.to_str()) {
469 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
472 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
473 if name != expected_name {
476 if let Some(ref prev) = file {
477 let err = format!("duplicate codegen backends found\n\
480 ", prev.display(), path.display());
481 early_error(ErrorOutputType::default(), &err);
483 file = Some(path.clone());
487 Some(ref s) => return load_backend_from_dylib(s),
489 let err = format!("failed to load default codegen backend for `{}`, \
490 no appropriate codegen dylib found in `{}`",
491 backend_name, sysroot.display());
492 early_error(ErrorOutputType::default(), &err);
498 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
499 use std::hash::Hasher;
501 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
502 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
503 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
504 // should still be safe enough to avoid collisions in practice.
505 let mut hasher = StableHasher::<Fingerprint>::new();
507 let mut metadata = session.opts.cg.metadata.clone();
508 // We don't want the crate_disambiguator to dependent on the order
509 // -C metadata arguments, so sort them:
511 // Every distinct -C metadata value is only incorporated once:
514 hasher.write(b"metadata");
516 // Also incorporate the length of a metadata string, so that we generate
517 // different values for `-Cmetadata=ab -Cmetadata=c` and
518 // `-Cmetadata=a -Cmetadata=bc`
519 hasher.write_usize(s.len());
520 hasher.write(s.as_bytes());
523 // Also incorporate crate type, so that we don't get symbol conflicts when
524 // linking against a library of the same name, if this is an executable.
528 .contains(&config::CrateType::Executable);
529 hasher.write(if is_exe { b"exe" } else { b"lib" });
531 CrateDisambiguator::from(hasher.finish())
534 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
535 // Unconditionally collect crate types from attributes to make them used
536 let attr_types: Vec<config::CrateType> = attrs
539 if a.check_name(sym::crate_type) {
540 match a.value_str() {
541 Some(sym::rlib) => Some(config::CrateType::Rlib),
542 Some(sym::dylib) => Some(config::CrateType::Dylib),
543 Some(sym::cdylib) => Some(config::CrateType::Cdylib),
544 Some(sym::lib) => Some(config::default_lib_output()),
545 Some(sym::staticlib) => Some(config::CrateType::Staticlib),
546 Some(sym::proc_dash_macro) => Some(config::CrateType::ProcMacro),
547 Some(sym::bin) => Some(config::CrateType::Executable),
549 let crate_types = vec![
555 sym::proc_dash_macro,
559 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().node {
560 let span = spanned.span;
561 let lev_candidate = find_best_match_for_name(
566 if let Some(candidate) = lev_candidate {
567 session.buffer_lint_with_diagnostic(
568 lint::builtin::UNKNOWN_CRATE_TYPES,
571 "invalid `crate_type` value",
572 lint::builtin::BuiltinLintDiagnostics::
575 "did you mean".to_string(),
576 format!("\"{}\"", candidate)
581 lint::builtin::UNKNOWN_CRATE_TYPES,
584 "invalid `crate_type` value"
598 // If we're generating a test executable, then ignore all other output
599 // styles at all other locations
600 if session.opts.test {
601 return vec![config::CrateType::Executable];
604 // Only check command line flags if present. If no types are specified by
605 // command line, then reuse the empty `base` Vec to hold the types that
606 // will be found in crate attributes.
607 let mut base = session.opts.crate_types.clone();
609 base.extend(attr_types);
611 base.push(::rustc_codegen_utils::link::default_output_for_target(
620 base.retain(|crate_type| {
621 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
624 session.warn(&format!(
625 "dropping unsupported crate type `{}` for target `{}`",
626 *crate_type, session.opts.target_triple
636 pub fn build_output_filenames(
638 odir: &Option<PathBuf>,
639 ofile: &Option<PathBuf>,
640 attrs: &[ast::Attribute],
642 ) -> OutputFilenames {
645 // "-" as input file will cause the parser to read from stdin so we
646 // have to make up a name
647 // We want to toss everything after the final '.'
648 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
650 // If a crate name is present, we use it as the link name
654 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
655 .unwrap_or_else(|| input.filestem().to_owned());
658 out_directory: dirpath,
660 single_output_file: None,
661 extra: sess.opts.cg.extra_filename.clone(),
662 outputs: sess.opts.output_types.clone(),
666 Some(ref out_file) => {
667 let unnamed_output_types = sess.opts
670 .filter(|a| a.is_none())
672 let ofile = if unnamed_output_types > 1 {
674 "due to multiple output types requested, the explicitly specified \
675 output file name will be adapted for each output type",
679 if !sess.opts.cg.extra_filename.is_empty() {
680 sess.warn("ignoring -C extra-filename flag due to -o flag");
682 Some(out_file.clone())
685 sess.warn("ignoring --out-dir flag due to -o flag");
689 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
690 out_filestem: out_file
696 single_output_file: ofile,
697 extra: sess.opts.cg.extra_filename.clone(),
698 outputs: sess.opts.output_types.clone(),
704 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
706 // FIXME: Currently the `everybody_loops` transformation is not applied to:
707 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
708 // waiting for miri to fix that.
709 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
710 // Solving this may require `!` to implement every trait, which relies on the an even more
711 // ambitious form of the closed RFC #1637. See also [#34511].
713 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
714 pub struct ReplaceBodyWithLoop<'a> {
715 within_static_or_const: bool,
716 nested_blocks: Option<Vec<ast::Block>>,
720 impl<'a> ReplaceBodyWithLoop<'a> {
721 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
722 ReplaceBodyWithLoop {
723 within_static_or_const: false,
729 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
730 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
731 let old_blocks = self.nested_blocks.take();
732 let ret = action(self);
733 self.within_static_or_const = old_const;
734 self.nested_blocks = old_blocks;
738 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
739 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
740 fn involves_impl_trait(ty: &ast::Ty) -> bool {
742 ast::TyKind::ImplTrait(..) => true,
743 ast::TyKind::Slice(ref subty) |
744 ast::TyKind::Array(ref subty, _) |
745 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
746 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
747 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
748 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
749 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
750 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
752 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
753 let types = data.args.iter().filter_map(|arg| match arg {
754 ast::GenericArg::Type(ty) => Some(ty),
757 any_involves_impl_trait(types.into_iter()) ||
758 data.constraints.iter().any(|c| {
760 ast::AssocTyConstraintKind::Bound { .. } => true,
761 ast::AssocTyConstraintKind::Equality { ref ty } =>
762 involves_impl_trait(ty),
766 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
767 any_involves_impl_trait(data.inputs.iter()) ||
768 any_involves_impl_trait(data.output.iter())
776 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
777 it.any(|subty| involves_impl_trait(subty))
780 involves_impl_trait(ty)
787 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a> {
788 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
789 let is_const = match i {
790 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
791 ast::ItemKind::Fn(ref decl, ref header, _, _) =>
792 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
795 self.run(is_const, |s| noop_visit_item_kind(i, s))
798 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
799 let is_const = match i.node {
800 ast::TraitItemKind::Const(..) => true,
801 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
802 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
805 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
808 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
809 let is_const = match i.node {
810 ast::ImplItemKind::Const(..) => true,
811 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
812 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
815 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
818 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
819 self.run(true, |s| noop_visit_anon_const(c, s))
822 fn visit_block(&mut self, b: &mut P<ast::Block>) {
823 fn stmt_to_block(rules: ast::BlockCheckMode,
824 s: Option<ast::Stmt>,
825 sess: &Session) -> ast::Block {
827 stmts: s.into_iter().collect(),
829 id: sess.next_node_id(),
830 span: syntax_pos::DUMMY_SP,
834 fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
835 let expr = P(ast::Expr {
836 id: sess.next_node_id(),
837 kind: ast::ExprKind::Block(P(b), None),
838 span: syntax_pos::DUMMY_SP,
839 attrs: ThinVec::new(),
843 id: sess.next_node_id(),
844 node: ast::StmtKind::Expr(expr),
845 span: syntax_pos::DUMMY_SP,
849 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
850 let loop_expr = P(ast::Expr {
851 kind: ast::ExprKind::Loop(P(empty_block), None),
852 id: self.sess.next_node_id(),
853 span: syntax_pos::DUMMY_SP,
854 attrs: ThinVec::new(),
857 let loop_stmt = ast::Stmt {
858 id: self.sess.next_node_id(),
859 span: syntax_pos::DUMMY_SP,
860 node: ast::StmtKind::Expr(loop_expr),
863 if self.within_static_or_const {
864 noop_visit_block(b, self)
866 visit_clobber(b.deref_mut(), |b| {
867 let mut stmts = vec![];
869 let old_blocks = self.nested_blocks.replace(vec![]);
871 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
873 // we put a Some in there earlier with that replace(), so this is valid
874 let new_blocks = self.nested_blocks.take().unwrap();
875 self.nested_blocks = old_blocks;
876 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
879 let mut new_block = ast::Block {
884 if let Some(old_blocks) = self.nested_blocks.as_mut() {
885 //push our fresh block onto the cache and yield an empty block with `loop {}`
886 if !new_block.stmts.is_empty() {
887 old_blocks.push(new_block);
890 stmt_to_block(b.rules, Some(loop_stmt), self.sess)
892 //push `loop {}` onto the end of our fresh block and yield that
893 new_block.stmts.push(loop_stmt);
901 // in general the pretty printer processes unexpanded code, so
902 // we override the default `visit_mac` method which panics.
903 fn visit_mac(&mut self, mac: &mut ast::Mac) {
904 noop_visit_mac(mac, self)