Skip to content

Commit 84071e2

Browse files
committed
Support fetching Attribute of items.
1 parent 9c3bc80 commit 84071e2

File tree

7 files changed

+193
-2
lines changed

7 files changed

+193
-2
lines changed

Cargo.lock

+2
Original file line numberDiff line numberDiff line change
@@ -4675,6 +4675,8 @@ name = "rustc_smir"
46754675
version = "0.0.0"
46764676
dependencies = [
46774677
"rustc_abi",
4678+
"rustc_ast",
4679+
"rustc_ast_pretty",
46784680
"rustc_data_structures",
46794681
"rustc_hir",
46804682
"rustc_middle",

compiler/rustc_smir/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ edition = "2021"
66
[dependencies]
77
# tidy-alphabetical-start
88
rustc_abi = { path = "../rustc_abi" }
9+
rustc_ast = { path = "../rustc_ast" }
10+
rustc_ast_pretty = { path = "../rustc_ast_pretty" }
911
rustc_data_structures = { path = "../rustc_data_structures" }
1012
rustc_hir = { path = "../rustc_hir" }
1113
rustc_middle = { path = "../rustc_middle" }

compiler/rustc_smir/src/rustc_smir/context.rs

+19
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,25 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
228228
}
229229
}
230230

231+
fn get_attrs_by_path(
232+
&self,
233+
def_id: stable_mir::DefId,
234+
attr: &[stable_mir::Symbol],
235+
) -> Vec<stable_mir::ty::Attribute> {
236+
let mut tables = self.0.borrow_mut();
237+
let tcx = tables.tcx;
238+
let did = tables[def_id];
239+
let attr_name: Vec<_> =
240+
attr.iter().map(|seg| rustc_span::symbol::Symbol::intern(&seg)).collect();
241+
tcx.get_attrs_by_path(did, &attr_name)
242+
.map(|attribute| {
243+
let attr_str = rustc_ast_pretty::pprust::attribute_to_string(attribute);
244+
let span = attribute.span;
245+
stable_mir::ty::Attribute::new(attr_str, span.stable(&mut *tables))
246+
})
247+
.collect()
248+
}
249+
231250
fn span_to_string(&self, span: stable_mir::ty::Span) -> String {
232251
let tables = self.0.borrow();
233252
tables.tcx.sess.source_map().span_to_diagnostic_string(tables[span])

compiler/stable_mir/src/compiler_interface.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::mir::mono::{Instance, InstanceDef, StaticDef};
1111
use crate::mir::{BinOp, Body, Place, UnOp};
1212
use crate::target::MachineInfo;
1313
use crate::ty::{
14-
AdtDef, AdtKind, Allocation, ClosureDef, ClosureKind, FieldDef, FnDef, ForeignDef,
14+
AdtDef, AdtKind, Allocation, Attribute, ClosureDef, ClosureKind, FieldDef, FnDef, ForeignDef,
1515
ForeignItemKind, ForeignModule, ForeignModuleDef, GenericArgs, GenericPredicates, Generics,
1616
ImplDef, ImplTrait, IntrinsicDef, LineInfo, MirConst, PolyFnSig, RigidTy, Span, TraitDecl,
1717
TraitDef, Ty, TyConst, TyConstId, TyKind, UintTy, VariantDef,
@@ -55,6 +55,9 @@ pub trait Context {
5555
/// Returns the name of given `DefId`
5656
fn def_name(&self, def_id: DefId, trimmed: bool) -> Symbol;
5757

58+
/// Get all attributes with the given attribute name.
59+
fn get_attrs_by_path(&self, def_id: DefId, attr: &[Symbol]) -> Vec<Attribute>;
60+
5861
/// Returns printable, human readable form of `Span`
5962
fn span_to_string(&self, span: Span) -> String;
6063

compiler/stable_mir/src/crate_def.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Module that define a common trait for things that represent a crate definition,
22
//! such as, a function, a trait, an enum, and any other definitions.
33
4-
use crate::ty::{GenericArgs, Span, Ty};
4+
use crate::ty::{Attribute, GenericArgs, Span, Ty};
55
use crate::{with, Crate, Symbol};
66

77
/// A unique identification number for each item accessible for the current compilation unit.
@@ -50,6 +50,12 @@ pub trait CrateDef {
5050
let def_id = self.def_id();
5151
with(|cx| cx.span_of_an_item(def_id))
5252
}
53+
54+
/// Return attributes with the given attribute name.
55+
fn attrs_by_path(&self, attr: &[Symbol]) -> Vec<Attribute> {
56+
let def_id = self.def_id();
57+
with(|cx| cx.get_attrs_by_path(def_id, attr))
58+
}
5359
}
5460

5561
/// A trait that can be used to retrieve a definition's type.

compiler/stable_mir/src/ty.rs

+22
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,28 @@ pub struct Placeholder<T> {
248248
pub bound: T,
249249
}
250250

251+
#[derive(Clone, Debug, PartialEq, Eq)]
252+
pub struct Attribute {
253+
value: String,
254+
span: Span,
255+
}
256+
257+
impl Attribute {
258+
pub fn new(value: String, span: Span) -> Attribute {
259+
Attribute { value, span }
260+
}
261+
262+
/// Get the span of this attribute.
263+
pub fn span(&self) -> Span {
264+
self.span
265+
}
266+
267+
/// Get the string representation of this attribute.
268+
pub fn as_str(&self) -> &str {
269+
&self.value
270+
}
271+
}
272+
251273
#[derive(Clone, Copy, PartialEq, Eq)]
252274
pub struct Span(usize);
253275

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
//@ run-pass
2+
//! Test information regarding type layout.
3+
4+
//@ ignore-stage1
5+
//@ ignore-cross-compile
6+
//@ ignore-remote
7+
//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837
8+
9+
#![feature(rustc_private)]
10+
#![feature(control_flow_enum)]
11+
12+
extern crate rustc_hir;
13+
#[macro_use]
14+
extern crate rustc_smir;
15+
extern crate rustc_driver;
16+
extern crate rustc_interface;
17+
extern crate stable_mir;
18+
19+
use rustc_smir::rustc_internal;
20+
use stable_mir::{CrateDef, CrateItems};
21+
use std::io::Write;
22+
use std::ops::ControlFlow;
23+
24+
const CRATE_NAME: &str = "input";
25+
26+
/// This function uses the Stable MIR APIs to get information about the test crate.
27+
fn test_stable_mir() -> ControlFlow<()> {
28+
// Find items in the local crate.
29+
let items = stable_mir::all_local_items();
30+
31+
test_builtins(&items);
32+
test_derive(&items);
33+
test_tool(&items);
34+
35+
ControlFlow::Continue(())
36+
}
37+
38+
// Test built-in attributes.
39+
fn test_builtins(items: &CrateItems) {
40+
let target_fn = *get_item(&items, "builtins_fn").unwrap();
41+
let allow_attrs = target_fn.attrs_by_path(&["allow".to_string()]);
42+
assert_eq!(allow_attrs[0].as_str(), "#![allow(unused_variables)]");
43+
44+
let inline_attrs = target_fn.attrs_by_path(&["inline".to_string()]);
45+
assert_eq!(inline_attrs[0].as_str(), "#[inline]");
46+
47+
let deprecated_attrs = target_fn.attrs_by_path(&["deprecated".to_string()]);
48+
assert_eq!(deprecated_attrs[0].as_str(), "#[deprecated(since = \"5.2.0\")]");
49+
}
50+
51+
// Test derive attribute.
52+
fn test_derive(items: &CrateItems) {
53+
let target_struct = *get_item(&items, "Foo").unwrap();
54+
let attrs = target_struct.attrs_by_path(&["derive".to_string()]);
55+
// No `derive` attribute since it's expanded before MIR.
56+
assert_eq!(attrs.len(), 0);
57+
58+
// Check derived trait method's attributes.
59+
let derived_fmt = *get_item(&items, "<Foo as std::fmt::Debug>::fmt").unwrap();
60+
// The Rust reference lies about this attribute. It doesn't show up in `clone` or `fmt` impl.
61+
let _fmt_attrs = derived_fmt.attrs_by_path(&["automatically_derived".to_string()]);
62+
}
63+
64+
// Test tool attributes.
65+
fn test_tool(items: &CrateItems) {
66+
let rustfmt_fn = *get_item(&items, "do_not_format").unwrap();
67+
let rustfmt_attrs = rustfmt_fn.attrs_by_path(&["rustfmt".to_string(), "skip".to_string()]);
68+
assert_eq!(rustfmt_attrs[0].as_str(), "#[rustfmt::skip]");
69+
70+
let clippy_fn = *get_item(&items, "complex_fn").unwrap();
71+
let clippy_attrs = clippy_fn.attrs_by_path(&["clippy".to_string(),
72+
"cyclomatic_complexity".to_string()]);
73+
assert_eq!(clippy_attrs[0].as_str(), "#[clippy::cyclomatic_complexity = \"100\"]");
74+
}
75+
76+
77+
fn get_item<'a>(
78+
items: &'a CrateItems,
79+
name: &str,
80+
) -> Option<&'a stable_mir::CrateItem> {
81+
for item in items {
82+
println!("{:?}", item);
83+
}
84+
items.iter().find(|crate_item| crate_item.name() == name)
85+
}
86+
87+
/// This test will generate and analyze a dummy crate using the stable mir.
88+
/// For that, it will first write the dummy crate into a file.
89+
/// Then it will create a `StableMir` using custom arguments and then
90+
/// it will run the compiler.
91+
fn main() {
92+
let path = "attribute_input.rs";
93+
generate_input(&path).unwrap();
94+
let args = vec![
95+
"rustc".to_string(),
96+
"--crate-type=lib".to_string(),
97+
"--crate-name".to_string(),
98+
CRATE_NAME.to_string(),
99+
path.to_string(),
100+
];
101+
run!(args, test_stable_mir).unwrap();
102+
}
103+
104+
fn generate_input(path: &str) -> std::io::Result<()> {
105+
let mut file = std::fs::File::create(path)?;
106+
write!(
107+
file,
108+
r#"
109+
// General metadata applied to the enclosing module or crate.
110+
#![crate_type = "lib"]
111+
112+
// Mixed inner and outer attributes.
113+
#[inline]
114+
#[deprecated(since = "5.2.0")]
115+
fn builtins_fn() {{
116+
#![allow(unused_variables)]
117+
118+
let x = ();
119+
let y = ();
120+
let z = ();
121+
}}
122+
123+
// A derive attribute to automatically implement a trait.
124+
#[derive(Debug, Clone, Copy)]
125+
struct Foo(u32);
126+
127+
// A rustfmt tool attribute.
128+
#[rustfmt::skip]
129+
fn do_not_format() {{}}
130+
131+
// A clippy tool attribute.
132+
#[clippy::cyclomatic_complexity = "100"]
133+
pub fn complex_fn() {{}}
134+
"#
135+
)?;
136+
Ok(())
137+
}

0 commit comments

Comments
 (0)