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 #[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::DIAGNOSTICS);
46 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
47 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
48 all_errors.extend_from_slice(&rustc_privacy::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::DIAGNOSTICS);
52 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
53 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
54 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
55 all_errors.extend_from_slice(&syntax::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 = Symbol::intern("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 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
111 if sess.unstable_options() {
112 rustc_lint::register_internals(&mut sess.lint_store.borrow_mut(), Some(&sess));
115 let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
116 add_configuration(&mut cfg, &sess, &*codegen_backend);
117 sess.parse_sess.config = cfg;
119 (Lrc::new(sess), Lrc::new(codegen_backend), source_map)
122 // Temporarily have stack size set to 32MB to deal with various crates with long method
123 // chains or deep syntax trees.
124 // FIXME(oli-obk): get https://github.com/rust-lang/rust/pull/55617 the finish line
125 const STACK_SIZE: usize = 32 * 1024 * 1024; // 32MB
127 fn get_stack_size() -> Option<usize> {
128 // FIXME: Hacks on hacks. If the env is trying to override the stack size
129 // then *don't* set it explicitly.
130 if env::var_os("RUST_MIN_STACK").is_none() {
137 struct Sink(Arc<Mutex<Vec<u8>>>);
138 impl Write for Sink {
139 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
140 Write::write(&mut *self.0.lock().unwrap(), data)
142 fn flush(&mut self) -> io::Result<()> { Ok(()) }
145 #[cfg(not(parallel_compiler))]
146 pub fn scoped_thread<F: FnOnce() -> R + Send, R: Send>(cfg: thread::Builder, f: F) -> R {
148 unsafe impl Send for Ptr {}
149 unsafe impl Sync for Ptr {}
152 let run = Ptr(&mut f as *mut _ as *mut ());
153 let mut result = None;
154 let result_ptr = Ptr(&mut result as *mut _ as *mut ());
156 let thread = cfg.spawn(move || {
157 let run = unsafe { (*(run.0 as *mut Option<F>)).take().unwrap() };
158 let result = unsafe { &mut *(result_ptr.0 as *mut Option<R>) };
159 *result = Some(run());
162 match thread.unwrap().join() {
163 Ok(()) => result.unwrap(),
164 Err(p) => panic::resume_unwind(p),
168 #[cfg(not(parallel_compiler))]
169 pub fn spawn_thread_pool<F: FnOnce() -> R + Send, R: Send>(
170 _threads: Option<usize>,
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( || {
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>(
194 threads: Option<usize>,
195 stderr: &Option<Arc<Mutex<Vec<u8>>>>,
198 use rayon::{ThreadPool, ThreadPoolBuilder};
202 let gcx_ptr = &Lock::new(0);
204 let mut config = ThreadPoolBuilder::new()
205 .acquire_thread_handler(jobserver::acquire_thread)
206 .release_thread_handler(jobserver::release_thread)
207 .num_threads(Session::threads_from_count(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(|| {
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 |worker: &mut dyn FnMut()| {
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, || worker())
236 ThreadPool::scoped_pool(config, 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 pub fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
288 // For now we only allow this function to be called once as it'll dlopen a
289 // few things, which seems to work best if we only do that once. In
290 // general this assertion never trips due to the once guard in `get_codegen_backend`,
291 // but there's a few manual calls to this function in this file we protect
293 static LOADED: AtomicBool = AtomicBool::new(false);
294 assert!(!LOADED.fetch_or(true, Ordering::SeqCst),
295 "cannot load the default codegen backend twice");
297 let target = session::config::host_triple();
298 let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()];
299 let path = current_dll_path()
300 .and_then(|s| s.canonicalize().ok());
301 if let Some(dll) = path {
302 // use `parent` twice to chop off the file name and then also the
303 // directory containing the dll which should be either `lib` or `bin`.
304 if let Some(path) = dll.parent().and_then(|p| p.parent()) {
305 // The original `path` pointed at the `rustc_driver` crate's dll.
306 // Now that dll should only be in one of two locations. The first is
307 // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The
308 // other is the target's libdir, for example
309 // `$sysroot/lib/rustlib/$target/lib/*.dll`.
311 // We don't know which, so let's assume that if our `path` above
312 // ends in `$target` we *could* be in the target libdir, and always
313 // assume that we may be in the main libdir.
314 sysroot_candidates.push(path.to_owned());
316 if path.ends_with(target) {
317 sysroot_candidates.extend(path.parent() // chop off `$target`
318 .and_then(|p| p.parent()) // chop off `rustlib`
319 .and_then(|p| p.parent()) // chop off `lib`
320 .map(|s| s.to_owned()));
325 let sysroot = sysroot_candidates.iter()
327 let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
328 sysroot.join(libdir).with_file_name(
329 option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
332 info!("codegen backend candidate: {}", f.display());
336 let sysroot = sysroot.unwrap_or_else(|| {
337 let candidates = sysroot_candidates.iter()
338 .map(|p| p.display().to_string())
341 let err = format!("failed to find a `codegen-backends` folder \
342 in the sysroot candidates:\n* {}", candidates);
343 early_error(ErrorOutputType::default(), &err);
345 info!("probing {} for a codegen backend", sysroot.display());
347 let d = sysroot.read_dir().unwrap_or_else(|e| {
348 let err = format!("failed to load default codegen backend, couldn't \
349 read `{}`: {}", sysroot.display(), e);
350 early_error(ErrorOutputType::default(), &err);
353 let mut file: Option<PathBuf> = None;
355 let expected_name = format!("rustc_codegen_llvm-{}", backend_name);
356 for entry in d.filter_map(|e| e.ok()) {
357 let path = entry.path();
358 let filename = match path.file_name().and_then(|s| s.to_str()) {
362 if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) {
365 let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()];
366 if name != expected_name {
369 if let Some(ref prev) = file {
370 let err = format!("duplicate codegen backends found\n\
373 ", prev.display(), path.display());
374 early_error(ErrorOutputType::default(), &err);
376 file = Some(path.clone());
380 Some(ref s) => return load_backend_from_dylib(s),
382 let err = format!("failed to load default codegen backend for `{}`, \
383 no appropriate codegen dylib found in `{}`",
384 backend_name, sysroot.display());
385 early_error(ErrorOutputType::default(), &err);
390 fn current_dll_path() -> Option<PathBuf> {
391 use std::ffi::{OsStr, CStr};
392 use std::os::unix::prelude::*;
395 let addr = current_dll_path as usize as *mut _;
396 let mut info = mem::zeroed();
397 if libc::dladdr(addr, &mut info) == 0 {
398 info!("dladdr failed");
401 if info.dli_fname.is_null() {
402 info!("dladdr returned null pointer");
405 let bytes = CStr::from_ptr(info.dli_fname).to_bytes();
406 let os = OsStr::from_bytes(bytes);
407 Some(PathBuf::from(os))
412 fn current_dll_path() -> Option<PathBuf> {
413 use std::ffi::OsString;
414 use std::os::windows::prelude::*;
417 fn GetModuleHandleExW(dwFlags: u32,
419 phModule: *mut usize) -> i32;
420 fn GetModuleFileNameW(hModule: usize,
421 lpFilename: *mut u16,
425 const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
429 let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
430 current_dll_path as usize,
433 info!("GetModuleHandleExW failed: {}", io::Error::last_os_error());
436 let mut space = Vec::with_capacity(1024);
437 let r = GetModuleFileNameW(module,
439 space.capacity() as u32);
441 info!("GetModuleFileNameW failed: {}", io::Error::last_os_error());
445 if r >= space.capacity() {
446 info!("our buffer was too small? {}",
447 io::Error::last_os_error());
451 let os = OsString::from_wide(&space);
452 Some(PathBuf::from(os))
457 pub(crate) fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
458 use std::hash::Hasher;
460 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
461 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
462 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
463 // should still be safe enough to avoid collisions in practice.
464 let mut hasher = StableHasher::<Fingerprint>::new();
466 let mut metadata = session.opts.cg.metadata.clone();
467 // We don't want the crate_disambiguator to dependent on the order
468 // -C metadata arguments, so sort them:
470 // Every distinct -C metadata value is only incorporated once:
473 hasher.write(b"metadata");
475 // Also incorporate the length of a metadata string, so that we generate
476 // different values for `-Cmetadata=ab -Cmetadata=c` and
477 // `-Cmetadata=a -Cmetadata=bc`
478 hasher.write_usize(s.len());
479 hasher.write(s.as_bytes());
482 // Also incorporate crate type, so that we don't get symbol conflicts when
483 // linking against a library of the same name, if this is an executable.
487 .contains(&config::CrateType::Executable);
488 hasher.write(if is_exe { b"exe" } else { b"lib" });
490 CrateDisambiguator::from(hasher.finish())
493 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
494 // Unconditionally collect crate types from attributes to make them used
495 let attr_types: Vec<config::CrateType> = attrs
498 if a.check_name(sym::crate_type) {
499 match a.value_str() {
500 Some(sym::rlib) => Some(config::CrateType::Rlib),
501 Some(sym::dylib) => Some(config::CrateType::Dylib),
502 Some(sym::cdylib) => Some(config::CrateType::Cdylib),
503 Some(sym::lib) => Some(config::default_lib_output()),
504 Some(sym::staticlib) => Some(config::CrateType::Staticlib),
505 Some(sym::proc_dash_macro) => Some(config::CrateType::ProcMacro),
506 Some(sym::bin) => Some(config::CrateType::Executable),
508 let crate_types = vec![
514 sym::proc_dash_macro,
518 if let ast::MetaItemKind::NameValue(spanned) = a.meta().unwrap().node {
519 let span = spanned.span;
520 let lev_candidate = find_best_match_for_name(
525 if let Some(candidate) = lev_candidate {
526 session.buffer_lint_with_diagnostic(
527 lint::builtin::UNKNOWN_CRATE_TYPES,
530 "invalid `crate_type` value",
531 lint::builtin::BuiltinLintDiagnostics::
534 "did you mean".to_string(),
535 format!("\"{}\"", candidate)
540 lint::builtin::UNKNOWN_CRATE_TYPES,
543 "invalid `crate_type` value"
557 // If we're generating a test executable, then ignore all other output
558 // styles at all other locations
559 if session.opts.test {
560 return vec![config::CrateType::Executable];
563 // Only check command line flags if present. If no types are specified by
564 // command line, then reuse the empty `base` Vec to hold the types that
565 // will be found in crate attributes.
566 let mut base = session.opts.crate_types.clone();
568 base.extend(attr_types);
570 base.push(::rustc_codegen_utils::link::default_output_for_target(
579 base.retain(|crate_type| {
580 let res = !::rustc_codegen_utils::link::invalid_output_for_target(session, *crate_type);
583 session.warn(&format!(
584 "dropping unsupported crate type `{}` for target `{}`",
585 *crate_type, session.opts.target_triple
595 pub fn build_output_filenames(
597 odir: &Option<PathBuf>,
598 ofile: &Option<PathBuf>,
599 attrs: &[ast::Attribute],
601 ) -> OutputFilenames {
604 // "-" as input file will cause the parser to read from stdin so we
605 // have to make up a name
606 // We want to toss everything after the final '.'
607 let dirpath = (*odir).as_ref().cloned().unwrap_or_default();
609 // If a crate name is present, we use it as the link name
613 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
614 .unwrap_or_else(|| input.filestem().to_owned());
617 out_directory: dirpath,
619 single_output_file: None,
620 extra: sess.opts.cg.extra_filename.clone(),
621 outputs: sess.opts.output_types.clone(),
625 Some(ref out_file) => {
626 let unnamed_output_types = sess.opts
629 .filter(|a| a.is_none())
631 let ofile = if unnamed_output_types > 1 {
633 "due to multiple output types requested, the explicitly specified \
634 output file name will be adapted for each output type",
638 Some(out_file.clone())
641 sess.warn("ignoring --out-dir flag due to -o flag");
643 if !sess.opts.cg.extra_filename.is_empty() {
644 sess.warn("ignoring -C extra-filename flag due to -o flag");
648 out_directory: out_file.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
649 out_filestem: out_file
655 single_output_file: ofile,
656 extra: sess.opts.cg.extra_filename.clone(),
657 outputs: sess.opts.output_types.clone(),
663 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
665 // FIXME: Currently the `everybody_loops` transformation is not applied to:
666 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
667 // waiting for miri to fix that.
668 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
669 // Solving this may require `!` to implement every trait, which relies on the an even more
670 // ambitious form of the closed RFC #1637. See also [#34511].
672 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
673 pub struct ReplaceBodyWithLoop<'a> {
674 within_static_or_const: bool,
675 nested_blocks: Option<Vec<ast::Block>>,
679 impl<'a> ReplaceBodyWithLoop<'a> {
680 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
681 ReplaceBodyWithLoop {
682 within_static_or_const: false,
688 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
689 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
690 let old_blocks = self.nested_blocks.take();
691 let ret = action(self);
692 self.within_static_or_const = old_const;
693 self.nested_blocks = old_blocks;
697 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
698 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
699 fn involves_impl_trait(ty: &ast::Ty) -> bool {
701 ast::TyKind::ImplTrait(..) => true,
702 ast::TyKind::Slice(ref subty) |
703 ast::TyKind::Array(ref subty, _) |
704 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
705 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
706 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
707 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
708 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
709 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
711 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
712 let types = data.args.iter().filter_map(|arg| match arg {
713 ast::GenericArg::Type(ty) => Some(ty),
716 any_involves_impl_trait(types.into_iter()) ||
717 any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty))
719 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
720 any_involves_impl_trait(data.inputs.iter()) ||
721 any_involves_impl_trait(data.output.iter())
729 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
730 it.any(|subty| involves_impl_trait(subty))
733 involves_impl_trait(ty)
740 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a> {
741 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
742 let is_const = match i {
743 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
744 ast::ItemKind::Fn(ref decl, ref header, _, _) =>
745 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
748 self.run(is_const, |s| noop_visit_item_kind(i, s))
751 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
752 let is_const = match i.node {
753 ast::TraitItemKind::Const(..) => true,
754 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
755 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
758 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
761 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
762 let is_const = match i.node {
763 ast::ImplItemKind::Const(..) => true,
764 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
765 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
768 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
771 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
772 self.run(true, |s| noop_visit_anon_const(c, s))
775 fn visit_block(&mut self, b: &mut P<ast::Block>) {
776 fn stmt_to_block(rules: ast::BlockCheckMode,
777 s: Option<ast::Stmt>,
778 sess: &Session) -> ast::Block {
780 stmts: s.into_iter().collect(),
782 id: sess.next_node_id(),
783 span: syntax_pos::DUMMY_SP,
787 fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
788 let expr = P(ast::Expr {
789 id: sess.next_node_id(),
790 node: ast::ExprKind::Block(P(b), None),
791 span: syntax_pos::DUMMY_SP,
792 attrs: ThinVec::new(),
796 id: sess.next_node_id(),
797 node: ast::StmtKind::Expr(expr),
798 span: syntax_pos::DUMMY_SP,
802 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
803 let loop_expr = P(ast::Expr {
804 node: ast::ExprKind::Loop(P(empty_block), None),
805 id: self.sess.next_node_id(),
806 span: syntax_pos::DUMMY_SP,
807 attrs: ThinVec::new(),
810 let loop_stmt = ast::Stmt {
811 id: self.sess.next_node_id(),
812 span: syntax_pos::DUMMY_SP,
813 node: ast::StmtKind::Expr(loop_expr),
816 if self.within_static_or_const {
817 noop_visit_block(b, self)
819 visit_clobber(b.deref_mut(), |b| {
820 let mut stmts = vec![];
822 let old_blocks = self.nested_blocks.replace(vec![]);
824 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
826 // we put a Some in there earlier with that replace(), so this is valid
827 let new_blocks = self.nested_blocks.take().unwrap();
828 self.nested_blocks = old_blocks;
829 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
832 let mut new_block = ast::Block {
837 if let Some(old_blocks) = self.nested_blocks.as_mut() {
838 //push our fresh block onto the cache and yield an empty block with `loop {}`
839 if !new_block.stmts.is_empty() {
840 old_blocks.push(new_block);
843 stmt_to_block(b.rules, Some(loop_stmt), self.sess)
845 //push `loop {}` onto the end of our fresh block and yield that
846 new_block.stmts.push(loop_stmt);
854 // in general the pretty printer processes unexpanded code, so
855 // we override the default `visit_mac` method which panics.
856 fn visit_mac(&mut self, mac: &mut ast::Mac) {
857 noop_visit_mac(mac, self)