Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/rustc_plugin/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rustc_plugin"
version = "0.12.0-nightly-2024-12-15"
version = "0.13.0-nightly-2025-03-03"
edition = "2021"
authors = ["Will Crichton <[email protected]>"]
description = "A framework for writing plugins that integrate with the Rust compiler"
Expand Down
2 changes: 1 addition & 1 deletion crates/rustc_plugin/examples/print-all-items/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ rustc_private = true

[dependencies]
rustc_plugin = { path = "../.." }
env_logger = "0.10"
env_logger = {version = "0.10", default-features = false}
clap = {version = "4.4", features = ["derive"]}
serde = {version = "1", features = ["derive"]}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2024-12-15"
channel = "nightly-2025-03-02"
components = ["rust-src", "rustc-dev", "llvm-tools-preview"]
36 changes: 25 additions & 11 deletions crates/rustc_plugin/examples/print-all-items/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
#![feature(rustc_private)]

extern crate rustc_driver;
extern crate rustc_hir;
extern crate rustc_interface;
extern crate rustc_middle;
extern crate rustc_session;

use std::{borrow::Cow, env, process::Command};

use clap::Parser;
use rustc_hir::{
intravisit::{self, Visitor},
Item,
};
use rustc_middle::ty::TyCtxt;
use rustc_plugin::{CrateFilter, RustcPlugin, RustcPluginArgs, Utf8Path};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -61,15 +66,16 @@ impl RustcPlugin for PrintAllItemsPlugin {
compiler_args: Vec<String>,
plugin_args: Self::Args,
) -> rustc_interface::interface::Result<()> {
let mut callbacks = PrintAllItemsCallbacks { args: plugin_args };
let compiler = rustc_driver::RunCompiler::new(&compiler_args, &mut callbacks);
compiler.run();
let mut callbacks = PrintAllItemsCallbacks {
args: Some(plugin_args),
};
rustc_driver::run_compiler(&compiler_args, &mut callbacks);
Ok(())
}
}

struct PrintAllItemsCallbacks {
args: PrintAllItemsPluginArgs,
args: Option<PrintAllItemsPluginArgs>,
}

impl rustc_driver::Callbacks for PrintAllItemsCallbacks {
Expand All @@ -82,7 +88,7 @@ impl rustc_driver::Callbacks for PrintAllItemsCallbacks {
tcx: TyCtxt<'_>,
) -> rustc_driver::Compilation {
// We call our top-level function with access to the type context `tcx` and the CLI arguments.
print_all_items(tcx, &self.args);
print_all_items(tcx, self.args.take().unwrap());

// Note that you should generally allow compilation to continue. If
// your plugin is being invoked on a dependency, then you need to ensure
Expand All @@ -92,21 +98,29 @@ impl rustc_driver::Callbacks for PrintAllItemsCallbacks {
}
}

// The core of our analysis. It doesn't do much, just access some methods on the `TyCtxt`.
// The core of our analysis. Right now it just prints out a description of each item.
// I recommend reading the Rustc Development Guide to better understand which compiler APIs
// are relevant to whatever task you have.
fn print_all_items(tcx: TyCtxt, args: &PrintAllItemsPluginArgs) {
let hir = tcx.hir();
for item_id in hir.items() {
let item = hir.item(item_id);
fn print_all_items(tcx: TyCtxt, args: PrintAllItemsPluginArgs) {
tcx.hir_visit_all_item_likes_in_crate(&mut PrintVisitor { args });
}

struct PrintVisitor {
args: PrintAllItemsPluginArgs,
}

impl Visitor<'_> for PrintVisitor {
fn visit_item(&mut self, item: &Item) -> Self::Result {
let mut msg = format!(
"There is an item \"{}\" of type \"{}\"",
item.ident,
item.kind.descr()
);
if args.allcaps {
if self.args.allcaps {
msg = msg.to_uppercase();
}
println!("{msg}");

intravisit::walk_item(self, item)
}
}
5 changes: 2 additions & 3 deletions crates/rustc_plugin/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ pub fn driver_main<T: RustcPlugin>(plugin: T) {
log::debug!("Running plugin...");
let plugin_args: T::Args =
serde_json::from_str(&env::var(PLUGIN_ARGS).unwrap()).unwrap();
plugin.run(args, plugin_args)
plugin.run(args, plugin_args).unwrap();
} else {
log::debug!(
"Running normal Rust. Relevant variables:\
Expand All @@ -161,8 +161,7 @@ run_on_all_crates={run_on_all_crates}, \
primary_package={primary_package}, \
is_target_crate={is_target_crate}"
);
rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
Ok(())
rustc_driver::run_compiler(&args, &mut DefaultCallbacks);
}
}))
}
4 changes: 2 additions & 2 deletions crates/rustc_utils/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rustc_utils"
version = "0.12.0-nightly-2024-12-15"
version = "0.13.0-nightly-2025-03-03"
edition = "2021"
authors = ["Will Crichton <[email protected]>"]
description = "Utilities for working with the Rust compiler"
Expand All @@ -27,7 +27,7 @@ serde = {version = "1", features = ["derive"], optional = true}
textwrap = {version = "0.16", optional = true}
regex = {version = "1", optional = true}
ts-rs = {version = "7", optional = true}
indexical = {version = "0.3.1", default-features = false, features = ["rustc"], optional = true}
indexical = {version = "0.7.0", default-features = false, features = ["rustc"], optional = true}

[dev-dependencies]
rustc_utils = {path = ".", features = ["test"]}
Expand Down
2 changes: 2 additions & 0 deletions crates/rustc_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
)]

extern crate either;
extern crate rustc_abi;
extern crate rustc_borrowck;
extern crate rustc_data_structures;
extern crate rustc_driver;
Expand All @@ -50,6 +51,7 @@ extern crate rustc_hir;
extern crate rustc_index;
extern crate rustc_infer;
extern crate rustc_interface;
extern crate rustc_lint_defs;
extern crate rustc_macros;
extern crate rustc_middle;
extern crate rustc_mir_dataflow;
Expand Down
2 changes: 1 addition & 1 deletion crates/rustc_utils/src/mir/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ impl<'tcx> BodyExt<'tcx> for Body<'tcx> {

fn source_info_to_hir_id(&self, info: &SourceInfo) -> HirId {
let scope = &self.source_scopes[info.scope];
let local_data = scope.local_data.as_ref().assert_crate_local();
let local_data = scope.local_data.as_ref().unwrap_crate_local();
local_data.lint_root
}

Expand Down
8 changes: 4 additions & 4 deletions crates/rustc_utils/src/mir/borrowck_facts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,17 +108,17 @@ fn mir_borrowck(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &BorrowCheckResult<'_> {
/// Note that as of May 2022, Polonius can be *very* slow for large functions.
/// It may take up to 30 seconds to analyze a single body with a large CFG.
#[allow(clippy::needless_lifetimes)]
pub fn get_body_with_borrowck_facts<'tcx>(
tcx: TyCtxt<'tcx>,
pub fn get_body_with_borrowck_facts(
tcx: TyCtxt<'_>,
def_id: LocalDefId,
) -> &'tcx BodyWithBorrowckFacts<'tcx> {
) -> &BodyWithBorrowckFacts<'_> {
let _ = tcx.mir_borrowck(def_id);
MIR_BODIES.with(|cache| {
let body = cache.get(&def_id, |_| panic!("mir_borrowck override should have stored body for item: {def_id:?}. Are you sure you registered borrowck_facts::override_queries?"));
unsafe {
std::mem::transmute::<
&BodyWithBorrowckFacts<'static>,
&'tcx BodyWithBorrowckFacts<'tcx>,
&BodyWithBorrowckFacts<'_>,
>(body)
}
})
Expand Down
8 changes: 4 additions & 4 deletions crates/rustc_utils/src/mir/control_dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ use rustc_data_structures::graph::{
DirectedGraph, Predecessors, StartNode, Successors,
};
use rustc_index::{
bit_set::{BitSet, SparseBitMatrix},
bit_set::{DenseBitSet, MixedBitSet, SparseBitMatrix},
Idx,
};
use smallvec::SmallVec;

struct ReversedGraph<'a, G: ControlFlowGraph> {
graph: &'a G,
exit: G::Node,
unreachable: BitSet<G::Node>,
unreachable: MixedBitSet<G::Node>,
}

impl<G: ControlFlowGraph> DirectedGraph for ReversedGraph<'_, G> {
Expand Down Expand Up @@ -76,7 +76,7 @@ impl<Node: Idx> PostDominators<Node> {
let mut reversed = ReversedGraph {
graph,
exit,
unreachable: BitSet::new_empty(num_nodes),
unreachable: MixedBitSet::new_empty(num_nodes),
};

let reachable = iterate::post_order_from(&reversed, exit);
Expand Down Expand Up @@ -194,7 +194,7 @@ impl<Node: Idx + Ord> ControlDependencies<Node> {
}

/// Returns the set of all node that are control-dependent on the given `node`.
pub fn dependent_on(&self, node: Node) -> Option<&BitSet<Node>> {
pub fn dependent_on(&self, node: Node) -> Option<&DenseBitSet<Node>> {
self.0.row(node)
}
}
Expand Down
13 changes: 3 additions & 10 deletions crates/rustc_utils/src/mir/location_or_arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,22 +42,15 @@ impl From<Local> for LocationOrArg {

#[cfg(feature = "indexical")]
pub mod index {
use indexical::{
impls::RustcIndexSet, index_vec::define_index_type, IndexedDomain, IndexedValue,
ToIndex,
};
use indexical::{bitset::rustc::IndexSet, define_index_type, IndexedDomain, ToIndex};

use super::*;

define_index_type! {
pub struct LocationOrArgIndex = u32;
pub struct LocationOrArgIndex for LocationOrArg = u32;
}

impl IndexedValue for LocationOrArg {
type Index = LocationOrArgIndex;
}

pub type LocationOrArgSet = RustcIndexSet<LocationOrArg>;
pub type LocationOrArgSet = IndexSet<LocationOrArg>;
pub type LocationOrArgDomain = IndexedDomain<LocationOrArg>;

pub struct CustomMarker;
Expand Down
8 changes: 4 additions & 4 deletions crates/rustc_utils/src/mir/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::{borrow::Cow, collections::VecDeque};

use log::{trace, warn};
use rustc_abi::{FieldIdx, VariantIdx};
use rustc_data_structures::fx::{FxHashMap as HashMap, FxHashSet as HashSet};
use rustc_hir::def_id::DefId;
use rustc_infer::infer::TyCtxtInferExt;
Expand All @@ -15,7 +16,6 @@ use rustc_middle::{
traits::ObligationCause,
ty::{self, AdtKind, Region, RegionKind, RegionVid, Ty, TyCtxt, TyKind, TypeVisitor},
};
use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_trait_selection::traits::NormalizeExt;
use rustc_type_ir::TypingMode;

Expand Down Expand Up @@ -452,7 +452,7 @@ impl<'tcx, Dispatcher: RegionVisitorDispatcher<'tcx>> TypeVisitor<TyCtxt<'tcx>>
{
fn visit_ty(&mut self, ty: Ty<'tcx>) {
let tcx = self.tcx;
if self.ty_stack.iter().any(|visited_ty| ty == *visited_ty) {
if self.ty_stack.contains(&ty) {
return;
}

Expand Down Expand Up @@ -556,7 +556,7 @@ impl<'tcx, Dispatcher: RegionVisitorDispatcher<'tcx>> TypeVisitor<TyCtxt<'tcx>>
_ if ty.is_primitive_ty() => {}

_ => warn!("unimplemented {ty:?} ({:?})", ty.kind()),
};
}

// let inherent_impls = tcx.inherent_impls(self.def_id);
// let traits = tcx.infer_ctxt().enter(|infcx| {
Expand Down Expand Up @@ -764,7 +764,7 @@ fn main() {
body_with_facts: &BodyWithBorrowckFacts<'tcx>,
) {
let body = &body_with_facts.body;
let def_id = tcx.hir().body_owner_def_id(body_id).to_def_id();
let def_id = tcx.hir_body_owner_def_id(body_id).to_def_id();
let p = Placer::new(tcx, body);

let y = p.local("y").mk();
Expand Down
20 changes: 8 additions & 12 deletions crates/rustc_utils/src/source_map/find_bodies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,28 @@ struct BodyFinder<'tcx> {
impl<'tcx> Visitor<'tcx> for BodyFinder<'tcx> {
type NestedFilter = OnlyBodies;

fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
}

fn visit_nested_body(&mut self, id: BodyId) {
let hir = self.nested_visit_map();
let tcx = self.tcx;
let hir = tcx.hir();

// const/static items are considered to have bodies, so we want to exclude
// them from our search for functions
if !hir
.body_owner_kind(hir.body_owner_def_id(id))
if !tcx
.hir_body_owner_kind(tcx.hir_body_owner_def_id(id))
.is_fn_or_closure()
{
return;
}

let body = hir.body(id);
let body = tcx.hir_body(id);
self.visit_body(body);

let hir = self.tcx.hir();
let span = hir.span_with_body(hir.body_owner(id));
let span = hir.span_with_body(tcx.hir_body_owner(id));
trace!(
"Searching body for {:?} with span {span:?} (local {:?})",
self
.tcx
.def_path_debug_str(hir.body_owner_def_id(id).to_def_id()),
.def_path_debug_str(tcx.hir_body_owner_def_id(id).to_def_id()),
span.as_local(body.value.span)
);

Expand All @@ -55,7 +51,7 @@ pub fn find_bodies(tcx: TyCtxt) -> Vec<(Span, BodyId)> {
tcx,
bodies: Vec::new(),
};
tcx.hir().visit_all_item_likes_in_crate(&mut finder);
tcx.hir_visit_all_item_likes_in_crate(&mut finder);
finder.bodies
}

Expand Down
Loading