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_pos::edition::Edition;
35 #[cfg(not(parallel_compiler))]
36 use std::{thread, panic};
38 /// Adds `target_feature = "..."` cfgs for a variety of platform
39 /// specific features (SSE, NEON etc.).
41 /// This is performed by checking whether a whitelisted set of
42 /// features is available on the target machine, by querying LLVM.
43 pub fn add_configuration(
44 cfg: &mut ast::CrateConfig,
46 codegen_backend: &dyn CodegenBackend,
48 let tf = sym::target_feature;
52 .target_features(sess)
54 .map(|feat| (tf, Some(feat))),
57 if sess.crt_static_feature() {
58 cfg.insert((tf, Some(Symbol::intern("crt-static"))));
62 pub fn create_session(
63 sopts: config::Options,
64 cfg: FxHashSet<(String, Option<String>)>,
65 diagnostic_output: DiagnosticOutput,
66 file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
67 input_path: Option<PathBuf>,
68 lint_caps: FxHashMap<lint::LintId, lint::Level>,
69 descriptions: Registry,
70 ) -> (Lrc<Session>, Lrc<Box<dyn CodegenBackend>>, Lrc<SourceMap>) {
71 let loader = file_loader.unwrap_or(box RealFileLoader);
72 let source_map = Lrc::new(SourceMap::with_file_loader(
74 sopts.file_path_mapping(),
76 let mut sess = session::build_session_with_source_map(
85 sess.prof.register_queries(|profiler| {
86 rustc::ty::query::QueryName::register_with_profiler(&profiler);
89 let codegen_backend = get_codegen_backend(&sess);
91 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
92 add_configuration(&mut cfg, &sess, &*codegen_backend);
93 sess.parse_sess.config = cfg;
95 (Lrc::new(sess), Lrc::new(codegen_backend), source_map)
98 // Temporarily have stack size set to 32MB to deal with various crates with long method
99 // chains or deep syntax trees, except when on Haiku.
100 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
101 #[cfg(not(target_os = "haiku"))]
102 const STACK_SIZE: usize = 32 * 1024 * 1024;
104 #[cfg(target_os = "haiku")]
105 const STACK_SIZE: usize = 16 * 1024 * 1024;
107 fn get_stack_size() -> Option<usize> {
108 // FIXME: Hacks on hacks. If the env is trying to override the stack size
109 // then *don't* set it explicitly.
110 env::var_os("RUST_MIN_STACK").is_none().then_some(STACK_SIZE)
113 struct Sink(Arc<Mutex<Vec<u8>>>);
114 impl Write for Sink {
115 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
116 Write::write(&mut *self.0.lock().unwrap(), data)
118 fn flush(&mut self) -> io::Result<()> { Ok(()) }
121 #[cfg(not(parallel_compiler))]
122 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
124 unsafe impl Send for Ptr {}
125 unsafe impl Sync for Ptr {}
128 let run = Ptr(&mut f as *mut _ as *mut ());
129 let mut result = None;
130 let result_ptr = Ptr(&mut result as *mut _ as *mut ());
132 let thread = cfg.spawn(move || {
133 let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
134 let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
135 *result = Some(run());
138 match thread.unwrap().join() {
139 Ok(()) => result.unwrap(),
140 Err(p) => panic::resume_unwind(p),
144 #[cfg(not(parallel_compiler))]
145 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
148 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
151 let mut cfg = thread::Builder::new().name("rustc".to_string());
153 if let Some(size) = get_stack_size() {
154 cfg = cfg.stack_size(size);
157 scoped_thread(cfg, || {
158 syntax::with_globals(edition, || {
159 ty::tls::GCX_PTR.set(&Lock::new(0), || {
160 if let Some(stderr) = stderr {
161 io::set_panic(Some(box Sink(stderr.clone())));
163 ty::tls::with_thread_locals(|| f())
169 #[cfg(parallel_compiler)]
170 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
173 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
176 use rayon::{ThreadBuilder, ThreadPool, ThreadPoolBuilder};
178 let gcx_ptr = &Lock::new(0);
180 let mut config = ThreadPoolBuilder::new()
181 .thread_name(|_| "rustc".to_string())
182 .acquire_thread_handler(jobserver::acquire_thread)
183 .release_thread_handler(jobserver::release_thread)
184 .num_threads(threads)
185 .deadlock_handler(|| unsafe { ty::query::handle_deadlock() });
187 if let Some(size) = get_stack_size() {
188 config = config.stack_size(size);
191 let with_pool = move |pool: &ThreadPool| pool.install(move || f());
193 syntax::with_globals(edition, || {
194 syntax::GLOBALS.with(|syntax_globals| {
195 syntax_pos::GLOBALS.with(|syntax_pos_globals| {
196 // The main handler runs for each Rayon worker thread and sets up
197 // the thread local rustc uses. syntax_globals and syntax_pos_globals are
198 // captured and set on the new threads. ty::tls::with_thread_locals sets up
199 // thread local callbacks from libsyntax
200 let main_handler = move |thread: ThreadBuilder| {
201 syntax::GLOBALS.set(syntax_globals, || {
202 syntax_pos::GLOBALS.set(syntax_pos_globals, || {
203 if let Some(stderr) = stderr {
204 io::set_panic(Some(box Sink(stderr.clone())));
206 ty::tls::with_thread_locals(|| {
207 ty::tls::GCX_PTR.set(gcx_ptr, || thread.run())
213 config.build_scoped(main_handler, with_pool).unwrap()
219 fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
220 let lib = DynamicLibrary::open(Some(path)).unwrap_or_else(|err| {
221 let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
222 early_error(ErrorOutputType::default(), &err);
225 match lib.symbol("__rustc_codegen_backend") {
228 mem::transmute::<*mut u8, _>(f)
231 let err = format!("couldn't load codegen backend as it \
232 doesn't export the `__rustc_codegen_backend` \
234 early_error(ErrorOutputType::default(), &err);
240 pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> {
241 static INIT: Once = Once::new();
243 static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!();
246 let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref()
247 .unwrap_or(&sess.target.target.options.codegen_backend);
248 let backend = match &codegen_name[..] {
249 filename if filename.contains(".") => {
250 load_backend_from_dylib(filename.as_ref())
252 codegen_name => get_codegen_sysroot(codegen_name),
259 let backend = unsafe { LOAD() };
264 // This is used for rustdoc, but it uses similar machinery to codegen backend
265 // loading, so we leave the code here. It is potentially useful for other tools
266 // that want to invoke the rustc binary while linking to rustc as well.
267 pub fn rustc_path<'a>() -> Option<&'a Path> {
268 static RUSTC_PATH: once_cell::sync::OnceCell<Option<PathBuf>> =
269 once_cell::sync::OnceCell::new();
271 const BIN_PATH: &str = env!("RUSTC_INSTALL_BINDIR");
273 RUSTC_PATH.get_or_init(|| get_rustc_path_inner(BIN_PATH)).as_ref().map(|v| &**v)
276 fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
277 sysroot_candidates().iter()
278 .filter_map(|sysroot| {
279 let candidate = sysroot.join(bin_path).join(if cfg!(target_os = "windows") {
284 candidate.exists().then_some(candidate)
289 fn sysroot_candidates() -> Vec<PathBuf> {
290 let target = session::config::host_triple();
291 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
292 let path = current_dll_path().and_then(|s| s.canonicalize().ok());
293 if let Some(dll) = path {
294 // use `parent` twice to chop off the file name and then also the
295 // directory containing the dll which should be either `lib` or `bin`.
296 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
297 // The original `path` pointed at the `rustc_driver` crate's dll.
298 // Now that dll should only be in one of two locations. The first is
299 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
300 // other is the target's libdir, for example
301 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
303 // We don't know which, so let's assume that if our `path` above
304 // ends in `$target` we *could* be in the target libdir, and always
305 // assume that we may be in the main libdir.
306 sysroot_candidates.push(path.to_owned());
308 if path.ends_with(target) {
309 sysroot_candidates.extend(path.parent() // chop off `$target`
310 .and_then(|p| p.parent()) // chop off `rustlib`
311 .and_then(|p| p.parent()) // chop off `lib`
312 .map(|s| s.to_owned()));
317 return sysroot_candidates;
320 fn current_dll_path() -> Option<PathBuf> {
321 use std::ffi::{OsStr, CStr};
322 use std::os::unix::prelude::*;
325 let addr = current_dll_path as usize as *mut _;
326 let mut info = mem::zeroed();
327 if libc::dladdr(addr, &mut info) == 0 {
328 info!("dladdr failed");
331 if info.dli_fname.is_null() {
332 info!("dladdr returned null pointer");
335 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
336 let os = OsStr::from_bytes(bytes);
337 Some(PathBuf::from(os))
342 fn current_dll_path() -> Option<PathBuf> {
343 use std::ffi::OsString;
344 use std::os::windows::prelude::*;
347 fn GetModuleHandleExW(dwFlags: u32,
349 phModule: *mut usize) -> i32;
350 fn GetModuleFileNameW(hModule: usize,
351 lpFilename: *mut u16,
355 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
359 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
360 current_dll_path as usize,
363 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
366 let mut space = Vec::with_capacity(1024);
367 let r = GetModuleFileNameW(module,
369 space.capacity() as u32);
371 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
375 if r >= space.capacity() {
376 info!("our buffer was too small? {}",
377 io::Error::last_os_error());
381 let os = OsString::from_wide(&space);
382 Some(PathBuf::from(os))
387 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
388 // For now we only allow this function to be called once as it'll dlopen a
389 // few things, which seems to work best if we only do that once. In
390 // general this assertion never trips due to the once guard in `get_codegen_backend`,
391 // but there's a few manual calls to this function in this file we protect
393 static LOADED: AtomicBool = AtomicBool::new(false);
394 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
395 "cannot load the default codegen backend twice");
397 let target = session::config::host_triple();
398 let sysroot_candidates = sysroot_candidates();
400 let sysroot = sysroot_candidates.iter()
402 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
403 sysroot.join(libdir).with_file_name(
404 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
407 info!("codegen backend candidate: {}", f.display());
411 let sysroot = sysroot.unwrap_or_else(|| {
412 let candidates = sysroot_candidates.iter()
413 .map(|p| p.display().to_string())
416 let err = format!("failed to find a `codegen-backends` folder \
417 in the sysroot candidates:\n* {}", candidates);
418 early_error(ErrorOutputType::default(), &err);
420 info!("probing {} for a codegen backend", sysroot.display());
422 let d = sysroot.read_dir().unwrap_or_else(|e| {
423 let err = format!("failed to load default codegen backend, couldn't \
424 read `{}`: {}", sysroot.display(), e);
425 early_error(ErrorOutputType::default(), &err);
428 let mut file: Option<PathBuf> = None;
430 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
431 for entry in d.filter_map(|e| e.ok()) {
432 let path = entry.path();
433 let filename = match path.file_name().and_then(|s| s.to_str()) {
437 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
440 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
441 if name != expected_name {
444 if let Some(ref prev) = file {
445 let err = format!("duplicate codegen backends found\n\
448 ", prev.display(), path.display());
449 early_error(ErrorOutputType::default(), &err);
451 file = Some(path.clone());
455 Some(ref s) => return load_backend_from_dylib(s),
457 let err = format!("failed to load default codegen backend for `{}`, \
458 no appropriate codegen dylib found in `{}`",
459 backend_name, sysroot.display());
460 early_error(ErrorOutputType::default(), &err);
466 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
467 use std::hash::Hasher;
469 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
470 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
471 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
472 // should still be safe enough to avoid collisions in practice.
473 let mut hasher = StableHasher::new();
475 let mut metadata = session.opts.cg.metadata.clone();
476 // We don't want the crate_disambiguator to dependent on the order
477 // -C metadata arguments, so sort them:
479 // Every distinct -C metadata value is only incorporated once:
482 hasher.write(b"metadata");
484 // Also incorporate the length of a metadata string, so that we generate
485 // different values for `-Cmetadata=ab -Cmetadata=c` and
486 // `-Cmetadata=a -Cmetadata=bc`
487 hasher.write_usize(s.len());
488 hasher.write(s.as_bytes());
491 // Also incorporate crate type, so that we don't get symbol conflicts when
492 // linking against a library of the same name, if this is an executable.
496 .contains(&config::CrateType::Executable);
497 hasher.write(if is_exe { b"exe" } else { b"lib" });
499 CrateDisambiguator::from(hasher.finish::<Fingerprint>())
502 pub(crate) fn check_attr_crate_type(attrs: &[ast::Attribute], lint_buffer: &mut lint::LintBuffer) {
503 // Unconditionally collect crate types from attributes to make them used
504 for a in attrs.iter() {
505 if a.check_name(sym::crate_type) {
506 if let Some(n) = a.value_str() {
507 if let Some(_) = categorize_crate_type(n) {
511 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().kind {
512 let span = spanned.span;
513 let lev_candidate = find_best_match_for_name(
514 CRATE_TYPES.iter().map(|(k, _)| k),
518 if let Some(candidate) = lev_candidate {
519 lint_buffer.buffer_lint_with_diagnostic(
520 lint::builtin::UNKNOWN_CRATE_TYPES,
523 "invalid `crate_type` value",
524 lint::builtin::BuiltinLintDiagnostics::
527 "did you mean".to_string(),
528 format!("\"{}\"", candidate)
532 lint_buffer.buffer_lint(
533 lint::builtin::UNKNOWN_CRATE_TYPES,
536 "invalid `crate_type` value"
545 const CRATE_TYPES: &[(Symbol, config::CrateType)] = &[
546 (sym::rlib, config::CrateType::Rlib),
547 (sym::dylib, config::CrateType::Dylib),
548 (sym::cdylib, config::CrateType::Cdylib),
549 (sym::lib, config::default_lib_output()),
550 (sym::staticlib, config::CrateType::Staticlib),
551 (sym::proc_dash_macro, config::CrateType::ProcMacro),
552 (sym::bin, config::CrateType::Executable),
555 fn categorize_crate_type(s: Symbol) -> Option<config::CrateType> {
556 Some(CRATE_TYPES.iter().find(|(key, _)| *key == s)?.1)
559 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
560 // Unconditionally collect crate types from attributes to make them used
561 let attr_types: Vec<config::CrateType> = attrs
564 if a.check_name(sym::crate_type) {
565 match a.value_str() {
566 Some(s) => categorize_crate_type(s),
575 // If we're generating a test executable, then ignore all other output
576 // styles at all other locations
577 if session.opts.test {
578 return vec![config::CrateType::Executable];
581 // Only check command line flags if present. If no types are specified by
582 // command line, then reuse the empty `base` Vec to hold the types that
583 // will be found in crate attributes.
584 let mut base = session.opts.crate_types.clone();
586 base.extend(attr_types);
588 base.push(::rustc_codegen_utils::link::default_output_for_target(
597 base.retain(|crate_type| {
598 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
601 session.warn(&format!(
602 "dropping unsupported crate type `{}` for target `{}`",
603 *crate_type, session.opts.target_triple
613 pub fn build_output_filenames(
615 odir: &Option<PathBuf>,
616 ofile: &Option<PathBuf>,
617 attrs: &[ast::Attribute],
619 ) -> OutputFilenames {
622 // "-" as input file will cause the parser to read from stdin so we
623 // have to make up a name
624 // We want to toss everything after the final '.'
625 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
627 // If a crate name is present, we use it as the link name
631 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
632 .unwrap_or_else(|| input.filestem().to_owned());
635 out_directory: dirpath,
637 single_output_file: None,
638 extra: sess.opts.cg.extra_filename.clone(),
639 outputs: sess.opts.output_types.clone(),
643 Some(ref out_file) => {
644 let unnamed_output_types = sess.opts
647 .filter(|a| a.is_none())
649 let ofile = if unnamed_output_types > 1 {
651 "due to multiple output types requested, the explicitly specified \
652 output file name will be adapted for each output type",
656 if !sess.opts.cg.extra_filename.is_empty() {
657 sess.warn("ignoring -C extra-filename flag due to -o flag");
659 Some(out_file.clone())
662 sess.warn("ignoring --out-dir flag due to -o flag");
666 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
667 out_filestem: out_file
673 single_output_file: ofile,
674 extra: sess.opts.cg.extra_filename.clone(),
675 outputs: sess.opts.output_types.clone(),
681 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
683 // FIXME: Currently the `everybody_loops` transformation is not applied to:
684 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
685 // waiting for miri to fix that.
686 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
687 // Solving this may require `!` to implement every trait, which relies on the an even more
688 // ambitious form of the closed RFC #1637. See also [#34511].
690 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
691 pub struct ReplaceBodyWithLoop<'a, 'b> {
692 within_static_or_const: bool,
693 nested_blocks: Option<Vec<ast::Block>>,
694 resolver: &'a mut Resolver<'b>,
697 impl<'a, 'b> ReplaceBodyWithLoop<'a, 'b> {
698 pub fn new(resolver: &'a mut Resolver<'b>) -> ReplaceBodyWithLoop<'a, 'b> {
699 ReplaceBodyWithLoop {
700 within_static_or_const: false,
706 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
707 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
708 let old_blocks = self.nested_blocks.take();
709 let ret = action(self);
710 self.within_static_or_const = old_const;
711 self.nested_blocks = old_blocks;
715 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
716 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
717 fn involves_impl_trait(ty: &ast::Ty) -> bool {
719 ast::TyKind::ImplTrait(..) => true,
720 ast::TyKind::Slice(ref subty) |
721 ast::TyKind::Array(ref subty, _) |
722 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
723 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
724 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
725 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
726 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
727 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
729 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
730 let types = data.args.iter().filter_map(|arg| match arg {
731 ast::GenericArg::Type(ty) => Some(ty),
734 any_involves_impl_trait(types.into_iter()) ||
735 data.constraints.iter().any(|c| {
737 ast::AssocTyConstraintKind::Bound { .. } => true,
738 ast::AssocTyConstraintKind::Equality { ref ty } =>
739 involves_impl_trait(ty),
743 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
744 any_involves_impl_trait(data.inputs.iter()) ||
745 any_involves_impl_trait(data.output.iter())
753 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
754 it.any(|subty| involves_impl_trait(subty))
757 involves_impl_trait(ty)
763 fn is_sig_const(sig: &ast::FnSig) -> bool {
764 sig.header.constness.node == ast::Constness::Const ||
765 ReplaceBodyWithLoop::should_ignore_fn(&sig.decl)
769 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a, '_> {
770 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
771 let is_const = match i {
772 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
773 ast::ItemKind::Fn(ref sig, _, _) => Self::is_sig_const(sig),
776 self.run(is_const, |s| noop_visit_item_kind(i, s))
779 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
780 let is_const = match i.kind {
781 ast::TraitItemKind::Const(..) => true,
782 ast::TraitItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
785 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
788 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
789 let is_const = match i.kind {
790 ast::ImplItemKind::Const(..) => true,
791 ast::ImplItemKind::Method(ref sig, _) => Self::is_sig_const(sig),
794 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
797 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
798 self.run(true, |s| noop_visit_anon_const(c, s))
801 fn visit_block(&mut self, b: &mut P<ast::Block>) {
802 fn stmt_to_block(rules: ast::BlockCheckMode,
803 s: Option<ast::Stmt>,
804 resolver: &mut Resolver<'_>) -> ast::Block {
806 stmts: s.into_iter().collect(),
808 id: resolver.next_node_id(),
809 span: syntax_pos::DUMMY_SP,
813 fn block_to_stmt(b: ast::Block, resolver: &mut Resolver<'_>) -> ast::Stmt {
814 let expr = P(ast::Expr {
815 id: resolver.next_node_id(),
816 kind: ast::ExprKind::Block(P(b), None),
817 span: syntax_pos::DUMMY_SP,
818 attrs: ThinVec::new(),
822 id: resolver.next_node_id(),
823 kind: ast::StmtKind::Expr(expr),
824 span: syntax_pos::DUMMY_SP,
828 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.resolver);
829 let loop_expr = P(ast::Expr {
830 kind: ast::ExprKind::Loop(P(empty_block), None),
831 id: self.resolver.next_node_id(),
832 span: syntax_pos::DUMMY_SP,
833 attrs: ThinVec::new(),
836 let loop_stmt = ast::Stmt {
837 id: self.resolver.next_node_id(),
838 span: syntax_pos::DUMMY_SP,
839 kind: ast::StmtKind::Expr(loop_expr),
842 if self.within_static_or_const {
843 noop_visit_block(b, self)
845 visit_clobber(b.deref_mut(), |b| {
846 let mut stmts = vec![];
848 let old_blocks = self.nested_blocks.replace(vec![]);
850 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
852 // we put a Some in there earlier with that replace(), so this is valid
853 let new_blocks = self.nested_blocks.take().unwrap();
854 self.nested_blocks = old_blocks;
855 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, self.resolver)));
858 let mut new_block = ast::Block {
863 if let Some(old_blocks) = self.nested_blocks.as_mut() {
864 //push our fresh block onto the cache and yield an empty block with `loop {}`
865 if !new_block.stmts.is_empty() {
866 old_blocks.push(new_block);
869 stmt_to_block(b.rules, Some(loop_stmt), &mut self.resolver)
871 //push `loop {}` onto the end of our fresh block and yield that
872 new_block.stmts.push(loop_stmt);
880 // in general the pretty printer processes unexpanded code, so
881 // we override the default `visit_mac` method which panics.
882 fn visit_mac(&mut self, mac: &mut ast::Mac) {
883 noop_visit_mac(mac, self)