Skip to content

Fix Deser for Other Attributes #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repository = "https://github.com/rust-lang/rustdoc-types"
serde = {version="1.0.186"}
serde_derive = {version="1.0.186"}
rustc-hash = {version="2", optional=true}
serde_json = "1.0"

[features]
default = []
Expand Down
105 changes: 103 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use std::path::PathBuf;
#[cfg(feature = "rustc-hash")]
use rustc_hash::FxHashMap as HashMap;
use serde_derive::{Deserialize, Serialize};

use serde::de::Error;

/// The version of JSON output that this crate represents.
///
Expand Down Expand Up @@ -201,7 +201,7 @@ pub struct Item {
pub inner: ItemEnum,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
/// An attribute, e.g. `#[repr(C)]`
///
Expand Down Expand Up @@ -245,6 +245,105 @@ pub enum Attribute {
Other(String),
}

impl<'de> serde::Deserialize<'de> for Attribute {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;

// Strip #[ and ] if present
let cleaned = s.trim_start_matches("#[")
.trim_end_matches("]")
.trim();

// Now match on the cleaned string
Ok(match cleaned {
"non_exhaustive" => Attribute::NonExhaustive,
s if s.starts_with("must_use") => {
// Parse reason if present
let reason = if s.len() > "must_use".len() {
Some(s["must_use".len()..].trim_matches(|c| c == '(' || c == ')' || c == '"').to_string())
} else {
None
};
Attribute::MustUse { reason }
},
s if s.starts_with("export_name") => {
let name = s["export_name".len()..].trim_matches(|c| c == '=' || c == ' ' || c == '"').to_string();
Attribute::ExportName(name)
},

s if s.starts_with("export_name") => {
let name = s["export_name".len()..].trim_matches(|c| c == '=' || c == ' ' || c == '"').to_string();
Attribute::ExportName(name)
},

s if s.starts_with("link_section") => {
let section = s["link_section".len()..].trim_matches(|c| c == '=' || c == ' ' || c == '"').to_string();
Attribute::LinkSection(section)
},

"automatically_derived" => Attribute::AutomaticallyDerived,

s if s.starts_with("repr") => {
let repr_str = s["repr".len()..].trim_matches(|c| c == '(' || c == ')').trim();
let parts: Vec<&str> = repr_str.split(',').map(str::trim).collect();

let mut repr = AttributeRepr {
kind: ReprKind::C, // Will be overwritten
align: None,
packed: None,
int: None,
};

for part in parts {
if part.starts_with("align(") {
let align_str = part.trim_start_matches("align(").trim_end_matches(')');
repr.align = Some(align_str.parse().map_err(D::Error::custom)?);
} else if part.starts_with("packed(") {
let packed_str = part.trim_start_matches("packed(").trim_end_matches(')');
repr.packed = Some(packed_str.parse().map_err(D::Error::custom)?);
} else if part == "C" {
repr.kind = ReprKind::C;
} else if part == "transparent" {
repr.kind = ReprKind::Transparent;
} else if ["i8", "i16", "i32", "i64", "i128", "isize",
"u8", "u16", "u32", "u64", "u128", "usize"].contains(&part) {
repr.int = Some(part.to_string());
}
// Add other ReprKind variants as needed
}

Attribute::Repr(repr)
},

"no_mangle" => Attribute::NoMangle,

s if s.starts_with("target_feature") => {
let features_str = s["target_feature".len()..].trim_matches(|c| c == '(' || c == ')').trim();
let enable: Vec<String> = features_str
.split(',')
.filter_map(|feature| {
let feature = feature.trim();
if feature.starts_with("enable = ") {
Some(feature["enable = ".len()..].trim_matches('"').to_string())
} else {
None
}
})
.collect();
Attribute::TargetFeature { enable }
},


// Default case
_ => Attribute::Other(s.to_string()),
})
}
}


#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
/// The contents of a `#[repr(...)]` attribute.
///
Expand Down Expand Up @@ -878,6 +977,8 @@ pub enum Abi {
/// Can be specified as `extern "system"`.
System { unwind: bool },
/// Any other ABI, including unstable ones.
// XXX: This variant must be last in the enum because it is untagged.
#[serde(untagged)]
Other(String),
}

Expand Down
15 changes: 12 additions & 3 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@ use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
generics: Generics { params: vec![], where_predicates: vec![] },
kind: StructKind::Plain { fields: vec![], has_stripped_fields: false },
generics: Generics {
params: vec![],
where_predicates: vec![],
},
kind: StructKind::Plain {
fields: vec![],
has_stripped_fields: false,
},
impls: vec![],
});

Expand All @@ -22,7 +28,10 @@ fn test_struct_info_roundtrip() {
#[test]
fn test_union_info_roundtrip() {
let u = ItemEnum::Union(Union {
generics: Generics { params: vec![], where_predicates: vec![] },
generics: Generics {
params: vec![],
where_predicates: vec![],
},
has_stripped_fields: false,
fields: vec![],
impls: vec![],
Expand Down
Loading