Skip to content

Add support for parsing Rust 2024 edition of #[unsafe(no_mangle)] and unsafe(export_name = "foo")] attributes. #103

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
62 changes: 51 additions & 11 deletions csbindgen/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,7 @@ fn parse_method(item: FnItem, options: &BindgenOptions) -> Option<ExternMethod>
if !is_foreign_item {
let found = attrs
.iter()
.map(|attr| {
let name = &attr.path().segments.last().unwrap().ident;
if name == "no_mangle" {
return Some(NoMangle);
} else if name == "export_name" {
if let Some(x) = get_str_from_meta(&attr.meta) {
return Some(ExportName(x));
}
}
None
})
.map(|attr| parse_method_attribute(attr))
.flatten()
.next();

Expand Down Expand Up @@ -166,6 +156,56 @@ fn parse_method(item: FnItem, options: &BindgenOptions) -> Option<ExternMethod>
None
}

fn parse_method_attribute(attr: &syn::Attribute) -> Option<ExportSymbolNaming> {
let name = &attr.path().segments.last().unwrap().ident;

match name.to_string().as_str() {
"no_mangle" => Some(NoMangle),
"export_name" => {
if let Some(x) = get_str_from_meta(&attr.meta) {
Some(ExportName(x))
} else {
None
}
}
"unsafe" => parse_method_attribute_arguments(attr),
_ => None,
}
}

fn parse_method_attribute_arguments(attr: &syn::Attribute) -> Option<ExportSymbolNaming> {
if let syn::Meta::List(_) = attr.meta {
let parse_result = attr.parse_args_with(|input: syn::parse::ParseStream| {
if input.is_empty() {
return Ok(None);
}

let mut result = None;
let meta = input.parse::<syn::Meta>()?;

if let Some(ident) = meta.path().get_ident() {
match ident.to_string().as_str() {
"no_mangle" => result = Some(NoMangle),
"export_name" => {
if let Some(x) = get_str_from_meta(&meta) {
result = Some(ExportName(x));
}
}
_ => {}
}
}
Ok(result)
});

match parse_result {
Ok(Some(value)) => return Some(value),
Ok(None) => {}
Err(e) => println!("csbindgen can't parse attribute args: {}", e),
}
}
None
}

pub fn collect_type_alias(ast: &syn::File, result: &mut AliasMap) {
for item in depth_first_module_walk(&ast.items) {
if let Item::Type(t) = item {
Expand Down