fixed generation 1

This commit is contained in:
neuecc 2023-03-06 18:06:52 +09:00
parent 6d9e535975
commit 2f24e3a675
14 changed files with 8166 additions and 509 deletions

View File

@ -188,6 +188,19 @@ pub extern "C" fn call_bindgen() {
.unwrap(); .unwrap();
} }
#[no_mangle]
pub extern "C" fn call_bindgen_lz4() {
let path = std::env::current_dir().unwrap();
println!("starting dir: {}", path.display()); // csbindgen/csbindgen-tests
csbindgen::Builder::default()
.input_extern_file("../../../../csbindgen-tests/src/lz4.rs")
.csharp_class_name("LibLz4")
.csharp_dll_name("csbindgen_tests")
.generate_to_file("../../../../csbindgen-tests/src/lz4_ffi.cs", "../../../../dotnet-sandbox/lz4_bindgen.cs")
.unwrap();
}
#[repr(C)] #[repr(C)]
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct Context { pub struct Context {
@ -289,3 +302,8 @@ impl ByteBuffer {
drop(self.destroy_into_vec()); drop(self.destroy_into_vec());
} }
} }
trait Ex {}
impl Ex for i32{
}

File diff suppressed because it is too large Load Diff

View File

@ -84,6 +84,13 @@ impl AliasMap {
None => None, None => None,
} }
} }
pub fn get_mapped_name_or_self(&self, name: &String) -> String {
match self.get_mapped_value(name) {
Some(x) => x.type_name.to_owned(),
None => name.to_owned(),
}
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -214,6 +214,7 @@ pub fn emit_csharp(
// This code is generated by csbindgen. // This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY. // DON'T CHANGE THIS DIRECTLY.
// </auto-generated> // </auto-generated>
#pragma warning disable CS8981
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;

View File

@ -0,0 +1,58 @@
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
};
#[derive(Clone, Debug)]
pub struct FieldMap {
fields: HashMap<String, RefCell<HashSet<String>>>, // field_type_name -> DeclaringType(s)
}
impl FieldMap {
pub fn new() -> Self {
Self {
fields: HashMap::new(),
}
}
// type_name must be normalized
pub fn insert(&mut self, type_name: &String, field_type: &String) {
match self.fields.get(field_type) {
Some(x) => {
x.borrow_mut().insert(type_name.to_owned());
}
None => {
let map = RefCell::new(HashSet::new());
map.borrow_mut().insert(type_name.to_owned());
self.fields.insert(field_type.to_owned(), map);
}
}
}
pub fn exists_in_using_types(
&self,
struct_name: &String,
using_types: &HashSet<String>,
recursive_count: i32, // detect recrusive reference
) -> bool {
if recursive_count >= 10 {
return false;
}
if using_types.contains(struct_name) {
return true;
}
// try to find declaring types
if let Some(x) = self.fields.get(struct_name) {
for name in x.borrow().iter() {
if self.exists_in_using_types(name, using_types, recursive_count + 1) {
return true;
}
}
}
false
}
}

View File

@ -1,6 +1,7 @@
mod alias_map; mod alias_map;
mod builder; mod builder;
mod emitter; mod emitter;
mod field_map;
mod parser; mod parser;
mod type_meta; mod type_meta;
mod util; mod util;
@ -9,6 +10,7 @@ pub use builder::Builder;
use builder::BindgenOptions; use builder::BindgenOptions;
use emitter::*; use emitter::*;
use field_map::FieldMap;
use parser::*; use parser::*;
use std::{collections::HashSet, error::Error}; use std::{collections::HashSet, error::Error};
@ -37,26 +39,31 @@ pub(crate) fn generate(
let structs = collect_struct(&file_ast); let structs = collect_struct(&file_ast);
let enums = collect_enum(&file_ast); let enums = collect_enum(&file_ast);
// collect using_types
let mut using_types = HashSet::new(); let mut using_types = HashSet::new();
for method in &methods { for method in &methods {
// add to using_types with normalize
if let Some(x) = &method.return_type { if let Some(x) = &method.return_type {
using_types.insert(x.type_name.clone()); let normalized = aliases.get_mapped_name_or_self(&x.type_name);
using_types.insert(normalized.clone());
} }
for p in &method.parameters { for p in &method.parameters {
using_types.insert(p.rust_type.type_name.clone()); let normalized = aliases.get_mapped_name_or_self(&p.rust_type.type_name);
using_types.insert(normalized);
} }
} }
for item in &structs { let mut field_map = FieldMap::new();
if using_types.contains(&item.struct_name) { for struct_type in &structs {
for item in &item.fields { for field in &struct_type.fields {
using_types.insert(item.rust_type.type_name.clone()); let struct_type_normalized = aliases.get_mapped_name_or_self(&struct_type.struct_name);
} let field_type_normalized = aliases.get_mapped_name_or_self(&field.rust_type.type_name);
field_map.insert(&struct_type_normalized, &field_type_normalized);
} }
} }
let structs = reduce_struct(&structs, &using_types); let structs = reduce_struct(&structs, &field_map, &using_types);
let enums = reduce_enum(&enums, &using_types); let enums = reduce_enum(&enums, &field_map, &using_types);
let rust = if generate_rust { let rust = if generate_rust {
Some(emit_rust_method(&methods, options)) Some(emit_rust_method(&methods, options))
@ -68,16 +75,18 @@ pub(crate) fn generate(
Ok((rust, csharp)) Ok((rust, csharp))
} }
// #[test] #[test]
// fn test() { fn test() {
// let path = std::env::current_dir().unwrap(); let path = std::env::current_dir().unwrap();
// println!("starting dir: {}", path.display()); // csbindgen/csbindgen println!("starting dir: {}", path.display()); // csbindgen/csbindgen
// Builder::new() Builder::new()
// .input_bindgen_file("../csbindgen-tests/src/quiche.rs") .input_bindgen_file("csbindgen-tests/src/lz4.rs")
// .rust_method_prefix("csbindgen_quiche_") .csharp_class_name("LibLz4")
// .csharp_class_name("LibQuiche") .csharp_dll_name("csbindgen_tests")
// .csharp_dll_name("libquiche") .generate_to_file(
// .generate_to_file("../csbindgen-tests/src/quiche_ffi.rs", "../csbindgen-tests/../dotnet-sandbox/quiche_bindgen.cs") "csbindgen-tests/src/lz4_ffi.rs",
// .unwrap(); "dotnet-sandbox/lz4_bindgen.cs",
// } )
.unwrap();
}

View File

@ -1,4 +1,4 @@
use crate::{alias_map::AliasMap, builder::BindgenOptions, type_meta::*}; use crate::{alias_map::AliasMap, builder::BindgenOptions, field_map::FieldMap, type_meta::*};
use std::collections::HashSet; use std::collections::HashSet;
use syn::{ForeignItem, Item, Pat, ReturnType}; use syn::{ForeignItem, Item, Pat, ReturnType};
@ -227,10 +227,14 @@ pub fn collect_enum(ast: &syn::File) -> Vec<RustEnum> {
result result
} }
pub fn reduce_struct(structs: &Vec<RustStruct>, using_types: &HashSet<String>) -> Vec<RustStruct> { pub fn reduce_struct(
structs: &Vec<RustStruct>,
field_map: &FieldMap,
using_types: &HashSet<String>,
) -> Vec<RustStruct> {
let mut result = Vec::new(); let mut result = Vec::new();
for item in structs { for item in structs {
if using_types.contains(&item.struct_name) { if field_map.exists_in_using_types(&item.struct_name, using_types, 0) {
result.push(item.clone()); result.push(item.clone());
} }
} }
@ -238,10 +242,14 @@ pub fn reduce_struct(structs: &Vec<RustStruct>, using_types: &HashSet<String>) -
result result
} }
pub fn reduce_enum(enums: &Vec<RustEnum>, using_types: &HashSet<String>) -> Vec<RustEnum> { pub fn reduce_enum(
enums: &Vec<RustEnum>,
field_map: &FieldMap,
using_types: &HashSet<String>,
) -> Vec<RustEnum> {
let mut result = Vec::new(); let mut result = Vec::new();
for item in enums { for item in enums {
if using_types.contains(&item.enum_name) { if field_map.exists_in_using_types(&item.enum_name, using_types, 0) {
result.push(item.clone()); result.push(item.clone());
} }
} }

View File

@ -8,6 +8,13 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<!--<Compile Remove="bullet3_bindgen.cs" />
<Compile Remove="lz4_bindgen.cs" />
<Compile Remove="quiche_bindgen.cs" />
<Compile Remove="zstd_bindgen.cs" />-->
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="../target/debug/csbindgen_tests.dll"> <None Include="../target/debug/csbindgen_tests.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>

View File

@ -13,6 +13,10 @@ using System.Text;
unsafe unsafe
{ {
LibRust.call_bindgen_lz4();
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
static int Method(int x) => x * x; static int Method(int x) => x * x;

View File

@ -2,6 +2,7 @@
// This code is generated by csbindgen. // This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY. // DON'T CHANGE THIS DIRECTLY.
// </auto-generated> // </auto-generated>
#pragma warning disable CS8981
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -1767,6 +1768,24 @@ namespace CsBindgen
public fixed byte/* b3ForwardDynamicsAnalyticsIslandData, this length is invalid so must keep pointer and can't edit from C# */ m_islandData[64]; public fixed byte/* b3ForwardDynamicsAnalyticsIslandData, this length is invalid so must keep pointer and can't edit from C# */ m_islandData[64];
} }
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct b3PhysicsClientHandle__
{
public int unused;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct b3SharedMemoryCommandHandle__
{
public int unused;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct b3SharedMemoryStatusHandle__
{
public int unused;
}
} }

View File

@ -2,6 +2,7 @@
// This code is generated by csbindgen. // This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY. // DON'T CHANGE THIS DIRECTLY.
// </auto-generated> // </auto-generated>
#pragma warning disable CS8981
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -332,6 +333,70 @@ namespace CsBindgen
} }
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4_stream_t_internal
{
public fixed uint hashTable[4096];
public byte* dictionary;
public LZ4_stream_t_internal* dictCtx;
public uint currentOffset;
public uint tableType;
public uint dictSize;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct LZ4_stream_u
{
[FieldOffset(0)]
public fixed byte minStateSize[16416];
[FieldOffset(0)]
public LZ4_stream_t_internal internal_donotuse;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4_streamDecode_t_internal
{
public byte* externalDict;
public byte* prefixEnd;
public UIntPtr extDictSize;
public UIntPtr prefixSize;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct LZ4_streamDecode_u
{
[FieldOffset(0)]
public fixed byte minStateSize[32];
[FieldOffset(0)]
public LZ4_streamDecode_t_internal internal_donotuse;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4HC_CCtx_internal
{
public fixed uint hashTable[32768];
public fixed ushort chainTable[65536];
public byte* end;
public byte* prefixStart;
public byte* dictStart;
public uint dictLimit;
public uint lowLimit;
public uint nextToUpdate;
public short compressionLevel;
public sbyte favorDecSpeed;
public sbyte dirty;
public LZ4HC_CCtx_internal* dictCtx;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct LZ4_streamHC_u
{
[FieldOffset(0)]
public fixed byte minStateSize[262200];
[FieldOffset(0)]
public LZ4HC_CCtx_internal internal_donotuse;
}
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4F_frameInfo_t public unsafe partial struct LZ4F_frameInfo_t
{ {
@ -354,6 +419,12 @@ namespace CsBindgen
public fixed uint reserved[3]; public fixed uint reserved[3];
} }
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4F_cctx_s
{
public fixed byte _unused[1];
}
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4F_compressOptions_t public unsafe partial struct LZ4F_compressOptions_t
{ {
@ -361,6 +432,12 @@ namespace CsBindgen
public fixed uint reserved[3]; public fixed uint reserved[3];
} }
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4F_dctx_s
{
public fixed byte _unused[1];
}
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public unsafe partial struct LZ4F_decompressOptions_t public unsafe partial struct LZ4F_decompressOptions_t
{ {

View File

@ -2,6 +2,7 @@
// This code is generated by csbindgen. // This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY. // DON'T CHANGE THIS DIRECTLY.
// </auto-generated> // </auto-generated>
#pragma warning disable CS8981
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -78,6 +79,9 @@ namespace CsBindgen
[DllImport(__DllName, EntryPoint = "call_bindgen", CallingConvention = CallingConvention.Cdecl)] [DllImport(__DllName, EntryPoint = "call_bindgen", CallingConvention = CallingConvention.Cdecl)]
public static extern void call_bindgen(); public static extern void call_bindgen();
[DllImport(__DllName, EntryPoint = "call_bindgen_lz4", CallingConvention = CallingConvention.Cdecl)]
public static extern void call_bindgen_lz4();
} }

View File

@ -2,6 +2,7 @@
// This code is generated by csbindgen. // This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY. // DON'T CHANGE THIS DIRECTLY.
// </auto-generated> // </auto-generated>
#pragma warning disable CS8981
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;

View File

@ -2,6 +2,7 @@
// This code is generated by csbindgen. // This code is generated by csbindgen.
// DON'T CHANGE THIS DIRECTLY. // DON'T CHANGE THIS DIRECTLY.
// </auto-generated> // </auto-generated>
#pragma warning disable CS8981
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -254,6 +255,18 @@ namespace CsBindgen
} }
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_CCtx_s
{
public fixed byte _unused[1];
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_DCtx_s
{
public fixed byte _unused[1];
}
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_bounds internal unsafe partial struct ZSTD_bounds
{ {
@ -262,6 +275,34 @@ namespace CsBindgen
public int upperBound; public int upperBound;
} }
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_inBuffer_s
{
public void* src;
public UIntPtr size;
public UIntPtr pos;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_outBuffer_s
{
public void* dst;
public UIntPtr size;
public UIntPtr pos;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_CDict_s
{
public fixed byte _unused[1];
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe partial struct ZSTD_DDict_s
{
public fixed byte _unused[1];
}
} }