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>(
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>(
202 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
205 use rayon::{ThreadBuilder, ThreadPool, ThreadPoolBuilder};
207 let gcx_ptr = &Lock::new(0);
209 let mut config = ThreadPoolBuilder::new()
210 .thread_name(|_| "rustc".to_string())
211 .acquire_thread_handler(jobserver::acquire_thread)
212 .release_thread_handler(jobserver::release_thread)
213 .num_threads(threads)
214 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
216 if let Some(size) = get_stack_size() {
217 config = config.stack_size(size);
220 let with_pool = move |pool: &ThreadPool| pool.install(move || f());
222 syntax::with_globals(edition, || {
223 syntax::GLOBALS.with(|syntax_globals| {
224 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
225 // The main handler runs for each Rayon worker thread and sets up
226 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
227 // captured and set on the new threads. ty::tls::with_thread_locals sets up
228 // thread local callbacks from libsyntax
229 let main_handler = move |thread: ThreadBuilder| {
230 syntax::GLOBALS.set(syntax_globals, || {
231 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
232 if let Some(stderr) = stderr {
233 io::set_panic(Some(box Sink(stderr.clone())));
235 ty::tls::with_thread_locals(|| {
236 ty::tls::GCX_PTR.set(gcx_ptr, || thread.run())
242 config.build_scoped(main_handler, with_pool).unwrap()
248 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
249 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
250 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
251 early_error(ErrorOutputType::default(), &err);
254 match lib.symbol("__rustc_codegen_backend") {
257 mem::transmute::<*mut u8, _>(f)
260 let err = format!("couldn't load codegen backend as it \
261 doesn't export the `__rustc_codegen_backend` \
263 early_error(ErrorOutputType::default(), &err);
269 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
270 static INIT: Once = Once::new();
272 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
275 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
276 .unwrap_or(&sess.target.target.options.codegen_backend);
277 let backend = match &codegen_name[..] {
278 filename if filename.contains(".") => {
279 load_backend_from_dylib(filename.as_ref())
281 codegen_name => get_codegen_sysroot(codegen_name),
288 let backend = unsafe { LOAD() };
293 // This is used for rustdoc, but it uses similar machinery to codegen backend
294 // loading, so we leave the code here. It is potentially useful for other tools
295 // that want to invoke the rustc binary while linking to rustc as well.
296 pub fn rustc_path<'a>() -> Option<&'a Path> {
297 static RUSTC_PATH: once_cell::sync::OnceCell<Option<PathBuf>> =
298 once_cell::sync::OnceCell::new();
300 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
302 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
305 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
306 sysroot_candidates().iter()
307 .filter_map(|sysroot| {
308 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
313 if candidate.exists() {
322 fn sysroot_candidates() -> Vec<PathBuf> {
323 let target = session::config::host_triple();
324 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
325 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
326 if let Some(dll) = path {
327 // use `parent` twice to chop off the file name and then also the
328 // directory containing the dll which should be either `lib` or `bin`.
329 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
330 // The original `path` pointed at the `rustc_driver` crate's dll.
331 // Now that dll should only be in one of two locations. The first is
332 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
333 // other is the target's libdir, for example
334 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
336 // We don't know which, so let's assume that if our `path` above
337 // ends in `$target` we *could* be in the target libdir, and always
338 // assume that we may be in the main libdir.
339 sysroot_candidates.push(path.to_owned());
341 if path.ends_with(target) {
342 sysroot_candidates.extend(path.parent() // chop off `$target`
343 .and_then(|p| p.parent()) // chop off `rustlib`
344 .and_then(|p| p.parent()) // chop off `lib`
345 .map(|s| s.to_owned()));
350 return sysroot_candidates;
353 fn current_dll_path() -> Option<PathBuf> {
354 use std::ffi::{OsStr, CStr};
355 use std::os::unix::prelude::*;
358 let addr = current_dll_path as usize as *mut _;
359 let mut info = mem::zeroed();
360 if libc::dladdr(addr, &mut info) == 0 {
361 info!("dladdr failed");
364 if info.dli_fname.is_null() {
365 info!("dladdr returned null pointer");
368 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
369 let os = OsStr::from_bytes(bytes);
370 Some(PathBuf::from(os))
375 fn current_dll_path() -> Option<PathBuf> {
376 use std::ffi::OsString;
377 use std::os::windows::prelude::*;
380 fn GetModuleHandleExW(dwFlags: u32,
382 phModule: *mut usize) -> i32;
383 fn GetModuleFileNameW(hModule: usize,
384 lpFilename: *mut u16,
388 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
392 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
393 current_dll_path as usize,
396 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
399 let mut space = Vec::with_capacity(1024);
400 let r = GetModuleFileNameW(module,
402 space.capacity() as u32);
404 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
408 if r >= space.capacity() {
409 info!("our buffer was too small? {}",
410 io::Error::last_os_error());
414 let os = OsString::from_wide(&space);
415 Some(PathBuf::from(os))
420 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
421 // For now we only allow this function to be called once as it'll dlopen a
422 // few things, which seems to work best if we only do that once. In
423 // general this assertion never trips due to the once guard in `get_codegen_backend`,
424 // but there's a few manual calls to this function in this file we protect
426 static LOADED: AtomicBool = AtomicBool::new(false);
427 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
428 "cannot load the default codegen backend twice");
430 let target = session::config::host_triple();
431 let sysroot_candidates = sysroot_candidates();
433 let sysroot = sysroot_candidates.iter()
435 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
436 sysroot.join(libdir).with_file_name(
437 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
440 info!("codegen backend candidate: {}", f.display());
444 let sysroot = sysroot.unwrap_or_else(|| {
445 let candidates = sysroot_candidates.iter()
446 .map(|p| p.display().to_string())
449 let err = format!("failed to find a `codegen-backends` folder \
450 in the sysroot candidates:\n* {}", candidates);
451 early_error(ErrorOutputType::default(), &err);
453 info!("probing {} for a codegen backend", sysroot.display());
455 let d = sysroot.read_dir().unwrap_or_else(|e| {
456 let err = format!("failed to load default codegen backend, couldn't \
457 read `{}`: {}", sysroot.display(), e);
458 early_error(ErrorOutputType::default(), &err);
461 let mut file: Option<PathBuf> = None;
463 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
464 for entry in d.filter_map(|e| e.ok()) {
465 let path = entry.path();
466 let filename = match path.file_name().and_then(|s| s.to_str()) {
470 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
473 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
474 if name != expected_name {
477 if let Some(ref prev) = file {
478 let err = format!("duplicate codegen backends found\n\
481 ", prev.display(), path.display());
482 early_error(ErrorOutputType::default(), &err);
484 file = Some(path.clone());
488 Some(ref s) => return load_backend_from_dylib(s),
490 let err = format!("failed to load default codegen backend for `{}`, \
491 no appropriate codegen dylib found in `{}`",
492 backend_name, sysroot.display());
493 early_error(ErrorOutputType::default(), &err);
499 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
500 use std::hash::Hasher;
502 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
503 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
504 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
505 // should still be safe enough to avoid collisions in practice.
506 let mut hasher = StableHasher::new();
508 let mut metadata = session.opts.cg.metadata.clone();
509 // We don't want the crate_disambiguator to dependent on the order
510 // -C metadata arguments, so sort them:
512 // Every distinct -C metadata value is only incorporated once:
515 hasher.write(b"metadata");
517 // Also incorporate the length of a metadata string, so that we generate
518 // different values for `-Cmetadata=ab -Cmetadata=c` and
519 // `-Cmetadata=a -Cmetadata=bc`
520 hasher.write_usize(s.len());
521 hasher.write(s.as_bytes());
524 // Also incorporate crate type, so that we don't get symbol conflicts when
525 // linking against a library of the same name, if this is an executable.
529 .contains(&config::CrateType::Executable);
530 hasher.write(if is_exe { b"exe" } else { b"lib" });
532 CrateDisambiguator::from(hasher.finish::<Fingerprint>())
535 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
536 // Unconditionally collect crate types from attributes to make them used
537 let attr_types: Vec<config::CrateType> = attrs
540 if a.check_name(sym::crate_type) {
541 match a.value_str() {
542 Some(sym::rlib) => Some(config::CrateType::Rlib),
543 Some(sym::dylib) => Some(config::CrateType::Dylib),
544 Some(sym::cdylib) => Some(config::CrateType::Cdylib),
545 Some(sym::lib) => Some(config::default_lib_output()),
546 Some(sym::staticlib) => Some(config::CrateType::Staticlib),
547 Some(sym::proc_dash_macro) => Some(config::CrateType::ProcMacro),
548 Some(sym::bin) => Some(config::CrateType::Executable),
550 let crate_types = vec![
556 sym::proc_dash_macro,
560 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
561 let span = spanned.span;
562 let lev_candidate = find_best_match_for_name(
567 if let Some(candidate) = lev_candidate {
568 session.buffer_lint_with_diagnostic(
569 lint::builtin::UNKNOWN_CRATE_TYPES,
572 "invalid `crate_type` value",
573 lint::builtin::BuiltinLintDiagnostics::
576 "did you mean".to_string(),
577 format!("\"{}\"", candidate)
582 lint::builtin::UNKNOWN_CRATE_TYPES,
585 "invalid `crate_type` value"
599 // If we're generating a test executable, then ignore all other output
600 // styles at all other locations
601 if session.opts.test {
602 return vec![config::CrateType::Executable];
605 // Only check command line flags if present. If no types are specified by
606 // command line, then reuse the empty `base` Vec to hold the types that
607 // will be found in crate attributes.
608 let mut base = session.opts.crate_types.clone();
610 base.extend(attr_types);
612 base.push(::rustc_codegen_utils::link::default_output_for_target(
621 base.retain(|crate_type| {
622 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
625 session.warn(&format!(
626 "dropping unsupported crate type `{}` for target `{}`",
627 *crate_type, session.opts.target_triple
637 pub fn build_output_filenames(
639 odir: &Option<PathBuf>,
640 ofile: &Option<PathBuf>,
641 attrs: &[ast::Attribute],
643 ) -> OutputFilenames {
646 // "-" as input file will cause the parser to read from stdin so we
647 // have to make up a name
648 // We want to toss everything after the final '.'
649 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
651 // If a crate name is present, we use it as the link name
655 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
656 .unwrap_or_else(|| input.filestem().to_owned());
659 out_directory: dirpath,
661 single_output_file: None,
662 extra: sess.opts.cg.extra_filename.clone(),
663 outputs: sess.opts.output_types.clone(),
667 Some(ref out_file) => {
668 let unnamed_output_types = sess.opts
671 .filter(|a| a.is_none())
673 let ofile = if unnamed_output_types > 1 {
675 "due to multiple output types requested, the explicitly specified \
676 output file name will be adapted for each output type",
680 if !sess.opts.cg.extra_filename.is_empty() {
681 sess.warn("ignoring -C extra-filename flag due to -o flag");
683 Some(out_file.clone())
686 sess.warn("ignoring --out-dir flag due to -o flag");
690 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
691 out_filestem: out_file
697 single_output_file: ofile,
698 extra: sess.opts.cg.extra_filename.clone(),
699 outputs: sess.opts.output_types.clone(),
705 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
707 // FIXME: Currently the `everybody_loops` transformation is not applied to:
708 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
709 // waiting for miri to fix that.
710 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
711 // Solving this may require `!` to implement every trait, which relies on the an even more
712 // ambitious form of the closed RFC #1637. See also [#34511].
714 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
715 pub struct ReplaceBodyWithLoop<'a> {
716 within_static_or_const: bool,
717 nested_blocks: Option<Vec<ast::Block>>,
721 impl<'a> ReplaceBodyWithLoop<'a> {
722 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
723 ReplaceBodyWithLoop {
724 within_static_or_const: false,
730 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
731 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
732 let old_blocks = self.nested_blocks.take();
733 let ret = action(self);
734 self.within_static_or_const = old_const;
735 self.nested_blocks = old_blocks;
739 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
740 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
741 fn involves_impl_trait(ty: &ast::Ty) -> bool {
743 ast::TyKind::ImplTrait(..) => true,
744 ast::TyKind::Slice(ref subty) |
745 ast::TyKind::Array(ref subty, _) |
746 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
747 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
748 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
749 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
750 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
751 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
753 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
754 let types = data.args.iter().filter_map(|arg| match arg {
755 ast::GenericArg::Type(ty) => Some(ty),
758 any_involves_impl_trait(types.into_iter()) ||
759 data.constraints.iter().any(|c| {
761 ast::AssocTyConstraintKind::Bound { .. } => true,
762 ast::AssocTyConstraintKind::Equality { ref ty } =>
763 involves_impl_trait(ty),
767 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
768 any_involves_impl_trait(data.inputs.iter()) ||
769 any_involves_impl_trait(data.output.iter())
777 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
778 it.any(|subty| involves_impl_trait(subty))
781 involves_impl_trait(ty)
788 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a> {
789 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
790 let is_const = match i {
791 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
792 ast::ItemKind::Fn(ref decl, ref header, _, _) =>
793 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
796 self.run(is_const, |s| noop_visit_item_kind(i, s))
799 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
800 let is_const = match i.kind {
801 ast::TraitItemKind::Const(..) => true,
802 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
803 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
806 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
809 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
810 let is_const = match i.kind {
811 ast::ImplItemKind::Const(..) => true,
812 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
813 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
816 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
819 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
820 self.run(true, |s| noop_visit_anon_const(c, s))
823 fn visit_block(&mut self, b: &mut P<ast::Block>) {
824 fn stmt_to_block(rules: ast::BlockCheckMode,
825 s: Option<ast::Stmt>,
826 sess: &Session) -> ast::Block {
828 stmts: s.into_iter().collect(),
830 id: sess.next_node_id(),
831 span: syntax_pos::DUMMY_SP,
835 fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
836 let expr = P(ast::Expr {
837 id: sess.next_node_id(),
838 kind: ast::ExprKind::Block(P(b), None),
839 span: syntax_pos::DUMMY_SP,
840 attrs: ThinVec::new(),
844 id: sess.next_node_id(),
845 kind: ast::StmtKind::Expr(expr),
846 span: syntax_pos::DUMMY_SP,
850 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
851 let loop_expr = P(ast::Expr {
852 kind: ast::ExprKind::Loop(P(empty_block), None),
853 id: self.sess.next_node_id(),
854 span: syntax_pos::DUMMY_SP,
855 attrs: ThinVec::new(),
858 let loop_stmt = ast::Stmt {
859 id: self.sess.next_node_id(),
860 span: syntax_pos::DUMMY_SP,
861 kind: ast::StmtKind::Expr(loop_expr),
864 if self.within_static_or_const {
865 noop_visit_block(b, self)
867 visit_clobber(b.deref_mut(), |b| {
868 let mut stmts = vec![];
870 let old_blocks = self.nested_blocks.replace(vec![]);
872 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
874 // we put a Some in there earlier with that replace(), so this is valid
875 let new_blocks = self.nested_blocks.take().unwrap();
876 self.nested_blocks = old_blocks;
877 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
880 let mut new_block = ast::Block {
885 if let Some(old_blocks) = self.nested_blocks.as_mut() {
886 //push our fresh block onto the cache and yield an empty block with `loop {}`
887 if !new_block.stmts.is_empty() {
888 old_blocks.push(new_block);
891 stmt_to_block(b.rules, Some(loop_stmt), self.sess)
893 //push `loop {}` onto the end of our fresh block and yield that
894 new_block.stmts.push(loop_stmt);
902 // in general the pretty printer processes unexpanded code, so
903 // we override the default `visit_mac` method which panics.
904 fn visit_mac(&mut self, mac: &mut ast::Mac) {
905 noop_visit_mac(mac, self)