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;
17 use rustc_resolve::{self, Resolver};
19 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
20 use std::io::{self, Write};
22 use std::path::{Path, PathBuf};
23 use std::sync::atomic::{AtomicBool, Ordering};
24 use std::sync::{Arc, Mutex, Once};
25 use std::ops::DerefMut;
26 use smallvec::SmallVec;
28 use syntax::mut_visit::{*, MutVisitor, visit_clobber};
29 use syntax::ast::BlockCheckMode;
30 use syntax::util::lev_distance::find_best_match_for_name;
31 use syntax::source_map::{FileLoader, RealFileLoader, SourceMap};
32 use syntax::symbol::{Symbol, sym};
33 use syntax::{self, ast, attr};
34 use syntax_expand::config::process_configure_mod;
35 use syntax_pos::edition::Edition;
36 #[cfg(not(parallel_compiler))]
37 use std::{thread, panic};
39 /// Adds `target_feature = "..."` cfgs for a variety of platform
40 /// specific features (SSE, NEON etc.).
42 /// This is performed by checking whether a whitelisted set of
43 /// features is available on the target machine, by querying LLVM.
44 pub fn add_configuration(
45 cfg: &mut ast::CrateConfig,
47 codegen_backend: &dyn CodegenBackend,
49 let tf = sym::target_feature;
53 .target_features(sess)
55 .map(|feat| (tf, Some(feat))),
58 if sess.crt_static_feature() {
59 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
63 pub fn create_session(
64 sopts: config::Options,
65 cfg: FxHashSet<(String, Option<String>)>,
66 diagnostic_output: DiagnosticOutput,
67 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
68 input_path: Option<PathBuf>,
69 lint_caps: FxHashMap<lint::LintId, lint::Level>,
70 descriptions: Registry,
71 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>, Lrc<SourceMap>) {
72 let loader = file_loader.unwrap_or(box RealFileLoader);
73 let source_map = Lrc::new(SourceMap::with_file_loader(
75 sopts.file_path_mapping(),
77 let mut sess = session::build_session_with_source_map(
84 process_configure_mod,
87 sess.prof.register_queries(|profiler| {
88 rustc::ty::query::QueryName::register_with_profiler(&profiler);
91 let codegen_backend = get_codegen_backend(&sess);
93 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
94 add_configuration(&mut cfg, &sess, &*codegen_backend);
95 sess.parse_sess.config = cfg;
97 (Lrc::new(sess), Lrc::new(codegen_backend), source_map)
100 // Temporarily have stack size set to 32MB to deal with various crates with long method
101 // chains or deep syntax trees, except when on Haiku.
102 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
103 #[cfg(not(target_os = "haiku"))]
104 const STACK_SIZE: usize = 32 * 1024 * 1024;
106 #[cfg(target_os = "haiku")]
107 const STACK_SIZE: usize = 16 * 1024 * 1024;
109 fn get_stack_size() -> Option<usize> {
110 // FIXME: Hacks on hacks. If the env is trying to override the stack size
111 // then *don't* set it explicitly.
112 if env::var_os("RUST_MIN_STACK").is_none() {
119 struct Sink(Arc<Mutex<Vec<u8>>>);
120 impl Write for Sink {
121 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
122 Write::write(&mut *self.0.lock().unwrap(), data)
124 fn flush(&mut self) -> io::Result<()> { Ok(()) }
127 #[cfg(not(parallel_compiler))]
128 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
130 unsafe impl Send for Ptr {}
131 unsafe impl Sync for Ptr {}
134 let run = Ptr(&mut f as *mut _ as *mut ());
135 let mut result = None;
136 let result_ptr = Ptr(&mut result as *mut _ as *mut ());
138 let thread = cfg.spawn(move || {
139 let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
140 let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
141 *result = Some(run());
144 match thread.unwrap().join() {
145 Ok(()) => result.unwrap(),
146 Err(p) => panic::resume_unwind(p),
150 #[cfg(not(parallel_compiler))]
151 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
154 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
157 let mut cfg = thread::Builder::new().name("rustc".to_string());
159 if let Some(size) = get_stack_size() {
160 cfg = cfg.stack_size(size);
163 scoped_thread(cfg, || {
164 syntax::with_globals(edition, || {
165 ty::tls::GCX_PTR.set(&Lock::new(0), || {
166 if let Some(stderr) = stderr {
167 io::set_panic(Some(box Sink(stderr.clone())));
169 ty::tls::with_thread_locals(|| f())
175 #[cfg(parallel_compiler)]
176 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
179 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
182 use rayon::{ThreadBuilder, ThreadPool, ThreadPoolBuilder};
184 let gcx_ptr = &Lock::new(0);
186 let mut config = ThreadPoolBuilder::new()
187 .thread_name(|_| "rustc".to_string())
188 .acquire_thread_handler(jobserver::acquire_thread)
189 .release_thread_handler(jobserver::release_thread)
190 .num_threads(threads)
191 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
193 if let Some(size) = get_stack_size() {
194 config = config.stack_size(size);
197 let with_pool = move |pool: &ThreadPool| pool.install(move || f());
199 syntax::with_globals(edition, || {
200 syntax::GLOBALS.with(|syntax_globals| {
201 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
202 // The main handler runs for each Rayon worker thread and sets up
203 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
204 // captured and set on the new threads. ty::tls::with_thread_locals sets up
205 // thread local callbacks from libsyntax
206 let main_handler = move |thread: ThreadBuilder| {
207 syntax::GLOBALS.set(syntax_globals, || {
208 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
209 if let Some(stderr) = stderr {
210 io::set_panic(Some(box Sink(stderr.clone())));
212 ty::tls::with_thread_locals(|| {
213 ty::tls::GCX_PTR.set(gcx_ptr, || thread.run())
219 config.build_scoped(main_handler, with_pool).unwrap()
225 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
226 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
227 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
228 early_error(ErrorOutputType::default(), &err);
231 match lib.symbol("__rustc_codegen_backend") {
234 mem::transmute::<*mut u8, _>(f)
237 let err = format!("couldn't load codegen backend as it \
238 doesn't export the `__rustc_codegen_backend` \
240 early_error(ErrorOutputType::default(), &err);
246 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
247 static INIT: Once = Once::new();
249 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
252 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
253 .unwrap_or(&sess.target.target.options.codegen_backend);
254 let backend = match &codegen_name[..] {
255 filename if filename.contains(".") => {
256 load_backend_from_dylib(filename.as_ref())
258 codegen_name => get_codegen_sysroot(codegen_name),
265 let backend = unsafe { LOAD() };
270 // This is used for rustdoc, but it uses similar machinery to codegen backend
271 // loading, so we leave the code here. It is potentially useful for other tools
272 // that want to invoke the rustc binary while linking to rustc as well.
273 pub fn rustc_path<'a>() -> Option<&'a Path> {
274 static RUSTC_PATH: once_cell::sync::OnceCell<Option<PathBuf>> =
275 once_cell::sync::OnceCell::new();
277 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
279 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
282 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
283 sysroot_candidates().iter()
284 .filter_map(|sysroot| {
285 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
290 if candidate.exists() {
299 fn sysroot_candidates() -> Vec<PathBuf> {
300 let target = session::config::host_triple();
301 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
302 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
303 if let Some(dll) = path {
304 // use `parent` twice to chop off the file name and then also the
305 // directory containing the dll which should be either `lib` or `bin`.
306 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
307 // The original `path` pointed at the `rustc_driver` crate's dll.
308 // Now that dll should only be in one of two locations. The first is
309 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
310 // other is the target's libdir, for example
311 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
313 // We don't know which, so let's assume that if our `path` above
314 // ends in `$target` we *could* be in the target libdir, and always
315 // assume that we may be in the main libdir.
316 sysroot_candidates.push(path.to_owned());
318 if path.ends_with(target) {
319 sysroot_candidates.extend(path.parent() // chop off `$target`
320 .and_then(|p| p.parent()) // chop off `rustlib`
321 .and_then(|p| p.parent()) // chop off `lib`
322 .map(|s| s.to_owned()));
327 return sysroot_candidates;
330 fn current_dll_path() -> Option<PathBuf> {
331 use std::ffi::{OsStr, CStr};
332 use std::os::unix::prelude::*;
335 let addr = current_dll_path as usize as *mut _;
336 let mut info = mem::zeroed();
337 if libc::dladdr(addr, &mut info) == 0 {
338 info!("dladdr failed");
341 if info.dli_fname.is_null() {
342 info!("dladdr returned null pointer");
345 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
346 let os = OsStr::from_bytes(bytes);
347 Some(PathBuf::from(os))
352 fn current_dll_path() -> Option<PathBuf> {
353 use std::ffi::OsString;
354 use std::os::windows::prelude::*;
357 fn GetModuleHandleExW(dwFlags: u32,
359 phModule: *mut usize) -> i32;
360 fn GetModuleFileNameW(hModule: usize,
361 lpFilename: *mut u16,
365 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
369 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
370 current_dll_path as usize,
373 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
376 let mut space = Vec::with_capacity(1024);
377 let r = GetModuleFileNameW(module,
379 space.capacity() as u32);
381 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
385 if r >= space.capacity() {
386 info!("our buffer was too small? {}",
387 io::Error::last_os_error());
391 let os = OsString::from_wide(&space);
392 Some(PathBuf::from(os))
397 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
398 // For now we only allow this function to be called once as it'll dlopen a
399 // few things, which seems to work best if we only do that once. In
400 // general this assertion never trips due to the once guard in `get_codegen_backend`,
401 // but there's a few manual calls to this function in this file we protect
403 static LOADED: AtomicBool = AtomicBool::new(false);
404 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
405 "cannot load the default codegen backend twice");
407 let target = session::config::host_triple();
408 let sysroot_candidates = sysroot_candidates();
410 let sysroot = sysroot_candidates.iter()
412 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
413 sysroot.join(libdir).with_file_name(
414 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
417 info!("codegen backend candidate: {}", f.display());
421 let sysroot = sysroot.unwrap_or_else(|| {
422 let candidates = sysroot_candidates.iter()
423 .map(|p| p.display().to_string())
426 let err = format!("failed to find a `codegen-backends` folder \
427 in the sysroot candidates:\n* {}", candidates);
428 early_error(ErrorOutputType::default(), &err);
430 info!("probing {} for a codegen backend", sysroot.display());
432 let d = sysroot.read_dir().unwrap_or_else(|e| {
433 let err = format!("failed to load default codegen backend, couldn't \
434 read `{}`: {}", sysroot.display(), e);
435 early_error(ErrorOutputType::default(), &err);
438 let mut file: Option<PathBuf> = None;
440 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
441 for entry in d.filter_map(|e| e.ok()) {
442 let path = entry.path();
443 let filename = match path.file_name().and_then(|s| s.to_str()) {
447 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
450 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
451 if name != expected_name {
454 if let Some(ref prev) = file {
455 let err = format!("duplicate codegen backends found\n\
458 ", prev.display(), path.display());
459 early_error(ErrorOutputType::default(), &err);
461 file = Some(path.clone());
465 Some(ref s) => return load_backend_from_dylib(s),
467 let err = format!("failed to load default codegen backend for `{}`, \
468 no appropriate codegen dylib found in `{}`",
469 backend_name, sysroot.display());
470 early_error(ErrorOutputType::default(), &err);
476 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
477 use std::hash::Hasher;
479 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
480 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
481 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
482 // should still be safe enough to avoid collisions in practice.
483 let mut hasher = StableHasher::new();
485 let mut metadata = session.opts.cg.metadata.clone();
486 // We don't want the crate_disambiguator to dependent on the order
487 // -C metadata arguments, so sort them:
489 // Every distinct -C metadata value is only incorporated once:
492 hasher.write(b"metadata");
494 // Also incorporate the length of a metadata string, so that we generate
495 // different values for `-Cmetadata=ab -Cmetadata=c` and
496 // `-Cmetadata=a -Cmetadata=bc`
497 hasher.write_usize(s.len());
498 hasher.write(s.as_bytes());
501 // Also incorporate crate type, so that we don't get symbol conflicts when
502 // linking against a library of the same name, if this is an executable.
506 .contains(&config::CrateType::Executable);
507 hasher.write(if is_exe { b"exe" } else { b"lib" });
509 CrateDisambiguator::from(hasher.finish::<Fingerprint>())
512 pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut lint::LintBuffer) {
513 // Unconditionally collect crate types from attributes to make them used
514 for a in attrs.iter() {
515 if a.check_name(sym::crate_type) {
516 if let Some(n) = a.value_str() {
517 if let Some(_) = categorize_crate_type(n) {
521 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
522 let span = spanned.span;
523 let lev_candidate = find_best_match_for_name(
524 CRATE_TYPES.iter().map(|(k, _)| k),
528 if let Some(candidate) = lev_candidate {
529 lint_buffer.buffer_lint_with_diagnostic(
530 lint::builtin::UNKNOWN_CRATE_TYPES,
533 "invalid `crate_type` value",
534 lint::builtin::BuiltinLintDiagnostics::
537 "did you mean".to_string(),
538 format!("\"{}\"", candidate)
542 lint_buffer.buffer_lint(
543 lint::builtin::UNKNOWN_CRATE_TYPES,
546 "invalid `crate_type` value"
555 const CRATE_TYPES: &[(Symbol, config::CrateType)] = &[
556 (sym::rlib, config::CrateType::Rlib),
557 (sym::dylib, config::CrateType::Dylib),
558 (sym::cdylib, config::CrateType::Cdylib),
559 (sym::lib, config::default_lib_output()),
560 (sym::staticlib, config::CrateType::Staticlib),
561 (sym::proc_dash_macro, config::CrateType::ProcMacro),
562 (sym::bin, config::CrateType::Executable),
565 fn categorize_crate_type(s: Symbol) -> Option<config::CrateType> {
566 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
569 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
570 // Unconditionally collect crate types from attributes to make them used
571 let attr_types: Vec<config::CrateType> = attrs
574 if a.check_name(sym::crate_type) {
575 match a.value_str() {
576 Some(s) => categorize_crate_type(s),
585 // If we're generating a test executable, then ignore all other output
586 // styles at all other locations
587 if session.opts.test {
588 return vec![config::CrateType::Executable];
591 // Only check command line flags if present. If no types are specified by
592 // command line, then reuse the empty `base` Vec to hold the types that
593 // will be found in crate attributes.
594 let mut base = session.opts.crate_types.clone();
596 base.extend(attr_types);
598 base.push(::rustc_codegen_utils::link::default_output_for_target(
607 base.retain(|crate_type| {
608 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
611 session.warn(&format!(
612 "dropping unsupported crate type `{}` for target `{}`",
613 *crate_type, session.opts.target_triple
623 pub fn build_output_filenames(
625 odir: &Option<PathBuf>,
626 ofile: &Option<PathBuf>,
627 attrs: &[ast::Attribute],
629 ) -> OutputFilenames {
632 // "-" as input file will cause the parser to read from stdin so we
633 // have to make up a name
634 // We want to toss everything after the final '.'
635 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
637 // If a crate name is present, we use it as the link name
641 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
642 .unwrap_or_else(|| input.filestem().to_owned());
645 out_directory: dirpath,
647 single_output_file: None,
648 extra: sess.opts.cg.extra_filename.clone(),
649 outputs: sess.opts.output_types.clone(),
653 Some(ref out_file) => {
654 let unnamed_output_types = sess.opts
657 .filter(|a| a.is_none())
659 let ofile = if unnamed_output_types > 1 {
661 "due to multiple output types requested, the explicitly specified \
662 output file name will be adapted for each output type",
666 if !sess.opts.cg.extra_filename.is_empty() {
667 sess.warn("ignoring -C extra-filename flag due to -o flag");
669 Some(out_file.clone())
672 sess.warn("ignoring --out-dir flag due to -o flag");
676 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
677 out_filestem: out_file
683 single_output_file: ofile,
684 extra: sess.opts.cg.extra_filename.clone(),
685 outputs: sess.opts.output_types.clone(),
691 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
693 // FIXME: Currently the `everybody_loops` transformation is not applied to:
694 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
695 // waiting for miri to fix that.
696 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
697 // Solving this may require `!` to implement every trait, which relies on the an even more
698 // ambitious form of the closed RFC #1637. See also [#34511].
700 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
701 pub struct ReplaceBodyWithLoop<'a, 'b> {
702 within_static_or_const: bool,
703 nested_blocks: Option<Vec<ast::Block>>,
704 resolver: &'a mut Resolver<'b>,
707 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
708 pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
709 ReplaceBodyWithLoop {
710 within_static_or_const: false,
716 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
717 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
718 let old_blocks = self.nested_blocks.take();
719 let ret = action(self);
720 self.within_static_or_const = old_const;
721 self.nested_blocks = old_blocks;
725 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
726 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
727 fn involves_impl_trait(ty: &ast::Ty) -> bool {
729 ast::TyKind::ImplTrait(..) => true,
730 ast::TyKind::Slice(ref subty) |
731 ast::TyKind::Array(ref subty, _) |
732 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
733 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
734 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
735 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
736 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
737 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
739 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
740 let types = data.args.iter().filter_map(|arg| match arg {
741 ast::GenericArg::Type(ty) => Some(ty),
744 any_involves_impl_trait(types.into_iter()) ||
745 data.constraints.iter().any(|c| {
747 ast::AssocTyConstraintKind::Bound { .. } => true,
748 ast::AssocTyConstraintKind::Equality { ref ty } =>
749 involves_impl_trait(ty),
753 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
754 any_involves_impl_trait(data.inputs.iter()) ||
755 any_involves_impl_trait(data.output.iter())
763 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
764 it.any(|subty| involves_impl_trait(subty))
767 involves_impl_trait(ty)
773 fn is_sig_const(sig: &ast::FnSig) -> bool {
774 sig.header.constness.node == ast::Constness::Const ||
775 ReplaceBodyWithLoop::should_ignore_fn(&sig.decl)
779 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
780 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
781 let is_const = match i {
782 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
783 ast::ItemKind::Fn(ref sig, _, _) => Self::is_sig_const(sig),
786 self.run(is_const, |s| noop_visit_item_kind(i, s))
789 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
790 let is_const = match i.kind {
791 ast::TraitItemKind::Const(..) => true,
792 ast::TraitItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
795 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
798 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
799 let is_const = match i.kind {
800 ast::ImplItemKind::Const(..) => true,
801 ast::ImplItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
804 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
807 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
808 self.run(true, |s| noop_visit_anon_const(c, s))
811 fn visit_block(&mut self, b: &mut P<ast::Block>) {
812 fn stmt_to_block(rules: ast::BlockCheckMode,
813 s: Option<ast::Stmt>,
814 resolver: &mut Resolver<'_>) -> ast::Block {
816 stmts: s.into_iter().collect(),
818 id: resolver.next_node_id(),
819 span: syntax_pos::DUMMY_SP,
823 fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
824 let expr = P(ast::Expr {
825 id: resolver.next_node_id(),
826 kind: ast::ExprKind::Block(P(b), None),
827 span: syntax_pos::DUMMY_SP,
828 attrs: ThinVec::new(),
832 id: resolver.next_node_id(),
833 kind: ast::StmtKind::Expr(expr),
834 span: syntax_pos::DUMMY_SP,
838 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
839 let loop_expr = P(ast::Expr {
840 kind: ast::ExprKind::Loop(P(empty_block), None),
841 id: self.resolver.next_node_id(),
842 span: syntax_pos::DUMMY_SP,
843 attrs: ThinVec::new(),
846 let loop_stmt = ast::Stmt {
847 id: self.resolver.next_node_id(),
848 span: syntax_pos::DUMMY_SP,
849 kind: ast::StmtKind::Expr(loop_expr),
852 if self.within_static_or_const {
853 noop_visit_block(b, self)
855 visit_clobber(b.deref_mut(), |b| {
856 let mut stmts = vec![];
858 let old_blocks = self.nested_blocks.replace(vec![]);
860 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
862 // we put a Some in there earlier with that replace(), so this is valid
863 let new_blocks = self.nested_blocks.take().unwrap();
864 self.nested_blocks = old_blocks;
865 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
868 let mut new_block = ast::Block {
873 if let Some(old_blocks) = self.nested_blocks.as_mut() {
874 //push our fresh block onto the cache and yield an empty block with `loop {}`
875 if !new_block.stmts.is_empty() {
876 old_blocks.push(new_block);
879 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
881 //push `loop {}` onto the end of our fresh block and yield that
882 new_block.stmts.push(loop_stmt);
890 // in general the pretty printer processes unexpanded code, so
891 // we override the default `visit_mac` method which panics.
892 fn visit_mac(&mut self, mac: &mut ast::Mac) {
893 noop_visit_mac(mac, self)