1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use crate::ir::{Attributes, Attribute, Path};
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use quote::quote;
use std::convert::TryFrom;
pub fn ligen_dependencies(attributes: TokenStream) -> TokenStream {
let attributes = Attributes::try_from(attributes).expect("Failed to parse Attributes.");
let mut dependencies = TokenStream::new();
let mut ligen_attributes = TokenStream::new();
for attribute in &attributes.attributes {
if let Attribute::Group(identifier, attribute) = attribute {
let path = format!("ligen_{identifier}::ligen_{identifier}", identifier = identifier.name);
let path = Path::from(path);
dependencies.append_all(quote! {
use #path;
});
ligen_attributes.append_all(quote! {
#identifier(#attribute),
})
}
}
let ligen_attributes = quote! {
#[ligen(#ligen_attributes)]
};
quote! {
pub mod ffi {
use std::ffi::CStr;
use std::os::raw::c_char;
use ligen::ligen;
#dependencies
pub struct CChar(*const c_char);
impl From<CChar> for String {
fn from(cchar: CChar) -> Self {
unsafe { CStr::from_ptr(cchar.0).to_str().unwrap().to_string() }
}
}
pub struct RString(std::ffi::CString);
#ligen_attributes
impl RString {
pub fn new(string: *const c_char) -> Self {
string.into()
}
pub fn as_ptr(&self) -> *const c_char {
self.0.as_ptr()
}
}
impl From<String> for RString {
fn from(string: String) -> Self {
let string = std::ffi::CString::new(string).expect("Couldn't create CString.");
Self(string)
}
}
impl From<RString> for String {
fn from(string: RString) -> Self {
string.0.to_string_lossy().to_string()
}
}
impl From<*const c_char> for RString {
fn from(c_char: *const c_char) -> Self {
unsafe {
let string = std::ffi::CString::new(
std::ffi::CStr::from_ptr(c_char)
.to_string_lossy()
.to_string(),
).expect("Failed to create RString.");
Self(string)
}
}
}
}
}
}