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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation,
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use anyhow::{anyhow, Context};
use proc_macro2::Ident;
use quote::ToTokens;
use syn::punctuated::Punctuated;
use syn::{
parse_quote,
FnArg,
ForeignItem,
ForeignItemFn,
ForeignItemType,
GenericArgument,
ItemEnum,
ItemForeignMod,
Pat,
PatIdent,
PathArguments,
PathSegment,
Receiver,
ReturnType,
Token,
TraitBound,
Type,
TypeParamBound,
TypeReference,
TypeTraitObject,
};
pub use crate::binding_types::*;
use crate::cpp::exception_class_name;
use crate::enum_helpers::is_primitive_enum;
use crate::ordered_hash_set::OrderedHashSet;
use crate::utils::{is_primitive, BuildContext};
/// The structure keeps the Rust types wrappers,
/// methods of the structures and global functions
/// signatures. `user_custom_types` is a subset
/// of `rust_types_wrappers`, since the latter collection
/// keeps all the wrappers that will be handled, and the
/// first one keeps only a user defined types wrappers
/// along with their methods.
///
pub struct ExternModuleTranslator {
pub shared_enums: HashSet<ItemEnum>,
pub exception_names: HashSet<String>,
pub rust_types_wrappers: OrderedHashSet<WrapperType>,
pub user_custom_types: HashMap<WrapperType, Vec<Function>>,
pub user_traits: HashMap<WrapperType, Vec<Function>>,
pub global_functions: Vec<Function>,
pub exception_trait_methods: HashSet<Function>,
}
impl ExternModuleTranslator {
pub fn new(shared_enums: HashSet<ItemEnum>) -> Self {
let mut rust_types_wrappers = OrderedHashSet::default();
shared_enums
.iter()
.for_each(|enum_item| rust_types_wrappers.insert(parse_enum_wrapper(enum_item)));
Self {
shared_enums,
rust_types_wrappers,
exception_names: Default::default(),
user_custom_types: Default::default(),
user_traits: Default::default(),
global_functions: Default::default(),
exception_trait_methods: Default::default(),
}
}
/// Takes extern "Rust" module and translates its functions.
/// It also stores information about the functions signatures
/// for a further processing.
///
pub fn parse_items_in_extern_rust_module(
&mut self,
extern_module: &ItemForeignMod,
context: &BuildContext,
) -> anyhow::Result<()> {
extern_module
.items
.iter()
.filter(|extern_item| match extern_item {
ForeignItem::Fn(function) => context.check_cfg_attrs(&function.attrs),
ForeignItem::Type(type_) => context.check_cfg_attrs(&type_.attrs),
_ => true,
})
.try_for_each(|extern_item| match extern_item {
ForeignItem::Fn(function) => self.register_new_rust_function(function),
ForeignItem::Type(ForeignItemType { ident, .. }) => {
self.register_custom_type(ident);
Ok(())
}
_ => Ok(()),
})
}
/// Takes extern "Traits" module and translates its functions.
/// It also stores information about the functions signatures
/// for a further processing.
///
pub fn translate_trait_external_modules(
&mut self,
extern_module: &ItemForeignMod,
context: &BuildContext,
) -> anyhow::Result<()> {
extern_module
.items
.iter()
.filter(|extern_item| match extern_item {
ForeignItem::Fn(function) => context.check_cfg_attrs(&function.attrs),
_ => true,
})
.try_for_each(|extern_item| match extern_item {
ForeignItem::Fn(original_function) => {
let (associated_structure, function) =
self.translate_function(original_function)?;
if let Some(custom_trait) = associated_structure {
self.user_traits
.entry(custom_trait)
.or_default()
.push(function);
Ok(())
} else {
Err(anyhow!(
"Global functions are not supported in extern \"Traits\"."
))
}
}
_ => Ok(()),
})
}
/// Takes extern "ExceptionTrait" module and translates its methods.
/// It also stores information about the functions signatures
/// for a further processing.
///
pub fn translate_exception_trait_external_module(
&mut self,
extern_module: &ItemForeignMod,
context: &BuildContext,
) -> anyhow::Result<()> {
extern_module
.items
.iter()
.filter(|extern_item| match extern_item {
ForeignItem::Fn(function) => context.check_cfg_attrs(&function.attrs),
_ => true,
})
.try_for_each(|extern_item| match extern_item {
ForeignItem::Fn(function) => {
let method = self.translate_exception_trait_function(function)?;
self.exception_trait_methods.insert(method);
Ok(())
}
_ => Err(anyhow!(
"Only functions are acceptable in `ExceptionsTrait`"
)),
})
}
/// Method stores a wrapper to a custom user's type.
/// Can be used while parsing `type SomeUserType;`
/// to register a new type `RustUserType` in
/// the collection of intermediate-form wrappers.
///
fn register_custom_type(&mut self, original_type_name: &Ident) -> WrapperType {
let new_wrapper_type = WrapperType {
original_type_name: parse_quote!( #original_type_name ),
wrapper_name: original_type_name.to_string(),
rust_type: RustWrapperType::Custom,
reference_parameters: None,
};
self.rust_types_wrappers.insert(new_wrapper_type.clone());
if let Entry::Vacant(entry) = self.user_custom_types.entry(new_wrapper_type.clone()) {
entry.insert(vec![]);
};
new_wrapper_type
}
/// Example:
/// `fn foo(self: &SomeType) -> Result<AnotherType>` ==>
/// `fn foo(self: &SomeType) -> ResultAnotherType`.
///
/// The method takes the Rust function signature and
/// registers every type as a `WrapperType` as well as
/// translates it into inner function form `Function`.
/// If the type has a `self` argument it returns its
/// WrapperType in the result.
///
/// Example:
/// ```rust
/// use syn::{ForeignItemFn, parse_quote};
/// use rusty_bind_parser::extern_module_translator::*;
///
///
/// let mut local_module_translator = ExternModuleTranslator::new(Default::default());
/// let function: ForeignItemFn = parse_quote! { fn foo(self: &SomeType, a: u32) -> Option<u32>; };
/// if let (Some(associated_type), Function {
/// arguments,
/// return_type: Some(return_type),
/// name,
/// }) = local_module_translator.translate_function(&function).unwrap() {
/// assert!(name == "foo");
/// assert!(arguments.len() == 2);
/// assert!(arguments[0] == Arg {arg_name: "self".to_owned(), typ: WrapperType {
/// original_type_name: parse_quote! { SomeType },
/// wrapper_name: "SomeType".to_owned(),
/// rust_type: RustWrapperType::Custom,
/// reference_parameters: Some(ReferenceParameters::shared())
/// }});
/// assert!(arguments[1] == Arg {arg_name: "a".to_owned(), typ: WrapperType {
/// original_type_name: parse_quote! { u32 },
/// wrapper_name: "u32".to_owned(),
/// rust_type: RustWrapperType::Primitive,
/// reference_parameters: None,
/// }});
/// assert!(associated_type == WrapperType {
/// original_type_name: parse_quote! { SomeType },
/// wrapper_name: "SomeType".to_owned(),
/// rust_type: RustWrapperType::Custom ,
/// reference_parameters: Some(ReferenceParameters::shared())
/// });
/// println!("{return_type:?}");
/// assert!(return_type == WrapperType {
/// original_type_name: parse_quote! { Option<u32> },
/// wrapper_name: "Optionalu32".to_owned(),
/// rust_type: RustWrapperType::Option(
/// WrapperType {
/// original_type_name: parse_quote! { u32 },
/// wrapper_name: "u32".to_owned(),
/// rust_type: RustWrapperType::Primitive,
/// reference_parameters: None,
/// }.boxed()
/// ),
/// reference_parameters: None,
/// });
/// } else {
/// panic!("Translated function doesn't match.");
/// }
/// ```
///
pub fn translate_function(
&mut self,
function: &ForeignItemFn,
) -> anyhow::Result<(Option<WrapperType>, Function)> {
let mut arguments = vec![];
let mut associated_structure = None;
function
.sig
.inputs
.iter()
.try_for_each(|argument| match argument {
FnArg::Typed(argument) => {
let new_wrapper_type = self
.parse_and_register_rust_type(&argument.ty)
.with_context(|| {
format!(
"Unsupported type in function signature: {}",
function.sig.ident
)
})?;
// TODO WILX-184
if new_wrapper_type.rust_type == RustWrapperType::DataEnum {
return Err(anyhow!(
"Data carrying enums as functions arguments are not supported yet!"
));
};
if let Pat::Ident(PatIdent { ident, .. }) = argument.pat.as_ref() {
arguments.push(Arg {
arg_name: ident.to_string(),
typ: new_wrapper_type,
});
}
Ok(())
}
FnArg::Receiver(argument) => {
let new_wrapper_type = self
.parse_and_register_rust_type(&argument.ty)
.with_context(|| {
format!(
"Unsupported type in function signature: {}",
function.sig.ident
)
})?;
// TODO WILX-184
if new_wrapper_type.rust_type == RustWrapperType::DataEnum {
return Err(anyhow!(
"Data carrying enums as functions arguments are not supported yet!"
));
};
arguments.push(Arg {
arg_name: "self".to_string(),
typ: new_wrapper_type.clone(),
});
associated_structure = Some(new_wrapper_type);
Ok(())
}
})?;
let return_type = self.translate_return_type(function)?;
let function_name = function.sig.ident.clone();
Ok((
associated_structure,
Function {
arguments,
return_type,
name: function_name.to_string(),
},
))
}
fn translate_exception_trait_function(
&mut self,
function: &ForeignItemFn,
) -> anyhow::Result<Function> {
if function.sig.inputs.len() != 1 {
Err(anyhow!(
"Methods of ExceptionTrait must have only one argument: &self"
))
} else if let FnArg::Receiver(Receiver {
reference: Some((_, None)),
..
}) = function.sig.inputs.first().unwrap()
{
let return_type = self.translate_return_type(function)?;
let associated_structure = WrapperType {
original_type_name: parse_quote! {ExceptionTrait},
wrapper_name: "ExceptionTrait".to_string(),
rust_type: RustWrapperType::ExceptionTrait,
reference_parameters: Some(ReferenceParameters::shared()),
};
self.rust_types_wrappers
.insert(associated_structure.clone());
Ok(Function {
arguments: vec![Arg {
arg_name: "self".to_owned(),
typ: associated_structure,
}],
return_type,
name: function.sig.ident.to_string(),
})
} else {
Err(anyhow!(
"Methods of ExceptionTrait must have argument &self"
))
}
}
fn translate_return_type(
&mut self,
function: &ForeignItemFn,
) -> anyhow::Result<Option<WrapperType>> {
Ok(if let ReturnType::Type(_, typ) = &function.sig.output {
let new_wrapper_type = self.parse_and_register_rust_type(typ).with_context(|| {
format!(
"Unsupported return type in function `{}`",
function.sig.ident.clone(),
)
})?;
Some(new_wrapper_type)
} else {
None
})
}
/// Method registers the function in the local state of ExternModuleTranslator:
/// * function signature
/// * every type used in arguments and return statement
///
fn register_new_rust_function(&mut self, function: &ForeignItemFn) -> anyhow::Result<()> {
let (associated_structure, result_function) = self.translate_function(function)?;
if let Some(custom_type) = associated_structure {
self.user_custom_types
.entry(custom_type)
.or_default()
.push(result_function);
} else {
self.global_functions.push(result_function)
}
Ok(())
}
/// Translates <T> into T.
/// Example:
/// * <Result<u8>> --> Result<u8>
///
fn get_inner_generic_type(path_segment: &PathSegment) -> anyhow::Result<&Type> {
match &path_segment.arguments {
PathArguments::AngleBracketed(args) => args
.args
.first()
.with_context(|| format!("Unsupported generic definition: `{path_segment:?}`"))
.and_then(|generic_argument| match generic_argument {
GenericArgument::Type(typ) => Ok(typ),
_ => Err(anyhow!(
"Unsupported generic definition: `{path_segment:?}`"
)),
}),
_ => Err(anyhow!(
"Expected inner generic type specification: `{path_segment:?}`"
)),
}
}
/// Extracts inner generic types.
/// Example:
/// * Result<u8, i32> --> vec[u8, i32]
///
fn get_inner_generic_types(path_segment: &PathSegment) -> anyhow::Result<Vec<&Type>> {
match &path_segment.arguments {
PathArguments::AngleBracketed(args) => args
.args
.iter()
.map(|generic_argument| match generic_argument {
GenericArgument::Type(typ) => Ok(typ),
_ => Err(anyhow!("Unsupported generic type")),
})
.collect(),
_ => panic!("get_inner_generic_types called in bad context"),
}
}
/// Checks if the type is `&dyn Trait` and returns a proper WrapperType in
/// such a case.
///
fn translate_trait_wrapper_type(
&self,
bounds: &Punctuated<TypeParamBound, Token![+]>,
reference_parameters: Option<ReferenceParameters>,
) -> anyhow::Result<WrapperType> {
bounds
.first()
.and_then(|trait_token| {
if let TypeParamBound::Trait(TraitBound { path, .. }) = trait_token {
path.segments.first().map(|path_segment| {
let new_wrapper_type = WrapperType {
original_type_name: parse_quote!( #path ),
wrapper_name: path_segment.ident.to_string(),
rust_type: RustWrapperType::Trait,
reference_parameters,
};
Ok(new_wrapper_type)
})
} else {
Some(Err(anyhow!(
"Lifetimes in TraitObject `{bounds:?}` are not supported"
)))
}
})
.unwrap_or_else(|| {
Err(anyhow!(
"Problem occurred during parsing the &dyn type: Empty type `{bounds:?}`"
))
})
}
fn parse_rust_exceptions_type(&mut self, typ: &Type) -> anyhow::Result<WrapperType> {
match typ {
Type::Path(path) => path
.path
.segments
.first()
.context("Invalid enum indicating possible exceptions")
.and_then(|path_segment| {
let enum_ident = &path_segment.ident;
let enum_item = self
.get_enum(enum_ident.to_string().as_str())
.context("Result's 2nd argument must be an enum's ident.")?;
let exc_variants = enum_item
.variants
.iter()
.map(|v| v.ident.clone())
.collect::<Vec<_>>();
let exception_wrapper = WrapperType {
original_type_name: typ.clone(),
wrapper_name: enum_ident.to_string(),
rust_type: if is_primitive_enum(enum_item) {
RustWrapperType::Exceptions(Exceptions::Primitive(exc_variants.clone()))
} else {
RustWrapperType::Exceptions(Exceptions::NonPrimitive(
exc_variants.clone(),
))
},
reference_parameters: None,
};
self.exception_names.extend(
exc_variants
.iter()
.map(|variant_ident| exception_class_name(enum_ident, variant_ident)),
);
self.rust_types_wrappers.insert(exception_wrapper.clone());
Ok(exception_wrapper)
}),
_ => Err(anyhow!("Could not parse exception type")),
}
}
/// Method takes a type (for instance `Arc<Mutex<dyn SomeCustomType>>`)
/// and creates one or more intermediate-form wrappers which are remembered in ExternModuleTranslator.
/// Example:
/// The following wrappers are created out of Result<Arc<Mutex<dyn SomeCustomType>>>:
/// * ResultSharedMutexSomeCustomType - Result<Arc<Mutex<dyn SomeCustomType>>>
/// * SharedMutexSomeCustomType - Arc<Mutex<dyn SomeCustomType>>
///
/// Note: This method is called recursively for Results, Options and Vectors,
/// but for `Arc<T>` and `Rc<T>` the `T` is transparent for the parser.
///
fn parse_and_register_rust_type(&mut self, typ: &Type) -> anyhow::Result<WrapperType> {
match typ {
Type::Path(path) => {
path.path
.segments
.first()
.with_context(|| format!("Unsupported type `{typ:?}`"))
.and_then(|path_segment| {
let ident_str = path_segment.ident.to_string();
let new_wrapper_type = if let Some(enum_item) = self.get_enum(&ident_str) {
parse_enum_wrapper(enum_item)
} else if is_primitive(&ident_str) {
parse_primitive_wrapper(typ.clone(), &ident_str)
} else {
match ident_str.as_ref() {
"Result" => self.parse_result_wrapper(typ.clone(), path_segment)?,
"Option" => self.parse_option_wrapper(typ.clone(), path_segment)?,
"Box" => self.parse_box_wrapper(path_segment)?,
"Vec" => self.parse_vec_wrapper(typ.clone(), path_segment)?,
"Arc" => parse_arc_wrapper(typ.clone(), path_segment)?,
"String" => parse_string_wrapper(typ.clone()),
_ => parse_custom_wrapper(typ.clone(), path_segment),
}
};
// The following additional `Option<T>` type is used by
// the `Vec<T>::get(..) -> Option<T>;` function:
if let RustWrapperType::Vector(inner_type) = &new_wrapper_type.rust_type {
let inner_type_original = &inner_type.original_type_name;
let option_wrapper = WrapperType {
original_type_name: parse_quote! { Option<#inner_type_original> },
wrapper_name: format!("Optional{}", &inner_type.wrapper_name),
rust_type: RustWrapperType::Option(inner_type.clone().boxed()),
reference_parameters: None,
};
self.rust_types_wrappers.insert(option_wrapper);
}
self.rust_types_wrappers.insert(new_wrapper_type.clone());
Ok(new_wrapper_type)
})
}
Type::Reference(TypeReference {
elem,
mutability,
lifetime,
..
}) => {
let reference_parameters = Some(ReferenceParameters {
is_mut: mutability.is_some(),
is_static: lifetime
.as_ref()
.map_or(false, |lifetime| lifetime.ident == "static"),
});
if let Type::TraitObject(TypeTraitObject { bounds, .. }) = elem.as_ref() {
let new_wrapper_type =
self.translate_trait_wrapper_type(bounds, reference_parameters)?;
self.rust_types_wrappers.insert(new_wrapper_type.clone());
Ok(new_wrapper_type)
} else {
let wrapper = self.parse_and_register_rust_type(elem.as_ref());
wrapper.map(|wrapper| WrapperType {
reference_parameters,
..wrapper
})
}
}
_ => Err(anyhow!("Unsupported type `{typ:?}`")),
}
}
fn parse_result_wrapper(
&mut self,
original_type: Type,
path_segment: &PathSegment,
) -> anyhow::Result<WrapperType> {
ExternModuleTranslator::get_inner_generic_types(path_segment).and_then(|generic_types| {
let ok_type = self.parse_and_register_rust_type(
generic_types
.get(0)
.context("Result should have 2 generic types")?,
)?;
let exceptions_type = self.parse_rust_exceptions_type(
generic_types
.get(1)
.context("Result should have 2 generic types")?,
)?;
Ok(WrapperType {
original_type_name: original_type,
wrapper_name: format!(
"{}ResultWith{}",
&ok_type.wrapper_name, &exceptions_type.wrapper_name
),
rust_type: RustWrapperType::Result(ok_type.boxed(), exceptions_type.boxed()),
reference_parameters: None,
})
})
}
fn parse_option_wrapper(
&mut self,
original_type: Type,
path_segment: &PathSegment,
) -> anyhow::Result<WrapperType> {
ExternModuleTranslator::get_inner_generic_type(path_segment)
.and_then(|inner_path| self.parse_and_register_rust_type(inner_path))
.map(|inner_type_name| WrapperType {
original_type_name: original_type,
wrapper_name: format!("Optional{}", &inner_type_name.wrapper_name),
rust_type: RustWrapperType::Option(inner_type_name.boxed()),
reference_parameters: None,
})
}
fn parse_box_wrapper(&self, path_segment: &PathSegment) -> anyhow::Result<WrapperType> {
ExternModuleTranslator::get_inner_generic_type(path_segment).and_then(|inner_path| {
if let Type::TraitObject(TypeTraitObject { bounds, .. }) = inner_path {
self.translate_trait_wrapper_type(bounds, None)
} else {
Err(anyhow!("invalid Box inner type"))
}
})
}
fn parse_vec_wrapper(
&mut self,
original_type: Type,
path_segment: &PathSegment,
) -> anyhow::Result<WrapperType> {
ExternModuleTranslator::get_inner_generic_type(path_segment)
.and_then(|inner_path| self.parse_and_register_rust_type(inner_path))
.map(|inner_type_name| WrapperType {
original_type_name: original_type,
wrapper_name: format!("Vec{}", &inner_type_name.wrapper_name),
rust_type: RustWrapperType::Vector(inner_type_name.boxed()),
reference_parameters: None,
})
}
pub fn get_enum(&self, ident_str: &str) -> Option<&ItemEnum> {
self.shared_enums
.iter()
.find(|enum_item| enum_item.ident == ident_str)
}
}
fn parse_arc_wrapper(
original_type: Type,
path_segment: &PathSegment,
) -> anyhow::Result<WrapperType> {
ExternModuleTranslator::get_inner_generic_type(path_segment).map(|inner_path| {
let generated_inner_type_name = inner_path
.to_token_stream()
.to_string()
.replace("dyn", "")
.replace(['<', '>', ' '], "");
WrapperType {
original_type_name: original_type,
wrapper_name: format!("Shared{}", &generated_inner_type_name),
rust_type: if generated_inner_type_name.starts_with("Mutex") {
RustWrapperType::ArcMutex
} else {
RustWrapperType::Arc
},
reference_parameters: None,
}
})
}
fn parse_string_wrapper(original_type: Type) -> WrapperType {
WrapperType {
original_type_name: original_type,
wrapper_name: "RustString".to_string(),
rust_type: RustWrapperType::String,
reference_parameters: None,
}
}
fn parse_primitive_wrapper(original_type: Type, primitive: &str) -> WrapperType {
WrapperType {
original_type_name: original_type,
wrapper_name: primitive.to_owned(),
rust_type: RustWrapperType::Primitive,
reference_parameters: None,
}
}
fn parse_custom_wrapper(original_type: Type, path_segment: &PathSegment) -> WrapperType {
WrapperType {
original_type_name: original_type,
wrapper_name: path_segment.ident.to_string(),
rust_type: RustWrapperType::Custom,
reference_parameters: None,
}
}
fn parse_enum_wrapper(enum_item: &ItemEnum) -> WrapperType {
let ident = &enum_item.ident;
WrapperType {
original_type_name: parse_quote! {#ident},
wrapper_name: ident.to_string(),
rust_type: if is_primitive_enum(enum_item) {
RustWrapperType::FieldlessEnum
} else {
RustWrapperType::DataEnum
},
reference_parameters: None,
}
}
pub fn exception_wrapper_name(enum_ident: &str) -> String {
format!("{}Exceptions", &enum_ident)
}