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;
16 use rustc_metadata::dynamic_lib::DynamicLibrary;
24 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
25 use std::io::{self, Write};
27 use std::path::{Path, PathBuf};
28 use std::sync::atomic::{AtomicBool, Ordering};
29 use std::sync::{Arc, Mutex, Once};
30 use std::ops::DerefMut;
31 use smallvec::SmallVec;
33 use syntax::mut_visit::{*, MutVisitor, visit_clobber};
34 use syntax::ast::BlockCheckMode;
35 use syntax::util::lev_distance::find_best_match_for_name;
36 use syntax::source_map::{FileLoader, RealFileLoader, SourceMap};
37 use syntax::symbol::{Symbol, sym};
38 use syntax::{self, ast, attr};
39 use syntax_pos::edition::Edition;
40 #[cfg(not(parallel_compiler))]
41 use std::{thread, panic};
43 pub fn diagnostics_registry() -> Registry {
44 let mut all_errors = Vec::new();
45 all_errors.extend_from_slice(&rustc::error_codes::DIAGNOSTICS);
46 all_errors.extend_from_slice(&rustc_typeck::error_codes::DIAGNOSTICS);
47 all_errors.extend_from_slice(&rustc_resolve::error_codes::DIAGNOSTICS);
48 all_errors.extend_from_slice(&rustc_privacy::error_codes::DIAGNOSTICS);
49 // FIXME: need to figure out a way to get these back in here
50 // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics());
51 all_errors.extend_from_slice(&rustc_metadata::error_codes::DIAGNOSTICS);
52 all_errors.extend_from_slice(&rustc_passes::error_codes::DIAGNOSTICS);
53 all_errors.extend_from_slice(&rustc_plugin::error_codes::DIAGNOSTICS);
54 all_errors.extend_from_slice(&rustc_mir::error_codes::DIAGNOSTICS);
55 all_errors.extend_from_slice(&syntax::error_codes::DIAGNOSTICS);
57 Registry::new(&all_errors)
60 /// Adds `target_feature = "..."` cfgs for a variety of platform
61 /// specific features (SSE, NEON etc.).
63 /// This is performed by checking whether a whitelisted set of
64 /// features is available on the target machine, by querying LLVM.
65 pub fn add_configuration(
66 cfg: &mut ast::CrateConfig,
68 codegen_backend: &dyn CodegenBackend,
70 let tf = sym::target_feature;
74 .target_features(sess)
76 .map(|feat| (tf, Some(feat))),
79 if sess.crt_static_feature() {
80 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
84 pub fn create_session(
85 sopts: config::Options,
86 cfg: FxHashSet<(String, Option<String>)>,
87 diagnostic_output: DiagnosticOutput,
88 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
89 input_path: Option<PathBuf>,
90 lint_caps: FxHashMap<lint::LintId, lint::Level>,
91 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>, Lrc<SourceMap>) {
92 let descriptions = diagnostics_registry();
94 let loader = file_loader.unwrap_or(box RealFileLoader);
95 let source_map = Lrc::new(SourceMap::with_file_loader(
97 sopts.file_path_mapping(),
99 let mut sess = session::build_session_with_source_map(
108 let codegen_backend = get_codegen_backend(&sess);
110 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
111 add_configuration(&mut cfg, &sess, &*codegen_backend);
112 sess.parse_sess.config = cfg;
114 (Lrc::new(sess), Lrc::new(codegen_backend), source_map)
117 // Temporarily have stack size set to 32MB to deal with various crates with long method
118 // chains or deep syntax trees, except when on Haiku.
119 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
120 #[cfg(not(target_os = "haiku"))]
121 const STACK_SIZE: usize = 32 * 1024 * 1024;
123 #[cfg(target_os = "haiku")]
124 const STACK_SIZE: usize = 16 * 1024 * 1024;
126 fn get_stack_size() -> Option<usize> {
127 // FIXME: Hacks on hacks. If the env is trying to override the stack size
128 // then *don't* set it explicitly.
129 if env::var_os("RUST_MIN_STACK").is_none() {
136 struct Sink(Arc<Mutex<Vec<u8>>>);
137 impl Write for Sink {
138 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
139 Write::write(&mut *self.0.lock().unwrap(), data)
141 fn flush(&mut self) -> io::Result<()> { Ok(()) }
144 #[cfg(not(parallel_compiler))]
145 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
147 unsafe impl Send for Ptr {}
148 unsafe impl Sync for Ptr {}
151 let run = Ptr(&mut f as *mut _ as *mut ());
152 let mut result = None;
153 let result_ptr = Ptr(&mut result as *mut _ as *mut ());
155 let thread = cfg.spawn(move || {
156 let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
157 let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
158 *result = Some(run());
161 match thread.unwrap().join() {
162 Ok(()) => result.unwrap(),
163 Err(p) => panic::resume_unwind(p),
167 #[cfg(not(parallel_compiler))]
168 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
171 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
174 let mut cfg = thread::Builder::new().name("rustc".to_string());
176 if let Some(size) = get_stack_size() {
177 cfg = cfg.stack_size(size);
180 scoped_thread(cfg, || {
181 syntax::with_globals(edition, || {
182 ty::tls::GCX_PTR.set(&Lock::new(0), || {
183 if let Some(stderr) = stderr {
184 io::set_panic(Some(box Sink(stderr.clone())));
186 ty::tls::with_thread_locals(|| f())
192 #[cfg(parallel_compiler)]
193 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
196 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
199 use rayon::{ThreadBuilder, ThreadPool, ThreadPoolBuilder};
201 let gcx_ptr = &Lock::new(0);
203 let mut config = ThreadPoolBuilder::new()
204 .thread_name(|_| "rustc".to_string())
205 .acquire_thread_handler(jobserver::acquire_thread)
206 .release_thread_handler(jobserver::release_thread)
207 .num_threads(threads)
208 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
210 if let Some(size) = get_stack_size() {
211 config = config.stack_size(size);
214 let with_pool = move |pool: &ThreadPool| pool.install(move || f());
216 syntax::with_globals(edition, || {
217 syntax::GLOBALS.with(|syntax_globals| {
218 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
219 // The main handler runs for each Rayon worker thread and sets up
220 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
221 // captured and set on the new threads. ty::tls::with_thread_locals sets up
222 // thread local callbacks from libsyntax
223 let main_handler = move |thread: ThreadBuilder| {
224 syntax::GLOBALS.set(syntax_globals, || {
225 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
226 if let Some(stderr) = stderr {
227 io::set_panic(Some(box Sink(stderr.clone())));
229 ty::tls::with_thread_locals(|| {
230 ty::tls::GCX_PTR.set(gcx_ptr, || thread.run())
236 config.build_scoped(main_handler, with_pool).unwrap()
242 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
243 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
244 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
245 early_error(ErrorOutputType::default(), &err);
248 match lib.symbol("__rustc_codegen_backend") {
251 mem::transmute::<*mut u8, _>(f)
254 let err = format!("couldn't load codegen backend as it \
255 doesn't export the `__rustc_codegen_backend` \
257 early_error(ErrorOutputType::default(), &err);
263 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
264 static INIT: Once = Once::new();
266 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
269 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
270 .unwrap_or(&sess.target.target.options.codegen_backend);
271 let backend = match &codegen_name[..] {
272 filename if filename.contains(".") => {
273 load_backend_from_dylib(filename.as_ref())
275 codegen_name => get_codegen_sysroot(codegen_name),
282 let backend = unsafe { LOAD() };
287 // This is used for rustdoc, but it uses similar machinery to codegen backend
288 // loading, so we leave the code here. It is potentially useful for other tools
289 // that want to invoke the rustc binary while linking to rustc as well.
290 pub fn rustc_path<'a>() -> Option<&'a Path> {
291 static RUSTC_PATH: once_cell::sync::OnceCell<Option<PathBuf>> =
292 once_cell::sync::OnceCell::new();
294 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
296 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
299 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
300 sysroot_candidates().iter()
301 .filter_map(|sysroot| {
302 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
307 if candidate.exists() {
316 fn sysroot_candidates() -> Vec<PathBuf> {
317 let target = session::config::host_triple();
318 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
319 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
320 if let Some(dll) = path {
321 // use `parent` twice to chop off the file name and then also the
322 // directory containing the dll which should be either `lib` or `bin`.
323 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
324 // The original `path` pointed at the `rustc_driver` crate's dll.
325 // Now that dll should only be in one of two locations. The first is
326 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
327 // other is the target's libdir, for example
328 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
330 // We don't know which, so let's assume that if our `path` above
331 // ends in `$target` we *could* be in the target libdir, and always
332 // assume that we may be in the main libdir.
333 sysroot_candidates.push(path.to_owned());
335 if path.ends_with(target) {
336 sysroot_candidates.extend(path.parent() // chop off `$target`
337 .and_then(|p| p.parent()) // chop off `rustlib`
338 .and_then(|p| p.parent()) // chop off `lib`
339 .map(|s| s.to_owned()));
344 return sysroot_candidates;
347 fn current_dll_path() -> Option<PathBuf> {
348 use std::ffi::{OsStr, CStr};
349 use std::os::unix::prelude::*;
352 let addr = current_dll_path as usize as *mut _;
353 let mut info = mem::zeroed();
354 if libc::dladdr(addr, &mut info) == 0 {
355 info!("dladdr failed");
358 if info.dli_fname.is_null() {
359 info!("dladdr returned null pointer");
362 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
363 let os = OsStr::from_bytes(bytes);
364 Some(PathBuf::from(os))
369 fn current_dll_path() -> Option<PathBuf> {
370 use std::ffi::OsString;
371 use std::os::windows::prelude::*;
374 fn GetModuleHandleExW(dwFlags: u32,
376 phModule: *mut usize) -> i32;
377 fn GetModuleFileNameW(hModule: usize,
378 lpFilename: *mut u16,
382 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
386 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
387 current_dll_path as usize,
390 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
393 let mut space = Vec::with_capacity(1024);
394 let r = GetModuleFileNameW(module,
396 space.capacity() as u32);
398 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
402 if r >= space.capacity() {
403 info!("our buffer was too small? {}",
404 io::Error::last_os_error());
408 let os = OsString::from_wide(&space);
409 Some(PathBuf::from(os))
414 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
415 // For now we only allow this function to be called once as it'll dlopen a
416 // few things, which seems to work best if we only do that once. In
417 // general this assertion never trips due to the once guard in `get_codegen_backend`,
418 // but there's a few manual calls to this function in this file we protect
420 static LOADED: AtomicBool = AtomicBool::new(false);
421 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
422 "cannot load the default codegen backend twice");
424 let target = session::config::host_triple();
425 let sysroot_candidates = sysroot_candidates();
427 let sysroot = sysroot_candidates.iter()
429 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
430 sysroot.join(libdir).with_file_name(
431 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
434 info!("codegen backend candidate: {}", f.display());
438 let sysroot = sysroot.unwrap_or_else(|| {
439 let candidates = sysroot_candidates.iter()
440 .map(|p| p.display().to_string())
443 let err = format!("failed to find a `codegen-backends` folder \
444 in the sysroot candidates:\n* {}", candidates);
445 early_error(ErrorOutputType::default(), &err);
447 info!("probing {} for a codegen backend", sysroot.display());
449 let d = sysroot.read_dir().unwrap_or_else(|e| {
450 let err = format!("failed to load default codegen backend, couldn't \
451 read `{}`: {}", sysroot.display(), e);
452 early_error(ErrorOutputType::default(), &err);
455 let mut file: Option<PathBuf> = None;
457 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
458 for entry in d.filter_map(|e| e.ok()) {
459 let path = entry.path();
460 let filename = match path.file_name().and_then(|s| s.to_str()) {
464 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
467 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
468 if name != expected_name {
471 if let Some(ref prev) = file {
472 let err = format!("duplicate codegen backends found\n\
475 ", prev.display(), path.display());
476 early_error(ErrorOutputType::default(), &err);
478 file = Some(path.clone());
482 Some(ref s) => return load_backend_from_dylib(s),
484 let err = format!("failed to load default codegen backend for `{}`, \
485 no appropriate codegen dylib found in `{}`",
486 backend_name, sysroot.display());
487 early_error(ErrorOutputType::default(), &err);
493 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
494 use std::hash::Hasher;
496 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
497 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
498 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
499 // should still be safe enough to avoid collisions in practice.
500 let mut hasher = StableHasher::new();
502 let mut metadata = session.opts.cg.metadata.clone();
503 // We don't want the crate_disambiguator to dependent on the order
504 // -C metadata arguments, so sort them:
506 // Every distinct -C metadata value is only incorporated once:
509 hasher.write(b"metadata");
511 // Also incorporate the length of a metadata string, so that we generate
512 // different values for `-Cmetadata=ab -Cmetadata=c` and
513 // `-Cmetadata=a -Cmetadata=bc`
514 hasher.write_usize(s.len());
515 hasher.write(s.as_bytes());
518 // Also incorporate crate type, so that we don't get symbol conflicts when
519 // linking against a library of the same name, if this is an executable.
523 .contains(&config::CrateType::Executable);
524 hasher.write(if is_exe { b"exe" } else { b"lib" });
526 CrateDisambiguator::from(hasher.finish::<Fingerprint>())
529 pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut lint::LintBuffer) {
530 // Unconditionally collect crate types from attributes to make them used
531 for a in attrs.iter() {
532 if a.check_name(sym::crate_type) {
533 if let Some(n) = a.value_str() {
534 if let Some(_) = categorize_crate_type(n) {
538 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
539 let span = spanned.span;
540 let lev_candidate = find_best_match_for_name(
541 CRATE_TYPES.iter().map(|(k, _)| k),
545 if let Some(candidate) = lev_candidate {
546 lint_buffer.buffer_lint_with_diagnostic(
547 lint::builtin::UNKNOWN_CRATE_TYPES,
550 "invalid `crate_type` value",
551 lint::builtin::BuiltinLintDiagnostics::
554 "did you mean".to_string(),
555 format!("\"{}\"", candidate)
559 lint_buffer.buffer_lint(
560 lint::builtin::UNKNOWN_CRATE_TYPES,
563 "invalid `crate_type` value"
572 const CRATE_TYPES: &[(Symbol, config::CrateType)] = &[
573 (sym::rlib, config::CrateType::Rlib),
574 (sym::dylib, config::CrateType::Dylib),
575 (sym::cdylib, config::CrateType::Cdylib),
576 (sym::lib, config::default_lib_output()),
577 (sym::staticlib, config::CrateType::Staticlib),
578 (sym::proc_dash_macro, config::CrateType::ProcMacro),
579 (sym::bin, config::CrateType::Executable),
582 fn categorize_crate_type(s: Symbol) -> Option<config::CrateType> {
583 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
586 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
587 // Unconditionally collect crate types from attributes to make them used
588 let attr_types: Vec<config::CrateType> = attrs
591 if a.check_name(sym::crate_type) {
592 match a.value_str() {
593 Some(s) => categorize_crate_type(s),
602 // If we're generating a test executable, then ignore all other output
603 // styles at all other locations
604 if session.opts.test {
605 return vec![config::CrateType::Executable];
608 // Only check command line flags if present. If no types are specified by
609 // command line, then reuse the empty `base` Vec to hold the types that
610 // will be found in crate attributes.
611 let mut base = session.opts.crate_types.clone();
613 base.extend(attr_types);
615 base.push(::rustc_codegen_utils::link::default_output_for_target(
624 base.retain(|crate_type| {
625 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
628 session.warn(&format!(
629 "dropping unsupported crate type `{}` for target `{}`",
630 *crate_type, session.opts.target_triple
640 pub fn build_output_filenames(
642 odir: &Option<PathBuf>,
643 ofile: &Option<PathBuf>,
644 attrs: &[ast::Attribute],
646 ) -> OutputFilenames {
649 // "-" as input file will cause the parser to read from stdin so we
650 // have to make up a name
651 // We want to toss everything after the final '.'
652 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
654 // If a crate name is present, we use it as the link name
658 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
659 .unwrap_or_else(|| input.filestem().to_owned());
662 out_directory: dirpath,
664 single_output_file: None,
665 extra: sess.opts.cg.extra_filename.clone(),
666 outputs: sess.opts.output_types.clone(),
670 Some(ref out_file) => {
671 let unnamed_output_types = sess.opts
674 .filter(|a| a.is_none())
676 let ofile = if unnamed_output_types > 1 {
678 "due to multiple output types requested, the explicitly specified \
679 output file name will be adapted for each output type",
683 if !sess.opts.cg.extra_filename.is_empty() {
684 sess.warn("ignoring -C extra-filename flag due to -o flag");
686 Some(out_file.clone())
689 sess.warn("ignoring --out-dir flag due to -o flag");
693 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
694 out_filestem: out_file
700 single_output_file: ofile,
701 extra: sess.opts.cg.extra_filename.clone(),
702 outputs: sess.opts.output_types.clone(),
708 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
710 // FIXME: Currently the `everybody_loops` transformation is not applied to:
711 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
712 // waiting for miri to fix that.
713 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
714 // Solving this may require `!` to implement every trait, which relies on the an even more
715 // ambitious form of the closed RFC #1637. See also [#34511].
717 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
718 pub struct ReplaceBodyWithLoop<'a> {
719 within_static_or_const: bool,
720 nested_blocks: Option<Vec<ast::Block>>,
724 impl<'a> ReplaceBodyWithLoop<'a> {
725 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
726 ReplaceBodyWithLoop {
727 within_static_or_const: false,
733 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
734 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
735 let old_blocks = self.nested_blocks.take();
736 let ret = action(self);
737 self.within_static_or_const = old_const;
738 self.nested_blocks = old_blocks;
742 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
743 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
744 fn involves_impl_trait(ty: &ast::Ty) -> bool {
746 ast::TyKind::ImplTrait(..) => true,
747 ast::TyKind::Slice(ref subty) |
748 ast::TyKind::Array(ref subty, _) |
749 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
750 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
751 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
752 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
753 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
754 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
756 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
757 let types = data.args.iter().filter_map(|arg| match arg {
758 ast::GenericArg::Type(ty) => Some(ty),
761 any_involves_impl_trait(types.into_iter()) ||
762 data.constraints.iter().any(|c| {
764 ast::AssocTyConstraintKind::Bound { .. } => true,
765 ast::AssocTyConstraintKind::Equality { ref ty } =>
766 involves_impl_trait(ty),
770 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
771 any_involves_impl_trait(data.inputs.iter()) ||
772 any_involves_impl_trait(data.output.iter())
780 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
781 it.any(|subty| involves_impl_trait(subty))
784 involves_impl_trait(ty)
790 fn is_sig_const(sig: &ast::FnSig) -> bool {
791 sig.header.constness.node == ast::Constness::Const || Self::should_ignore_fn(&sig.decl)
795 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a> {
796 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
797 let is_const = match i {
798 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
799 ast::ItemKind::Fn(ref sig, _, _) => Self::is_sig_const(sig),
802 self.run(is_const, |s| noop_visit_item_kind(i, s))
805 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
806 let is_const = match i.kind {
807 ast::TraitItemKind::Const(..) => true,
808 ast::TraitItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
811 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
814 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
815 let is_const = match i.kind {
816 ast::ImplItemKind::Const(..) => true,
817 ast::ImplItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
820 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
823 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
824 self.run(true, |s| noop_visit_anon_const(c, s))
827 fn visit_block(&mut self, b: &mut P<ast::Block>) {
828 fn stmt_to_block(rules: ast::BlockCheckMode,
829 s: Option<ast::Stmt>,
830 sess: &Session) -> ast::Block {
832 stmts: s.into_iter().collect(),
834 id: sess.next_node_id(),
835 span: syntax_pos::DUMMY_SP,
839 fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
840 let expr = P(ast::Expr {
841 id: sess.next_node_id(),
842 kind: ast::ExprKind::Block(P(b), None),
843 span: syntax_pos::DUMMY_SP,
844 attrs: ThinVec::new(),
848 id: sess.next_node_id(),
849 kind: ast::StmtKind::Expr(expr),
850 span: syntax_pos::DUMMY_SP,
854 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
855 let loop_expr = P(ast::Expr {
856 kind: ast::ExprKind::Loop(P(empty_block), None),
857 id: self.sess.next_node_id(),
858 span: syntax_pos::DUMMY_SP,
859 attrs: ThinVec::new(),
862 let loop_stmt = ast::Stmt {
863 id: self.sess.next_node_id(),
864 span: syntax_pos::DUMMY_SP,
865 kind: ast::StmtKind::Expr(loop_expr),
868 if self.within_static_or_const {
869 noop_visit_block(b, self)
871 visit_clobber(b.deref_mut(), |b| {
872 let mut stmts = vec![];
874 let old_blocks = self.nested_blocks.replace(vec![]);
876 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
878 // we put a Some in there earlier with that replace(), so this is valid
879 let new_blocks = self.nested_blocks.take().unwrap();
880 self.nested_blocks = old_blocks;
881 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
884 let mut new_block = ast::Block {
889 if let Some(old_blocks) = self.nested_blocks.as_mut() {
890 //push our fresh block onto the cache and yield an empty block with `loop {}`
891 if !new_block.stmts.is_empty() {
892 old_blocks.push(new_block);
895 stmt_to_block(b.rules, Some(loop_stmt), self.sess)
897 //push `loop {}` onto the end of our fresh block and yield that
898 new_block.stmts.push(loop_stmt);
906 // in general the pretty printer processes unexpanded code, so
907 // we override the default `visit_mac` method which panics.
908 fn visit_mac(&mut self, mac: &mut ast::Mac) {
909 noop_visit_mac(mac, self)