Skip to content
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

physx-sys: Emit default values in FFI bindings for literal values #221

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
27 changes: 26 additions & 1 deletion physx-sys/pxbind/src/consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,31 @@ pub enum Item {
kind: Type,
},
ConstantExpr {
value: Option<String>,
#[serde(rename = "type")]
kind: Type,
},
CXXBoolLiteralExpr {
value: bool,
#[serde(rename = "type")]
kind: Type,
},
IntegerLiteral {
value: String,
#[serde(rename = "type")]
kind: Type,
},
FloatingLiteral {
value: String,
#[serde(rename = "type")]
kind: Type,
},
StringLiteral {
value: String,
#[serde(rename = "type")]
kind: Type,
},
UserDefinedLiteral {
value: String,
#[serde(rename = "type")]
kind: Type,
Expand All @@ -111,7 +136,7 @@ pub enum Item {
TemplateArgument {
#[serde(rename = "type")]
kind: Option<Type>,
value: Option<i32>,
value: Option<i64>,
},
RecordType {
#[serde(rename = "type")]
Expand Down
4 changes: 3 additions & 1 deletion physx-sys/pxbind/src/consumer/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ impl<'ast> super::AstConsumer<'ast> {
}
}

return value.parse().context("failed to parse enum constant");
if let Some(v) = value {
return v.parse().context("failed to parse enum constant");
}
}
_ => continue,
}
Expand Down
29 changes: 26 additions & 3 deletions physx-sys/pxbind/src/consumer/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub struct Function {
pub struct Param<'ast> {
pub name: Cow<'ast, str>,
pub kind: QualType<'ast>,
pub default_value: Option<&'ast str>,
}

impl<'ast> Param<'ast> {
Expand All @@ -27,6 +28,7 @@ impl<'ast> Param<'ast> {
is_pointee_const: is_const,
pointee: Box::new(rec_type),
},
default_value: None,
}
}
}
Expand Down Expand Up @@ -181,12 +183,29 @@ impl<'ast> super::AstConsumer<'ast> {
template_types: &[(&str, &TemplateArg<'ast>)],
func: &mut FuncBinding<'ast>,
) -> anyhow::Result<()> {
for (i, param) in node
for (i, (param, default_value)) in node
.inner
.iter()
.filter_map(|inn| {
if let Item::ParmVarDecl(param) = &inn.kind {
Some(param)
if inn.inner.len() > 0 {
let default_value: Option<&str> = match &inn.inner[0].kind {
Item::IntegerLiteral { value, kind: _ } => Some(value),
Item::FloatingLiteral { value, kind: _ } => {
Some(if value == "1.00999999" { "1.01" } else { value })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems... weird to me. I don't think you could get a floating point error turning 1.01 into 1.0099999. Where does it show up?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the C++ headers the "inflation" parameter to several different functions often has the value of "1.01" - but the Clang++ json dump command prints these values as 1.00999999 - so changing it back to 1.01 better matches the original value in the C++ headers.

virtual		PxBounds3		getWorldBounds(float inflation = 1.01f) const = 0;

A more general fix would obviously be to handle any floating point value that seems to have been incorrectly formatted, but I think this was basically the only default value PhysX uses that has this error.

Copy link
Member Author

@slvmnd slvmnd Oct 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Putting:

float f(float a=1.01f) {
	return a+a;
}

Through "clang++ -Xclang -ast-dump=json -fsyntax-only tst.cpp" gives:

          "name": "a",
          "type": {
            "qualType": "float"
          },
          "init": "c",
          "inner": [
            {
              "id": "0x7fe26608a580",
              "kind": "FloatingLiteral",
              "range": {
                "begin": {
                  "offset": 14,
                  "col": 15,
                  "tokLen": 5
                },
                "end": {
                  "offset": 14,
                  "col": 15,
                  "tokLen": 5
                }
              },
              "type": {
                "qualType": "float"
              },
              "valueCategory": "prvalue",
              "value": "1.00999999"
            }
          ]

🥴

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the same value in f32, clang just does lazy job at human-formatting:

dbg!(1.01f32-1.00999999f32 == 0.0f32);
dbg!(1.01f32-1.00999999f32);
dbg!(1.01f64-1.00999999f64 == 0.0f64);
dbg!(1.01f64-1.00999999f64);
[src\main.rs:2] 1.01f32 - 1.00999999f32 == 0.0f32 = true
[src\main.rs:3] 1.01f32 - 1.00999999f32 = 0.0
[src\main.rs:4] 1.01f64 - 1.00999999f64 == 0.0f64 = false
[src\main.rs:5] 1.01f64 - 1.00999999f64 = 9.99999993922529e-9

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest to parse and format it back in rust (and add a comment explaining it):

value.parse::<f32>().ok().map(|value| format!("{value}"))
[src\main.rs:2] "1.00999999".parse::<f32>().ok().map(|value| format!("{value}")) = Some(
    "1.01",
)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion @rlidwka - I have updated the pull request using format! instead.

}
Item::StringLiteral { value, kind: _ } => Some(value),
Item::UserDefinedLiteral { value, kind: _ } => Some(value),
Item::CXXBoolLiteralExpr { value, kind: _ } => {
Some(if *value { "true" } else { "false" })
}
_ => None,
};

Some((param, default_value))
} else {
Some((param, None))
}
} else {
None
}
Expand All @@ -206,7 +225,11 @@ impl<'ast> super::AstConsumer<'ast> {
)
})?;

func.params.push(Param { name: pname, kind });
func.params.push(Param {
name: pname,
kind,
default_value: default_value,
});
}

Ok(())
Expand Down
14 changes: 13 additions & 1 deletion physx-sys/pxbind/src/generator/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,20 @@ impl<'ast> FuncBinding<'ast> {
}

let indent = Indent(level);

let mut acc = String::new();

// write default values of params
let mut first_param = true;
for param in self.params.iter() {
if let Some(v) = &param.default_value {
if first_param {
writesln!(acc, "{indent}///");
first_param = false;
}
writesln!(acc, "{indent}/// {} = {}", param.name, v);
}
}

writes!(acc, "{indent}pub fn {}(", self.name);

for (i, param) in self.params.iter().enumerate() {
Expand Down