Skip to content

Allow modifying macro tokens at parse time #3211

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 5 commits into
base: main
Choose a base branch
from
Open
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
44 changes: 43 additions & 1 deletion bindgen-integration/build.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
extern crate bindgen;

use bindgen::callbacks::{
DeriveInfo, IntKind, MacroParsingBehavior, ParseCallbacks,
DeriveInfo, IntKind, MacroParsingBehavior, ParseCallbacks, Token, TokenKind,
};
use bindgen::{Builder, EnumVariation, Formatter};
use std::collections::HashSet;
Expand Down Expand Up @@ -145,6 +145,48 @@ impl ParseCallbacks for MacroCallback {
vec![]
}
}

fn modify_macro(&self, _name: &str, tokens: &mut Vec<Token>) {
// Handle macros dealing with bit positions of the format HI:LO
if tokens.len() == 4 && tokens[2].kind == TokenKind::Punctuation {
if let Ok(colon) = std::str::from_utf8(&tokens[2].raw) {
if colon != ":" {
return;
}
let high = match std::str::from_utf8(&tokens[1].raw) {
Ok(s) => {
if let Ok(val) = s.parse::<u16>() {
val
} else {
return;
}
}
Err(_) => {
return;
}
};

let low = match std::str::from_utf8(&tokens[3].raw) {
Ok(s) => {
if let Ok(val) = s.parse::<u16>() {
val
} else {
return;
}
}
Err(_) => {
return;
}
};
let value: u32 = ((high as u32) << 16) | low as u32;
tokens[1] = Token::from((
TokenKind::Literal,
value.to_string().as_bytes(),
));
tokens.truncate(2);
}
}
}
}

impl Drop for MacroCallback {
Expand Down
2 changes: 2 additions & 0 deletions bindgen-integration/cpp/Test.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
#define TESTMACRO_STRING_EXPR ("string")
#define TESTMACRO_STRING_FUNC_NON_UTF8(x) (x "ÿÿ") /* invalid UTF-8 on purpose */

#define TESTMACRO_COLON_VALUE 1:2

enum {
MY_ANNOYING_MACRO =
#define MY_ANNOYING_MACRO 1
Expand Down
6 changes: 6 additions & 0 deletions bindgen-integration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,9 @@ fn test_wrap_static_fns() {
extern_bindings::wrap_as_variadic_fn2_wrapped(1, 2);
}
}

#[test]
fn test_colon_define() {
let gold: u32 = (1u32 << 16) | 2;
assert_eq!(gold, bindings::TESTMACRO_COLON_VALUE);
}
5 changes: 5 additions & 0 deletions bindgen/callbacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ pub use crate::ir::analysis::DeriveTrait;
pub use crate::ir::derive::CanDerive as ImplementsTrait;
pub use crate::ir::enum_ty::{EnumVariantCustomBehavior, EnumVariantValue};
pub use crate::ir::int::IntKind;
pub use cexpr::token::Kind as TokenKind;
pub use cexpr::token::Token;
use std::fmt;

/// An enum to allow ignoring parsing of macros.
Expand Down Expand Up @@ -49,6 +51,9 @@ pub trait ParseCallbacks: fmt::Debug {
None
}

/// Modify the contents of a macro
fn modify_macro(&self, _name: &str, _tokens: &mut Vec<Token>) {}

/// The integer kind an integer macro should have, given a name and the
/// value of that macro, or `None` if you want the default to be chosen.
fn int_macro(&self, _name: &str, _value: i64) -> Option<IntKind> {
Expand Down
6 changes: 5 additions & 1 deletion bindgen/ir/var.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,11 @@ fn parse_macro(
) -> Option<(Vec<u8>, cexpr::expr::EvalResult)> {
use cexpr::expr;

let cexpr_tokens = cursor.cexpr_tokens();
let mut cexpr_tokens = cursor.cexpr_tokens();

for callbacks in &ctx.options().parse_callbacks {
callbacks.modify_macro(&cursor.spelling(), &mut cexpr_tokens);
}

let parser = expr::IdentifierParser::new(ctx.parsed_macros());

Expand Down
Loading