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 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
use proc_macro2::Span;
use quote::ToTokens;
use serde::{Deserialize, Serialize};
use syn::{punctuated::Punctuated, *};
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::fmt;
use std::ops::ControlFlow;
use super::{
Attrs, Docs, Enum, Ident, Lifetime, LifetimeEnv, LifetimeTransitivity, Method, NamedLifetime,
OpaqueStruct, Path, RustLink, Struct,
};
use crate::Env;
/// A type declared inside a Diplomat-annotated module.
#[derive(Clone, Serialize, Debug, Hash, PartialEq, Eq)]
#[non_exhaustive]
pub enum CustomType {
/// A non-opaque struct whose fields will be visible across the FFI boundary.
Struct(Struct),
/// A struct annotated with [`diplomat::opaque`] whose fields are not visible.
Opaque(OpaqueStruct),
/// A fieldless enum.
Enum(Enum),
}
impl CustomType {
/// Get the name of the custom type, which is unique within a module.
pub fn name(&self) -> &Ident {
match self {
CustomType::Struct(strct) => &strct.name,
CustomType::Opaque(strct) => &strct.name,
CustomType::Enum(enm) => &enm.name,
}
}
/// Get the methods declared in impls of the custom type.
pub fn methods(&self) -> &Vec<Method> {
match self {
CustomType::Struct(strct) => &strct.methods,
CustomType::Opaque(strct) => &strct.methods,
CustomType::Enum(enm) => &enm.methods,
}
}
pub fn attrs(&self) -> &Attrs {
match self {
CustomType::Struct(strct) => &strct.attrs,
CustomType::Opaque(strct) => &strct.attrs,
CustomType::Enum(enm) => &enm.attrs,
}
}
/// The name of the destructor in C
pub fn dtor_name(&self) -> String {
let name = self.attrs().abi_rename.apply(self.name().as_str().into());
format!("{name}_destroy")
}
/// Get the doc lines of the custom type.
pub fn docs(&self) -> &Docs {
match self {
CustomType::Struct(strct) => &strct.docs,
CustomType::Opaque(strct) => &strct.docs,
CustomType::Enum(enm) => &enm.docs,
}
}
/// Get all rust links on this type and its methods
pub fn all_rust_links(&self) -> impl Iterator<Item = &RustLink> + '_ {
[self.docs()]
.into_iter()
.chain(self.methods().iter().map(|m| m.docs()))
.flat_map(|d| d.rust_links().iter())
}
pub fn self_path(&self, in_path: &Path) -> Path {
in_path.sub_path(self.name().clone())
}
/// Get the lifetimes of the custom type.
pub fn lifetimes(&self) -> Option<&LifetimeEnv> {
match self {
CustomType::Struct(strct) => Some(&strct.lifetimes),
CustomType::Opaque(strct) => Some(&strct.lifetimes),
CustomType::Enum(_) => None,
}
}
}
/// A symbol declared in a module, which can either be a pointer to another path,
/// or a custom type defined directly inside that module
#[derive(Clone, Serialize, Debug)]
#[non_exhaustive]
pub enum ModSymbol {
/// A symbol that is a pointer to another path.
Alias(Path),
/// A symbol that is a submodule.
SubModule(Ident),
/// A symbol that is a custom type.
CustomType(CustomType),
}
/// A named type that is just a path, e.g. `std::borrow::Cow<'a, T>`.
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub struct PathType {
pub path: Path,
pub lifetimes: Vec<Lifetime>,
}
impl PathType {
pub fn to_syn(&self) -> syn::TypePath {
let mut path = self.path.to_syn();
if !self.lifetimes.is_empty() {
if let Some(seg) = path.segments.last_mut() {
let lifetimes = &self.lifetimes;
seg.arguments =
syn::PathArguments::AngleBracketed(syn::parse_quote! { <#(#lifetimes),*> });
}
}
syn::TypePath { qself: None, path }
}
pub fn new(path: Path) -> Self {
Self {
path,
lifetimes: vec![],
}
}
/// Get the `Self` type from a struct declaration.
///
/// Consider the following struct declaration:
/// ```
/// struct RefList<'a> {
/// data: &'a i32,
/// next: Option<Box<Self>>,
/// }
/// ```
/// When determining what type `Self` is in the `next` field, we would have to call
/// this method on the `syn::ItemStruct` that represents this struct declaration.
/// This method would then return a `PathType` representing `RefList<'a>`, so we
/// know that's what `Self` should refer to.
///
/// The reason this function exists though is so when we convert the fields' types
/// to `PathType`s, we don't panic. We don't actually need to write the struct's
/// field types expanded in the macro, so this function is more for correctness,
pub fn extract_self_type(strct: &syn::ItemStruct) -> Self {
let self_name = (&strct.ident).into();
PathType {
path: Path {
elements: vec![self_name],
},
lifetimes: strct
.generics
.lifetimes()
.map(|lt_def| (<_def.lifetime).into())
.collect(),
}
}
/// If this is a [`TypeName::Named`], grab the [`CustomType`] it points to from
/// the `env`, which contains all [`CustomType`]s across all FFI modules.
///
/// Also returns the path the CustomType is in (useful for resolving fields)
pub fn resolve_with_path<'a>(&self, in_path: &Path, env: &'a Env) -> (Path, &'a CustomType) {
let local_path = &self.path;
let mut cur_path = in_path.clone();
for (i, elem) in local_path.elements.iter().enumerate() {
match elem.as_str() {
"crate" => {
// TODO(#34): get the name of enclosing crate from env when we support multiple crates
cur_path = Path::empty()
}
"super" => cur_path = cur_path.get_super(),
o => match env.get(&cur_path, o) {
Some(ModSymbol::Alias(p)) => {
let mut remaining_elements: Vec<Ident> =
local_path.elements.iter().skip(i + 1).cloned().collect();
let mut new_path = p.elements.clone();
new_path.append(&mut remaining_elements);
return PathType::new(Path { elements: new_path })
.resolve_with_path(&cur_path.clone(), env);
}
Some(ModSymbol::SubModule(name)) => {
cur_path.elements.push(name.clone());
}
Some(ModSymbol::CustomType(t)) => {
if i == local_path.elements.len() - 1 {
return (cur_path, t);
} else {
panic!(
"Unexpected custom type when resolving symbol {} in {}",
o,
cur_path.elements.join("::")
)
}
}
None => panic!(
"Could not resolve symbol {} in {}",
o,
cur_path.elements.join("::")
),
},
}
}
panic!(
"Path {} does not point to a custom type",
in_path.elements.join("::")
)
}
/// If this is a [`TypeName::Named`], grab the [`CustomType`] it points to from
/// the `env`, which contains all [`CustomType`]s across all FFI modules.
///
/// If you need to resolve struct fields later, call [`Self::resolve_with_path()`] instead
/// to get the path to resolve the fields in.
pub fn resolve<'a>(&self, in_path: &Path, env: &'a Env) -> &'a CustomType {
self.resolve_with_path(in_path, env).1
}
}
impl From<&syn::TypePath> for PathType {
fn from(other: &syn::TypePath) -> Self {
let lifetimes = other
.path
.segments
.last()
.and_then(|last| {
if let PathArguments::AngleBracketed(angle_generics) = &last.arguments {
Some(
angle_generics
.args
.iter()
.map(|generic_arg| match generic_arg {
GenericArgument::Lifetime(lifetime) => lifetime.into(),
_ => panic!("generic type arguments are unsupported"),
})
.collect(),
)
} else {
None
}
})
.unwrap_or_default();
Self {
path: Path::from_syn(&other.path),
lifetimes,
}
}
}
impl From<Path> for PathType {
fn from(other: Path) -> Self {
PathType::new(other)
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
#[allow(clippy::exhaustive_enums)] // there are only two kinds of mutability we care about
pub enum Mutability {
Mutable,
Immutable,
}
impl Mutability {
pub fn to_syn(&self) -> Option<Token![mut]> {
match self {
Mutability::Mutable => Some(syn::token::Mut(Span::call_site())),
Mutability::Immutable => None,
}
}
pub fn from_syn(t: &Option<Token![mut]>) -> Self {
match t {
Some(_) => Mutability::Mutable,
None => Mutability::Immutable,
}
}
/// Returns `true` if `&self` is the mutable variant, otherwise `false`.
pub fn is_mutable(&self) -> bool {
matches!(self, Mutability::Mutable)
}
/// Returns `true` if `&self` is the immutable variant, otherwise `false`.
pub fn is_immutable(&self) -> bool {
matches!(self, Mutability::Immutable)
}
/// Shorthand ternary operator for choosing a value based on whether
/// a `Mutability` is mutable or immutable.
///
/// The following pattern (with very slight variations) shows up often in code gen:
/// ```ignore
/// if mutability.is_mutable() {
/// ""
/// } else {
/// "const "
/// }
/// ```
/// This is particularly annoying in `write!(...)` statements, where `cargo fmt`
/// expands it to take up 5 lines.
///
/// This method offers a 1-line alternative:
/// ```ignore
/// mutability.if_mut_else("", "const ")
/// ```
/// For cases where lazy evaluation is desired, consider using a conditional
/// or a `match` statement.
pub fn if_mut_else<T>(&self, if_mut: T, if_immut: T) -> T {
match self {
Mutability::Mutable => if_mut,
Mutability::Immutable => if_immut,
}
}
}
/// A local type reference, such as the type of a field, parameter, or return value.
/// Unlike [`CustomType`], which represents a type declaration, [`TypeName`]s can compose
/// types through references and boxing, and can also capture unresolved paths.
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
#[non_exhaustive]
pub enum TypeName {
/// A built-in Rust scalar primitive.
Primitive(PrimitiveType),
/// An unresolved path to a custom type, which can be resolved after all types
/// are collected with [`TypeName::resolve()`].
Named(PathType),
/// An optionally mutable reference to another type.
Reference(Lifetime, Mutability, Box<TypeName>),
/// A `Box<T>` type.
Box(Box<TypeName>),
/// A `Option<T>` type.
Option(Box<TypeName>),
/// A `Result<T, E>` or `diplomat_runtime::DiplomatWriteable` type. If the bool is true, it's `Result`
Result(Box<TypeName>, Box<TypeName>, bool),
Writeable,
/// A `&DiplomatStr` or `Box<DiplomatStr>` type.
/// Owned strings don't have a lifetime.
StrReference(Option<Lifetime>, StringEncoding),
/// A `&[T]` or `Box<[T]>` type, where `T` is a primitive.
/// Owned slices don't have a lifetime or mutability.
PrimitiveSlice(Option<(Lifetime, Mutability)>, PrimitiveType),
/// `&[&DiplomatStr]`
StrSlice(StringEncoding),
/// The `()` type.
Unit,
/// The `Self` type.
SelfType(PathType),
/// std::cmp::Ordering or core::cmp::Ordering
///
/// The path must be present! Ordering will be parsed as an AST type!
Ordering,
}
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug, Copy)]
#[non_exhaustive]
pub enum StringEncoding {
UnvalidatedUtf8,
UnvalidatedUtf16,
/// The caller guarantees that they're passing valid UTF-8, under penalty of UB
Utf8,
}
impl TypeName {
/// Converts the [`TypeName`] back into an AST node that can be spliced into a program.
pub fn to_syn(&self) -> syn::Type {
match self {
TypeName::Primitive(name) => {
syn::Type::Path(syn::parse_str(PRIMITIVE_TO_STRING.get(name).unwrap()).unwrap())
}
TypeName::Ordering => syn::Type::Path(syn::parse_str("i8").unwrap()),
TypeName::Named(name) | TypeName::SelfType(name) => {
// Self also gets expanded instead of turning into `Self` because
// this code is used to generate the `extern "C"` functions, which
// aren't in an impl block.
syn::Type::Path(name.to_syn())
}
TypeName::Reference(lifetime, mutability, underlying) => {
syn::Type::Reference(TypeReference {
and_token: syn::token::And(Span::call_site()),
lifetime: lifetime.to_syn(),
mutability: mutability.to_syn(),
elem: Box::new(underlying.to_syn()),
})
}
TypeName::Box(underlying) => syn::Type::Path(TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: Punctuated::from_iter(vec![PathSegment {
ident: syn::Ident::new("Box", Span::call_site()),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt(Span::call_site()),
args: Punctuated::from_iter(vec![GenericArgument::Type(
underlying.to_syn(),
)]),
gt_token: syn::token::Gt(Span::call_site()),
}),
}]),
},
}),
TypeName::Option(underlying) => syn::Type::Path(TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: Punctuated::from_iter(vec![PathSegment {
ident: syn::Ident::new("Option", Span::call_site()),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt(Span::call_site()),
args: Punctuated::from_iter(vec![GenericArgument::Type(
underlying.to_syn(),
)]),
gt_token: syn::token::Gt(Span::call_site()),
}),
}]),
},
}),
TypeName::Result(ok, err, true) => syn::Type::Path(TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: Punctuated::from_iter(vec![PathSegment {
ident: syn::Ident::new("Result", Span::call_site()),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt(Span::call_site()),
args: Punctuated::from_iter(vec![
GenericArgument::Type(ok.to_syn()),
GenericArgument::Type(err.to_syn()),
]),
gt_token: syn::token::Gt(Span::call_site()),
}),
}]),
},
}),
TypeName::Result(ok, err, false) => syn::Type::Path(TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: Punctuated::from_iter(vec![
PathSegment {
ident: syn::Ident::new("diplomat_runtime", Span::call_site()),
arguments: PathArguments::None,
},
PathSegment {
ident: syn::Ident::new("DiplomatResult", Span::call_site()),
arguments: PathArguments::AngleBracketed(
AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt(Span::call_site()),
args: Punctuated::from_iter(vec![
GenericArgument::Type(ok.to_syn()),
GenericArgument::Type(err.to_syn()),
]),
gt_token: syn::token::Gt(Span::call_site()),
},
),
},
]),
},
}),
TypeName::Writeable => syn::parse_quote! {
diplomat_runtime::DiplomatWriteable
},
TypeName::StrReference(Some(lifetime), StringEncoding::UnvalidatedUtf8) => {
syn::parse_str(&format!(
"{}DiplomatStr",
ReferenceDisplay(lifetime, &Mutability::Immutable)
))
.unwrap()
}
TypeName::StrReference(Some(lifetime), StringEncoding::UnvalidatedUtf16) => {
syn::parse_str(&format!(
"{}DiplomatStr16",
ReferenceDisplay(lifetime, &Mutability::Immutable)
))
.unwrap()
}
TypeName::StrReference(Some(lifetime), StringEncoding::Utf8) => syn::parse_str(
&format!("{}str", ReferenceDisplay(lifetime, &Mutability::Immutable)),
)
.unwrap(),
TypeName::StrReference(None, StringEncoding::UnvalidatedUtf8) => {
syn::parse_str("Box<DiplomatStr>").unwrap()
}
TypeName::StrReference(None, StringEncoding::UnvalidatedUtf16) => {
syn::parse_str("Box<DiplomatStr16>").unwrap()
}
TypeName::StrReference(None, StringEncoding::Utf8) => {
syn::parse_str("Box<str>").unwrap()
}
TypeName::StrSlice(StringEncoding::UnvalidatedUtf8) => {
syn::parse_str("&[&DiplomatStr]").unwrap()
}
TypeName::StrSlice(StringEncoding::UnvalidatedUtf16) => {
syn::parse_str("&[&DiplomatStr16]").unwrap()
}
TypeName::StrSlice(StringEncoding::Utf8) => syn::parse_str("&[&str]").unwrap(),
TypeName::PrimitiveSlice(Some((lifetime, mutability)), name) => {
let primitive_name = PRIMITIVE_TO_STRING.get(name).unwrap();
let formatted_str = format!(
"{}[{}]",
ReferenceDisplay(lifetime, mutability),
primitive_name
);
syn::parse_str(&formatted_str).unwrap()
}
TypeName::PrimitiveSlice(None, name) => syn::parse_str(&format!(
"Box<[{}]>",
PRIMITIVE_TO_STRING.get(name).unwrap()
))
.unwrap(),
TypeName::Unit => syn::parse_quote! {
()
},
}
}
/// Extract a [`TypeName`] from a [`syn::Type`] AST node.
/// The following rules are used to infer [`TypeName`] variants:
/// - If the type is a path with a single element that is the name of a Rust primitive, returns a [`TypeName::Primitive`]
/// - If the type is a path with a single element [`Box`], returns a [`TypeName::Box`] with the type parameter recursively converted
/// - If the type is a path with a single element [`Option`], returns a [`TypeName::Option`] with the type parameter recursively converted
/// - If the type is a path with a single element `Self` and `self_path_type` is provided, returns a [`TypeName::Named`]
/// - If the type is a path with a single element [`Result`], returns a [`TypeName::Result`] with the type parameters recursively converted
/// - If the type is a path equal to [`diplomat_runtime::DiplomatResult`], returns a [`TypeName::DiplomatResult`] with the type parameters recursively converted
/// - If the type is a path equal to [`diplomat_runtime::DiplomatWriteable`], returns a [`TypeName::Writeable`]
/// - If the type is a owned or borrowed string type, returns a [`TypeName::StrReference`]
/// - If the type is a owned or borrowed slice of a Rust primitive, returns a [`TypeName::PrimitiveSlice`]
/// - If the type is a reference (`&` or `&mut`), returns a [`TypeName::Reference`] with the referenced type recursively converted
/// - Otherwise, assume that the reference is to a [`CustomType`] in either the current module or another one, returns a [`TypeName::Named`]
pub fn from_syn(ty: &syn::Type, self_path_type: Option<PathType>) -> TypeName {
match ty {
syn::Type::Reference(r) => {
let lifetime = Lifetime::from(&r.lifetime);
let mutability = Mutability::from_syn(&r.mutability);
let name = r.elem.to_token_stream().to_string();
if name.starts_with("DiplomatStr") || name == "str" {
if mutability.is_mutable() {
panic!("mutable string references are disallowed");
}
if name == "DiplomatStr" {
return TypeName::StrReference(
Some(lifetime),
StringEncoding::UnvalidatedUtf8,
);
} else if name == "DiplomatStr16" {
return TypeName::StrReference(
Some(lifetime),
StringEncoding::UnvalidatedUtf16,
);
} else if name == "str" {
return TypeName::StrReference(Some(lifetime), StringEncoding::Utf8);
}
}
if let syn::Type::Slice(slice) = &*r.elem {
if let syn::Type::Path(p) = &*slice.elem {
if let Some(primitive) = p
.path
.get_ident()
.and_then(|i| STRING_TO_PRIMITIVE.get(i.to_string().as_str()))
{
return TypeName::PrimitiveSlice(
Some((lifetime, mutability)),
*primitive,
);
}
}
if let TypeName::StrReference(Some(Lifetime::Anonymous), encoding) =
TypeName::from_syn(&slice.elem, self_path_type.clone())
{
return TypeName::StrSlice(encoding);
}
}
TypeName::Reference(
lifetime,
mutability,
Box::new(TypeName::from_syn(r.elem.as_ref(), self_path_type)),
)
}
syn::Type::Path(p) => {
let p_len = p.path.segments.len();
if let Some(primitive) = p
.path
.get_ident()
.and_then(|i| STRING_TO_PRIMITIVE.get(i.to_string().as_str()))
{
TypeName::Primitive(*primitive)
} else if p_len >= 2
&& p.path.segments[p_len - 2].ident == "cmp"
&& p.path.segments[p_len - 1].ident == "Ordering"
{
TypeName::Ordering
} else if p_len == 1 && p.path.segments[0].ident == "Box" {
if let PathArguments::AngleBracketed(type_args) = &p.path.segments[0].arguments
{
if let GenericArgument::Type(syn::Type::Slice(slice)) = &type_args.args[0] {
if let TypeName::Primitive(p) =
TypeName::from_syn(&slice.elem, self_path_type)
{
TypeName::PrimitiveSlice(None, p)
} else {
panic!("Owned slices only support primitives.")
}
} else if let GenericArgument::Type(tpe) = &type_args.args[0] {
if tpe.to_token_stream().to_string() == "DiplomatStr" {
TypeName::StrReference(None, StringEncoding::UnvalidatedUtf8)
} else if tpe.to_token_stream().to_string() == "DiplomatStr16" {
TypeName::StrReference(None, StringEncoding::UnvalidatedUtf16)
} else if tpe.to_token_stream().to_string() == "str" {
TypeName::StrReference(None, StringEncoding::Utf8)
} else {
TypeName::Box(Box::new(TypeName::from_syn(tpe, self_path_type)))
}
} else {
panic!("Expected first type argument for Box to be a type")
}
} else {
panic!("Expected angle brackets for Box type")
}
} else if p_len == 1 && p.path.segments[0].ident == "Option" {
if let PathArguments::AngleBracketed(type_args) = &p.path.segments[0].arguments
{
if let GenericArgument::Type(tpe) = &type_args.args[0] {
TypeName::Option(Box::new(TypeName::from_syn(tpe, self_path_type)))
} else {
panic!("Expected first type argument for Option to be a type")
}
} else {
panic!("Expected angle brackets for Option type")
}
} else if p_len == 1 && p.path.segments[0].ident == "Self" {
if let Some(self_path_type) = self_path_type {
TypeName::SelfType(self_path_type)
} else {
panic!("Cannot have `Self` type outside of a method");
}
} else if p_len == 1 && p.path.segments[0].ident == "Result"
|| is_runtime_type(p, "DiplomatResult")
{
if let PathArguments::AngleBracketed(type_args) =
&p.path.segments.last().unwrap().arguments
{
if let (GenericArgument::Type(ok), GenericArgument::Type(err)) =
(&type_args.args[0], &type_args.args[1])
{
let ok = TypeName::from_syn(ok, self_path_type.clone());
let err = TypeName::from_syn(err, self_path_type);
TypeName::Result(
Box::new(ok),
Box::new(err),
!is_runtime_type(p, "DiplomatResult"),
)
} else {
panic!("Expected both type arguments for Result to be a type")
}
} else {
panic!("Expected angle brackets for Result type")
}
} else if is_runtime_type(p, "DiplomatWriteable") {
TypeName::Writeable
} else {
TypeName::Named(PathType::from(p))
}
}
syn::Type::Tuple(tup) => {
if tup.elems.is_empty() {
TypeName::Unit
} else {
todo!("Tuples are not currently supported")
}
}
other => panic!("Unsupported type: {}", other.to_token_stream()),
}
}
/// Returns `true` if `self` is the `TypeName::SelfType` variant, otherwise
/// `false`.
pub fn is_self(&self) -> bool {
matches!(self, TypeName::SelfType(_))
}
/// Recurse down the type tree, visiting all lifetimes.
///
/// Using this function, you can collect all the lifetimes into a collection,
/// or examine each one without having to make any additional allocations.
pub fn visit_lifetimes<'a, F, B>(&'a self, visit: &mut F) -> ControlFlow<B>
where
F: FnMut(&'a Lifetime, LifetimeOrigin) -> ControlFlow<B>,
{
match self {
TypeName::Named(path_type) | TypeName::SelfType(path_type) => path_type
.lifetimes
.iter()
.try_for_each(|lt| visit(lt, LifetimeOrigin::Named)),
TypeName::Reference(lt, _, ty) => {
ty.visit_lifetimes(visit)?;
visit(lt, LifetimeOrigin::Reference)
}
TypeName::Box(ty) | TypeName::Option(ty) => ty.visit_lifetimes(visit),
TypeName::Result(ok, err, _) => {
ok.visit_lifetimes(visit)?;
err.visit_lifetimes(visit)
}
TypeName::StrReference(Some(lt), ..) => visit(lt, LifetimeOrigin::StrReference),
TypeName::PrimitiveSlice(Some((lt, _)), ..) => {
visit(lt, LifetimeOrigin::PrimitiveSlice)
}
_ => ControlFlow::Continue(()),
}
}
/// Returns `true` if any lifetime satisfies a predicate, otherwise `false`.
///
/// This method is short-circuiting, meaning that if the predicate ever succeeds,
/// it will return immediately.
pub fn any_lifetime<'a, F>(&'a self, mut f: F) -> bool
where
F: FnMut(&'a Lifetime, LifetimeOrigin) -> bool,
{
self.visit_lifetimes(&mut |lifetime, origin| {
if f(lifetime, origin) {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
})
.is_break()
}
/// Returns `true` if all lifetimes satisfy a predicate, otherwise `false`.
///
/// This method is short-circuiting, meaning that if the predicate ever fails,
/// it will return immediately.
pub fn all_lifetimes<'a, F>(&'a self, mut f: F) -> bool
where
F: FnMut(&'a Lifetime, LifetimeOrigin) -> bool,
{
self.visit_lifetimes(&mut |lifetime, origin| {
if f(lifetime, origin) {
ControlFlow::Continue(())
} else {
ControlFlow::Break(())
}
})
.is_continue()
}
/// Returns all lifetimes in a [`LifetimeEnv`] that must live at least as
/// long as the type.
pub fn longer_lifetimes<'env>(
&self,
lifetime_env: &'env LifetimeEnv,
) -> Vec<&'env NamedLifetime> {
self.transitive_lifetime_bounds(LifetimeTransitivity::longer(lifetime_env))
}
/// Returns all lifetimes in a [`LifetimeEnv`] that are outlived by the type.
pub fn shorter_lifetimes<'env>(
&self,
lifetime_env: &'env LifetimeEnv,
) -> Vec<&'env NamedLifetime> {
self.transitive_lifetime_bounds(LifetimeTransitivity::shorter(lifetime_env))
}
/// Visits the provided [`LifetimeTransitivity`] value with all `NamedLifetime`s
/// in the type tree, and returns the transitively reachable lifetimes.
fn transitive_lifetime_bounds<'env>(
&self,
mut transitivity: LifetimeTransitivity<'env>,
) -> Vec<&'env NamedLifetime> {
self.visit_lifetimes(&mut |lifetime, _| -> ControlFlow<()> {
if let Lifetime::Named(named) = lifetime {
transitivity.visit(named);
}
ControlFlow::Continue(())
});
transitivity.finish()
}
pub fn is_zst(&self) -> bool {
// check_zst() prevents non-unit types from being ZSTs
matches!(*self, TypeName::Unit)
}
pub fn is_pointer(&self) -> bool {
matches!(*self, TypeName::Reference(..) | TypeName::Box(_))
}
}
#[non_exhaustive]
pub enum LifetimeOrigin {
Named,
Reference,
StrReference,
PrimitiveSlice,
}
fn is_runtime_type(p: &TypePath, name: &str) -> bool {
(p.path.segments.len() == 1 && p.path.segments[0].ident == name)
|| (p.path.segments.len() == 2
&& p.path.segments[0].ident == "diplomat_runtime"
&& p.path.segments[1].ident == name)
}
impl fmt::Display for TypeName {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TypeName::Primitive(p) => p.fmt(f),
TypeName::Ordering => write!(f, "Ordering"),
TypeName::Named(p) | TypeName::SelfType(p) => p.fmt(f),
TypeName::Reference(lifetime, mutability, typ) => {
write!(f, "{}{typ}", ReferenceDisplay(lifetime, mutability))
}
TypeName::Box(typ) => write!(f, "Box<{typ}>"),
TypeName::Option(typ) => write!(f, "Option<{typ}>"),
TypeName::Result(ok, err, _) => {
write!(f, "Result<{ok}, {err}>")
}
TypeName::Writeable => "DiplomatWriteable".fmt(f),
TypeName::StrReference(Some(lifetime), StringEncoding::UnvalidatedUtf8) => {
write!(
f,
"{}DiplomatStr",
ReferenceDisplay(lifetime, &Mutability::Immutable)
)
}
TypeName::StrReference(Some(lifetime), StringEncoding::UnvalidatedUtf16) => {
write!(
f,
"{}DiplomatStr16",
ReferenceDisplay(lifetime, &Mutability::Immutable)
)
}
TypeName::StrReference(Some(lifetime), StringEncoding::Utf8) => {
write!(
f,
"{}str",
ReferenceDisplay(lifetime, &Mutability::Immutable)
)
}
TypeName::StrReference(None, StringEncoding::UnvalidatedUtf8) => {
write!(f, "Box<DiplomatStr>")
}
TypeName::StrReference(None, StringEncoding::UnvalidatedUtf16) => {
write!(f, "Box<DiplomatStr16>")
}
TypeName::StrReference(None, StringEncoding::Utf8) => {
write!(f, "Box<str>")
}
TypeName::StrSlice(StringEncoding::UnvalidatedUtf8) => {
write!(f, "&[&DiplomatStr]")
}
TypeName::StrSlice(StringEncoding::UnvalidatedUtf16) => {
write!(f, "&[&DiplomatStr16]")
}
TypeName::StrSlice(StringEncoding::Utf8) => {
write!(f, "&[&str]")
}
TypeName::PrimitiveSlice(Some((lifetime, mutability)), typ) => {
write!(f, "{}[{typ}]", ReferenceDisplay(lifetime, mutability))
}
TypeName::PrimitiveSlice(None, typ) => write!(f, "Box<[{typ}]>"),
TypeName::Unit => "()".fmt(f),
}
}
}
/// An [`fmt::Display`] type for formatting Rust references.
///
/// # Examples
///
/// ```ignore
/// let lifetime = Lifetime::from(&syn::parse_str::<syn::Lifetime>("'a"));
/// let mutability = Mutability::Mutable;
/// // ...
/// let fmt = format!("{}[u8]", ReferenceDisplay(&lifetime, &mutability));
///
/// assert_eq!(fmt, "&'a mut [u8]");
/// ```
struct ReferenceDisplay<'a>(&'a Lifetime, &'a Mutability);
impl<'a> fmt::Display for ReferenceDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
Lifetime::Static => "&'static ".fmt(f)?,
Lifetime::Named(lifetime) => write!(f, "&{lifetime} ")?,
Lifetime::Anonymous => '&'.fmt(f)?,
}
if self.1.is_mutable() {
"mut ".fmt(f)?;
}
Ok(())
}
}
impl fmt::Display for PathType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.path.fmt(f)?;
if let Some((first, rest)) = self.lifetimes.split_first() {
write!(f, "<{first}")?;
for lifetime in rest {
write!(f, ", {lifetime}")?;
}
'>'.fmt(f)?;
}
Ok(())
}
}
/// A built-in Rust primitive scalar type.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
#[allow(non_camel_case_types)]
#[allow(clippy::exhaustive_enums)] // there are only these (scalar types)
pub enum PrimitiveType {
i8,
u8,
i16,
u16,
i32,
u32,
i64,
u64,
i128,
u128,
isize,
usize,
f32,
f64,
bool,
char,
/// a primitive byte that is not meant to be interpreted numerically
/// in languages that don't have fine-grained integer types
byte,
}
impl fmt::Display for PrimitiveType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
PrimitiveType::i8 => "i8",
PrimitiveType::u8 | PrimitiveType::byte => "u8",
PrimitiveType::i16 => "i16",
PrimitiveType::u16 => "u16",
PrimitiveType::i32 => "i32",
PrimitiveType::u32 => "u32",
PrimitiveType::i64 => "i64",
PrimitiveType::u64 => "u64",
PrimitiveType::i128 => "i128",
PrimitiveType::u128 => "u128",
PrimitiveType::isize => "isize",
PrimitiveType::usize => "usize",
PrimitiveType::f32 => "f32",
PrimitiveType::f64 => "f64",
PrimitiveType::bool => "bool",
PrimitiveType::char => "char",
}
.fmt(f)
}
}
lazy_static! {
static ref PRIMITIVES_MAPPING: [(&'static str, PrimitiveType); 17] = [
("i8", PrimitiveType::i8),
("u8", PrimitiveType::u8),
("i16", PrimitiveType::i16),
("u16", PrimitiveType::u16),
("i32", PrimitiveType::i32),
("u32", PrimitiveType::u32),
("i64", PrimitiveType::i64),
("u64", PrimitiveType::u64),
("i128", PrimitiveType::i128),
("u128", PrimitiveType::u128),
("isize", PrimitiveType::isize),
("usize", PrimitiveType::usize),
("f32", PrimitiveType::f32),
("f64", PrimitiveType::f64),
("bool", PrimitiveType::bool),
("DiplomatChar", PrimitiveType::char),
("DiplomatByte", PrimitiveType::byte),
];
static ref STRING_TO_PRIMITIVE: HashMap<&'static str, PrimitiveType> =
PRIMITIVES_MAPPING.iter().cloned().collect();
static ref PRIMITIVE_TO_STRING: HashMap<PrimitiveType, &'static str> =
PRIMITIVES_MAPPING.iter().map(|t| (t.1, t.0)).collect();
}
#[cfg(test)]
mod tests {
use insta;
use syn;
use super::TypeName;
#[test]
fn typename_primitives() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
i32
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
usize
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
bool
},
None
));
}
#[test]
fn typename_named() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
MyLocalStruct
},
None
));
}
#[test]
fn typename_references() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
&i32
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
&mut MyLocalStruct
},
None
));
}
#[test]
fn typename_boxes() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Box<i32>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Box<MyLocalStruct>
},
None
));
}
#[test]
fn typename_option() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Option<i32>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Option<MyLocalStruct>
},
None
));
}
#[test]
fn typename_result() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
DiplomatResult<MyLocalStruct, i32>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
DiplomatResult<(), MyLocalStruct>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Result<MyLocalStruct, i32>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Result<(), MyLocalStruct>
},
None
));
}
#[test]
fn lifetimes() {
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Foo<'a, 'b>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
::core::my_type::Foo
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
::core::my_type::Foo<'test>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Option<Ref<'object>>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Foo<'a, 'b, 'c, 'd>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
very::long::path::to::my::Type<'x, 'y, 'z>
},
None
));
insta::assert_yaml_snapshot!(TypeName::from_syn(
&syn::parse_quote! {
Result<OkRef<'a, 'b>, ErrRef<'c>>
},
None
));
}
}