mirror of
https://github.com/nodejs/node.git
synced 2026-11-21 12:59:16 -05:00
deps: update Rust crates for V8 15.5.35.20
Signed-off-by: Joyee Cheung <joyeec9h3@gmail.com> PR-URL: https://github.com/nodejs/node/pull/66537 Reviewed-By: Richard Lau <richard.lau@ibm.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
This commit is contained in:
1 parent
6b28cb0909
commit
d5a8930d0f
662 files changed
+84319
-6622
No files matched your search
+43
-33
@@ -26,23 +26,23 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "diplomat"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"diplomat_core",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "diplomat-runtime"
|
||||
version = "0.15.1"
|
||||
version = "0.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "diplomat_core"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
@@ -50,17 +50,17 @@ dependencies = [
|
||||
"serde",
|
||||
"smallvec",
|
||||
"strck",
|
||||
"syn",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.6"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -112,7 +112,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.2.0"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
@@ -130,7 +130,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider"
|
||||
version = "2.2.0"
|
||||
version = "2.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
@@ -146,7 +146,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ixdtf"
|
||||
version = "0.6.5"
|
||||
version = "0.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
@@ -156,17 +156,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.2"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "node_crates"
|
||||
version = "15.2.124"
|
||||
version = "15.5.35"
|
||||
dependencies = [
|
||||
"icu_locale",
|
||||
"icu_locale_core",
|
||||
"icu_provider",
|
||||
"syn",
|
||||
"syn 3.0.4",
|
||||
"temporal_capi",
|
||||
"temporal_rs",
|
||||
]
|
||||
@@ -181,7 +181,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
@@ -191,7 +191,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
@@ -199,7 +199,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.46"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
@@ -216,7 +216,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
@@ -225,7 +225,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.228"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
@@ -233,12 +233,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.228"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -261,7 +261,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.118"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
@@ -276,12 +286,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "temporal_capi"
|
||||
version = "0.2.4"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"diplomat",
|
||||
@@ -297,7 +307,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "temporal_rs"
|
||||
version = "0.2.4"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"calendrical_calculations",
|
||||
@@ -313,7 +323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "timezone_provider"
|
||||
version = "0.2.4"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"tinystr",
|
||||
@@ -324,7 +334,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.3"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
@@ -344,7 +354,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.3"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
@@ -364,7 +374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
@@ -383,13 +393,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.119",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.4"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
@@ -398,7 +408,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.6"
|
||||
version = "0.11.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"serde",
|
||||
@@ -409,12 +419,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.3"
|
||||
version = "0.11.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Vendored
+5
-5
@@ -3,8 +3,8 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "node_crates"
|
||||
version = "15.2.124"
|
||||
rust-version = "1.86"
|
||||
version = "15.5.35"
|
||||
rust-version = "1.88"
|
||||
|
||||
[lib]
|
||||
crate-type = [ "staticlib" ]
|
||||
@@ -23,14 +23,14 @@ version = "2.2.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.syn]
|
||||
version = "2"
|
||||
version = "3"
|
||||
features = [ "full" ]
|
||||
|
||||
[dependencies.temporal_capi]
|
||||
version = "0.2.4"
|
||||
version = "0.2.6"
|
||||
features = [ "zoneinfo64" ]
|
||||
|
||||
[dependencies.temporal_rs]
|
||||
version = "0.2.4"
|
||||
version = "0.2.6"
|
||||
default-features = false
|
||||
features = [ "float64_representable_durations" ]
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "95557babd58cf90e65c6175e7b9433f41f686bd2"
|
||||
"sha1": "702b1b2289f40ae45c01068eabb9c229b70827e7"
|
||||
},
|
||||
"path_in_vcs": "runtime"
|
||||
}
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
@@ -26,7 +26,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "diplomat-runtime"
|
||||
version = "0.15.1"
|
||||
version = "0.15.2"
|
||||
dependencies = [
|
||||
"jni",
|
||||
"log",
|
||||
@@ -89,15 +89,15 @@ checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.1"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
|
||||
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.94"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
+2
-2
@@ -11,9 +11,9 @@
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.88"
|
||||
name = "diplomat-runtime"
|
||||
version = "0.15.1"
|
||||
version = "0.15.2"
|
||||
authors = [
|
||||
"Shadaj Laddad <shadaj@users.noreply.github.com>",
|
||||
"Manish Goregaokar <manishsmail@gmail.com>",
|
||||
|
||||
+3
-1
@@ -1,7 +1,9 @@
|
||||
[package]
|
||||
name = "diplomat-runtime"
|
||||
description = "Common runtime utilities used by diplomat codegen"
|
||||
version = "0.15.1"
|
||||
# We are working on decoupling diplomat-runtime's version from the rest
|
||||
# https://github.com/rust-diplomat/diplomat/issues/958
|
||||
version = "0.15.2"
|
||||
rust-version.workspace = true
|
||||
authors.workspace = true
|
||||
categories.workspace = true
|
||||
|
||||
@@ -6,6 +6,7 @@ Diplomat supports generating bindings from Rust to:
|
||||
- C++
|
||||
- Dart
|
||||
- Javascript/Typescript
|
||||
- .NET (C#)
|
||||
- Kotlin (using JNA)
|
||||
- Python (using [nanobind](https://nanobind.readthedocs.io/en/latest/index.html))
|
||||
|
||||
|
||||
+19
-1
@@ -1,4 +1,4 @@
|
||||
#![cfg_attr(not(any(target_arch = "wasm32")), no_std)]
|
||||
#![no_std]
|
||||
|
||||
//! The [Diplomat](https://rust-diplomat.github.io/diplomat/) runtime crate.
|
||||
//!
|
||||
@@ -92,6 +92,24 @@ pub unsafe extern "C" fn diplomat_free(ptr: *mut u8, size: usize, align: usize)
|
||||
alloc::alloc::dealloc(ptr, Layout::from_size_align(size, align).unwrap())
|
||||
}
|
||||
|
||||
/// Frees a `Box<[u8]>` that was returned across FFI as a raw `(ptr, len)`
|
||||
/// pair (e.g. via `DiplomatOwnedSlice<u8>`).
|
||||
///
|
||||
/// Primarily to be called by generated FFI bindings, not Rust code, but is available if needed.
|
||||
///
|
||||
/// # Safety
|
||||
/// - `ptr`/`len` must be the raw parts of a `Box<[u8]>` that Rust allocated and handed across
|
||||
/// FFI; this reconstructs that box and drops it, so the same allocator that made it frees it.
|
||||
/// - Must not be called more than once for the same `ptr`.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn diplomat_owned_slice_u8_destroy(ptr: *mut u8, len: usize) {
|
||||
if !ptr.is_null() {
|
||||
drop(alloc::boxed::Box::from_raw(
|
||||
core::ptr::slice_from_raw_parts_mut(ptr, len),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `&[u8]` is a `&str`.
|
||||
///
|
||||
/// Primarily to be called by generated FFI bindings, not Rust code, but is available if needed.
|
||||
|
||||
@@ -47,6 +47,32 @@ impl<T> DiplomatOption<T> {
|
||||
pub fn into_converted_option<U: From<T>>(self) -> Option<U> {
|
||||
self.into_option().map(Into::into)
|
||||
}
|
||||
|
||||
pub fn map<U, F>(mut self, f: F) -> DiplomatOption<U>
|
||||
where
|
||||
F: FnOnce(T) -> U,
|
||||
{
|
||||
if self.is_ok {
|
||||
unsafe {
|
||||
let res = f(ManuallyDrop::take(&mut self.value.ok));
|
||||
DiplomatResult {
|
||||
value: DiplomatResultValue {
|
||||
ok: ManuallyDrop::new(res),
|
||||
},
|
||||
is_ok: true,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unsafe {
|
||||
DiplomatResult {
|
||||
value: DiplomatResultValue {
|
||||
err: self.value.err,
|
||||
},
|
||||
is_ok: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone, E: Clone> Clone for DiplomatResult<T, E> {
|
||||
|
||||
+11
-3
@@ -1,11 +1,17 @@
|
||||
//! Wasm-specific glue code
|
||||
//!
|
||||
//! This is a private module
|
||||
use alloc::format;
|
||||
|
||||
// `std` is only required to support a `panic_handler()` hook in debug builds:
|
||||
#[cfg(debug_assertions)]
|
||||
extern crate std;
|
||||
#[cfg(debug_assertions)]
|
||||
use alloc::{boxed::Box, string::String};
|
||||
|
||||
// https://blog.rust-lang.org/2026/04/04/changes-to-webassembly-targets-and-handling-undefined-symbols/#what-is-going-to-break-and-how-to-fix
|
||||
#[link(wasm_import_module = "env")]
|
||||
extern "C" {
|
||||
#[cfg(debug_assertions)]
|
||||
fn diplomat_throw_error_js(ptr: *const u8, len: usize);
|
||||
|
||||
#[cfg(feature = "log")]
|
||||
@@ -26,12 +32,14 @@ extern "C" {
|
||||
unsafe extern "C" fn diplomat_init() {
|
||||
#[cfg(debug_assertions)]
|
||||
std::panic::set_hook(Box::new(panic_handler));
|
||||
|
||||
#[cfg(feature = "log")]
|
||||
log::set_logger(&ConsoleLogger)
|
||||
.map(|()| log::set_max_level(log::LevelFilter::Debug))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn panic_handler(info: &std::panic::PanicHookInfo) {
|
||||
let msg = match info.payload().downcast_ref::<&'static str>() {
|
||||
Some(&s) => s,
|
||||
@@ -42,13 +50,13 @@ fn panic_handler(info: &std::panic::PanicHookInfo) {
|
||||
};
|
||||
|
||||
let msg = match info.location() {
|
||||
Some(l) => format!(
|
||||
Some(l) => alloc::format!(
|
||||
"wasm panicked at {}:{}:{}:\n{msg}",
|
||||
l.file(),
|
||||
l.line(),
|
||||
l.column(),
|
||||
),
|
||||
None => format!("wasm panicked at <unknown location>:\n{msg}"),
|
||||
None => alloc::format!("wasm panicked at <unknown location>:\n{msg}"),
|
||||
};
|
||||
|
||||
unsafe { diplomat_throw_error_js(msg.as_ptr(), msg.len()) }
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "6559f95efa34658b9e801b45e39f1b306c32e249"
|
||||
},
|
||||
"path_in_vcs": "macro"
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "125df445fc304a116c17fd974712ca2410c8e580"
|
||||
},
|
||||
"path_in_vcs": "macro"
|
||||
}
|
||||
Generated
Vendored
+39
-58
@@ -1,18 +1,23 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.5.0"
|
||||
name = "annotate-snippets"
|
||||
version = "0.12.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
|
||||
checksum = "f211a51805bc641f3ad5b7664c77d2547af685cc33b4cd8d31964027a46f13f1"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
name = "anstyle"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
@@ -28,29 +33,29 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "diplomat"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"diplomat_core",
|
||||
"insta",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"tempfile",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "diplomat_core"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9cf41b94101a4bce993febaf0098092b0bb31deaf0ecaf6e0a2562465f61b383"
|
||||
checksum = "73b18e806f9ecb92df828d080efe47984ae1193958295d4a84fb8b32c9a1aa1b"
|
||||
dependencies = [
|
||||
"annotate-snippets",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"strck",
|
||||
"syn",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -59,22 +64,6 @@ version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984"
|
||||
|
||||
[[package]]
|
||||
name = "insta"
|
||||
version = "1.36.1"
|
||||
@@ -107,26 +96,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.13"
|
||||
name = "memchr"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
|
||||
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.30"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1ccf34da56fc294e7d4ccf69a85992b7dfb826b7cf57bac6a70bba3494cc08a"
|
||||
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"syn",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.94"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
@@ -140,19 +129,6 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
@@ -180,7 +156,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.99",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -216,15 +192,14 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.10.1"
|
||||
name = "syn"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1"
|
||||
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fastrand",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -233,6 +208,12 @@ version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
Vendored
+8
-8
@@ -11,9 +11,9 @@
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.88"
|
||||
name = "diplomat"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
authors = [
|
||||
"Shadaj Laddad <shadaj@users.noreply.github.com>",
|
||||
"Manish Goregaokar <manishsmail@gmail.com>",
|
||||
@@ -38,13 +38,16 @@ categories = [
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/rust-diplomat/diplomat"
|
||||
|
||||
[features]
|
||||
pretty-print = ["diplomat_core/pretty-print"]
|
||||
|
||||
[lib]
|
||||
name = "diplomat"
|
||||
path = "src/lib.rs"
|
||||
proc-macro = true
|
||||
|
||||
[dependencies.diplomat_core]
|
||||
version = "0.15.0"
|
||||
version = "0.16.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.proc-macro2]
|
||||
@@ -54,7 +57,7 @@ version = "1.0.27"
|
||||
version = "1.0"
|
||||
|
||||
[dependencies.syn]
|
||||
version = "2.0"
|
||||
version = "3.0"
|
||||
features = [
|
||||
"full",
|
||||
"extra-traits",
|
||||
@@ -64,7 +67,4 @@ features = [
|
||||
version = "1.7.1"
|
||||
|
||||
[dev-dependencies.prettyplease]
|
||||
version = "0.2.30"
|
||||
|
||||
[dev-dependencies.tempfile]
|
||||
version = "3.2.0"
|
||||
version = "0.3.0"
|
||||
Generated
Vendored
+5
-3
@@ -17,11 +17,13 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
diplomat_core.workspace = true
|
||||
syn = { version = "2.0", features = ["full", "extra-traits"] }
|
||||
syn = { version = "3.0", features = ["full", "extra-traits"] }
|
||||
quote = "1.0"
|
||||
proc-macro2 = "1.0.27"
|
||||
|
||||
[features]
|
||||
pretty-print = ["diplomat_core/pretty-print"]
|
||||
|
||||
[dev-dependencies]
|
||||
insta = "1.7.1"
|
||||
tempfile = "3.2.0"
|
||||
prettyplease = "0.2.30"
|
||||
prettyplease = "0.3.0"
|
||||
Vendored
File renamed without changes.
Vendored
File renamed without changes.
File renamed without changes.
+1
@@ -6,6 +6,7 @@ Diplomat supports generating bindings from Rust to:
|
||||
- C++
|
||||
- Dart
|
||||
- Javascript/Typescript
|
||||
- .NET (C#)
|
||||
- Kotlin (using JNA)
|
||||
- Python (using [nanobind](https://nanobind.readthedocs.io/en/latest/index.html))
|
||||
|
||||
File renamed without changes.
Vendored
+51
-33
@@ -8,7 +8,7 @@
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{quote, ToTokens};
|
||||
use syn::*;
|
||||
use syn::{spanned::Spanned, *};
|
||||
|
||||
use diplomat_core::ast::{self, StdlibOrDiplomat};
|
||||
|
||||
@@ -138,12 +138,12 @@ fn gen_custom_vtable(custom_trait: &ast::Trait, custom_trait_vtable_type: &Ident
|
||||
pub alignment: usize,
|
||||
));
|
||||
for m in &custom_trait.methods {
|
||||
// TODO check that this is the right conversion, it might be the wrong direction
|
||||
let mut param_types: Vec<syn::Type> = m.params.iter().map(|p| param_ty(&p.ty)).collect();
|
||||
let method_name = Ident::new(&format!("run_{}_callback", m.name), Span::call_site());
|
||||
let return_tokens = match &m.output_type {
|
||||
Some(ret_ty) => {
|
||||
let conv_ret_ty = ret_ty.to_syn();
|
||||
let conv_ret_ty = ret_ty.ffi_safe_version().to_syn();
|
||||
|
||||
quote!( -> #conv_ret_ty)
|
||||
}
|
||||
None => {
|
||||
@@ -194,7 +194,16 @@ fn gen_custom_trait_impl(custom_trait: &ast::Trait, custom_trait_struct_name: &I
|
||||
let (return_tokens, end_token) = match &m.output_type {
|
||||
Some(ret_ty) => {
|
||||
let conv_ret_ty = ret_ty.to_syn();
|
||||
(quote!( -> #conv_ret_ty), quote! {})
|
||||
(
|
||||
quote!( -> #conv_ret_ty),
|
||||
match ret_ty {
|
||||
ast::TypeName::Result(_, _, StdlibOrDiplomat::Stdlib)
|
||||
| ast::TypeName::Option(_, StdlibOrDiplomat::Stdlib) => {
|
||||
quote!(.into())
|
||||
}
|
||||
_ => quote!(),
|
||||
},
|
||||
)
|
||||
}
|
||||
None => (quote! {}, quote! {;}),
|
||||
};
|
||||
@@ -328,13 +337,9 @@ fn gen_custom_function(func_info: FuncGen) -> Item {
|
||||
};
|
||||
|
||||
let (return_tokens, maybe_into) = if let Some(return_type) = func_info.return_type {
|
||||
if let ast::TypeName::Result(ok, err, StdlibOrDiplomat::Stdlib) = return_type {
|
||||
let ok = ok.to_syn();
|
||||
let err = err.to_syn();
|
||||
(
|
||||
quote! { -> diplomat_runtime::DiplomatResult<#ok, #err> },
|
||||
quote! { .into() },
|
||||
)
|
||||
if let ast::TypeName::Result(_, _, StdlibOrDiplomat::Stdlib) = return_type {
|
||||
let return_type_syn = return_type.ffi_safe_version().to_syn();
|
||||
(quote! { -> #return_type_syn }, quote! { .into() })
|
||||
} else if let ast::TypeName::StrReference(_, _, StdlibOrDiplomat::Stdlib)
|
||||
| ast::TypeName::StrSlice(.., StdlibOrDiplomat::Stdlib)
|
||||
| ast::TypeName::PrimitiveSlice(_, _, StdlibOrDiplomat::Stdlib) = return_type
|
||||
@@ -358,14 +363,20 @@ fn gen_custom_function(func_info: FuncGen) -> Item {
|
||||
}
|
||||
// anything else goes through DiplomatResult
|
||||
_ => {
|
||||
let ty = ty.to_syn();
|
||||
let ty_s = ty.to_syn();
|
||||
let conversion = if *is_std_option == StdlibOrDiplomat::Stdlib {
|
||||
quote! { .ok_or(()).into() }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
let conversion = if **ty == ast::TypeName::Ordering {
|
||||
quote! { .map(|i| i as i8) #conversion }
|
||||
} else {
|
||||
conversion
|
||||
};
|
||||
(
|
||||
quote! { -> diplomat_runtime::DiplomatResult<#ty, ()> },
|
||||
quote! { -> diplomat_runtime::DiplomatResult<#ty_s, ()> },
|
||||
conversion,
|
||||
)
|
||||
}
|
||||
@@ -450,6 +461,7 @@ impl AttributeInfo {
|
||||
|| seg == "abi_rename"
|
||||
|| seg == "demo"
|
||||
|| seg == "docs"
|
||||
|| seg == "include"
|
||||
{
|
||||
// diplomat-tool reads these, not diplomat::bridge.
|
||||
// throw them away so rustc doesn't complain about unknown attributes
|
||||
@@ -479,7 +491,26 @@ impl AttributeInfo {
|
||||
}
|
||||
|
||||
fn gen_bridge(mut input: ItemMod) -> ItemMod {
|
||||
let module = ast::Module::from_syn(&input, true);
|
||||
// The module cloned for includes only.
|
||||
// This avoids defining multiple items twice (like macros).
|
||||
|
||||
let base = std::env::var("CARGO_MANIFEST_DIR")
|
||||
.expect("Could not read CARGO_MANIFEST_DIR for parsing #[diplomat::include]");
|
||||
let base_path = std::path::Path::new(&base);
|
||||
|
||||
let module_loc = if let Some(f) = input.span().local_file() {
|
||||
// This should generally be the case, it's rare that we're reading from a bridge in a place where there isn't a file.
|
||||
ast::SpanLocation::FilePath(f.to_string_lossy().into())
|
||||
} else {
|
||||
ast::SpanLocation::None
|
||||
};
|
||||
// We do not cache:
|
||||
let module = ast::Module::from_syn(
|
||||
&input,
|
||||
true,
|
||||
Some(ast::ModuleIncludeInfo::new(base_path, None)),
|
||||
&module_loc,
|
||||
);
|
||||
// Clean out any diplomat attributes so Rust doesn't get mad
|
||||
let _attrs = AttributeInfo::extract(&mut input.attrs);
|
||||
let (brace, mut new_contents) = input.content.unwrap();
|
||||
@@ -496,7 +527,7 @@ fn gen_bridge(mut input: ItemMod) -> ItemMod {
|
||||
// are early error messages
|
||||
for field in s.fields.iter_mut() {
|
||||
let _attrs = AttributeInfo::extract(&mut field.attrs);
|
||||
let ty = ast::TypeName::from_syn(&field.ty, None);
|
||||
let ty = ast::TypeName::from_syn(&field.ty, None, &module_loc);
|
||||
if !ty.is_ffi_safe() {
|
||||
let ffisafe = ty.ffi_safe_version();
|
||||
panic!("Found non-FFI safe type inside struct: {ty}, try {ffisafe}");
|
||||
@@ -566,6 +597,9 @@ fn gen_bridge(mut input: ItemMod) -> ItemMod {
|
||||
};
|
||||
}
|
||||
}
|
||||
Item::Trait(t) => {
|
||||
let _attrs = AttributeInfo::extract(&mut t.attrs);
|
||||
}
|
||||
_ => (),
|
||||
});
|
||||
|
||||
@@ -685,23 +719,6 @@ pub fn bridge(
|
||||
proc_macro::TokenStream::from(expanded.to_token_stream())
|
||||
}
|
||||
|
||||
// Config is done in [`diplomat_tool::gen`], so we just set things to be ignored here.
|
||||
#[proc_macro_attribute]
|
||||
pub fn config(
|
||||
_attr: proc_macro::TokenStream,
|
||||
_input: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
"".parse().unwrap()
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn docs(
|
||||
_attr: proc_macro::TokenStream,
|
||||
_input: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
"".parse().unwrap()
|
||||
}
|
||||
|
||||
/// Generate From and Into implementations for a Diplomat enum
|
||||
///
|
||||
/// This is invoked as `#[diplomat::enum_convert(OtherEnumName)]`
|
||||
@@ -788,7 +805,7 @@ macro_rules! expose_attrs {
|
||||
}
|
||||
}
|
||||
|
||||
expose_attrs! {opaque, opaque_mut, attr, demo, skip_private_items}
|
||||
expose_attrs! {opaque, opaque_mut, attr, demo, docs, config, include, skip_private_items}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -805,6 +822,7 @@ mod tests {
|
||||
attrs: vec![],
|
||||
items: vec![item],
|
||||
shebang: None,
|
||||
frontmatter: None,
|
||||
};
|
||||
|
||||
prettyplease::unparse(&file)
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "6559f95efa34658b9e801b45e39f1b306c32e249"
|
||||
},
|
||||
"path_in_vcs": "core"
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
use proc_macro2::Span;
|
||||
use quote::{ToTokens, TokenStreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::{Borrow, Cow};
|
||||
use std::fmt;
|
||||
|
||||
/// An identifier, analogous to `syn::Ident` and `proc_macro2::Ident`.
|
||||
#[derive(Hash, Eq, PartialEq, Serialize, Clone, Debug, Ord, PartialOrd)]
|
||||
#[serde(transparent)]
|
||||
pub struct Ident(Cow<'static, str>);
|
||||
|
||||
impl Ident {
|
||||
/// Validate a string
|
||||
fn validate(string: &str) -> syn::Result<()> {
|
||||
syn::parse_str::<syn::Ident>(string).map(|_| {})
|
||||
}
|
||||
|
||||
/// Attempt to create a new `Ident`.
|
||||
///
|
||||
/// This function fails if the input isn't valid according to
|
||||
/// `proc_macro2::Ident`'s invariants.
|
||||
pub fn try_new(string: String) -> syn::Result<Self> {
|
||||
Self::validate(&string).map(|_| Self(Cow::from(string)))
|
||||
}
|
||||
|
||||
pub fn to_syn(&self) -> syn::Ident {
|
||||
syn::Ident::new(self.as_str(), Span::call_site())
|
||||
}
|
||||
|
||||
/// Get the `&str` representation.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// An [`Ident`] containing "this".
|
||||
pub const THIS: Self = Ident(Cow::Borrowed("this"));
|
||||
}
|
||||
|
||||
impl From<&'static str> for Ident {
|
||||
fn from(string: &'static str) -> Self {
|
||||
Self::validate(string).unwrap();
|
||||
Self(Cow::from(string))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Ident {
|
||||
fn from(string: String) -> Self {
|
||||
Self::validate(&string).unwrap();
|
||||
Self(Cow::from(string))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Ident {
|
||||
/// The derived `Deserialize` allows for creating `Ident`s that do not uphold
|
||||
/// the proper invariants. This custom impl ensures that this cannot happen.
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
Ok(Ident::from(String::deserialize(deserializer)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Borrow<str> for Ident {
|
||||
fn borrow(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Ident {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.as_str().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&syn::Ident> for Ident {
|
||||
fn from(ident: &syn::Ident) -> Self {
|
||||
Self(Cow::from(ident.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for Ident {
|
||||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
|
||||
tokens.append(self.to_syn());
|
||||
}
|
||||
}
|
||||
@@ -1,645 +0,0 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use quote::ToTokens;
|
||||
use serde::Serialize;
|
||||
use syn::{ImplItem, Item, ItemMod, UseTree, Visibility};
|
||||
|
||||
use super::{
|
||||
AttrInheritContext, Attrs, CustomType, Enum, Ident, Macros, Method, ModSymbol, Mutability,
|
||||
OpaqueType, Path, PathType, RustLink, Struct, Trait,
|
||||
};
|
||||
use crate::ast::Function;
|
||||
use crate::environment::*;
|
||||
|
||||
/// Custom Diplomat attribute that can be placed on a struct definition.
|
||||
#[derive(Debug)]
|
||||
enum DiplomatStructAttribute {
|
||||
/// The `#[diplomat::out]` attribute, used for non-opaque structs that
|
||||
/// contain an owned opaque in the form of a `Box`.
|
||||
Out,
|
||||
/// An attribute that can correspond to a type (struct or enum).
|
||||
TypeAttr(DiplomatTypeAttribute),
|
||||
}
|
||||
|
||||
/// Custom Diplomat attribute that can be placed on an enum or struct definition.
|
||||
#[derive(Debug)]
|
||||
enum DiplomatTypeAttribute {
|
||||
/// The `#[diplomat::opaque]` attribute, used for marking a type as opaque.
|
||||
/// Note that opaque structs can be borrowed in return types, but cannot
|
||||
/// be passed into a function behind a mutable reference.
|
||||
Opaque,
|
||||
/// The `#[diplomat::opaque_mut]` attribute, used for marking a type as
|
||||
/// opaque and mutable.
|
||||
/// Note that mutable opaque types can never be borrowed in return types
|
||||
/// (even immutably!), but can be passed into a function behind a mutable
|
||||
/// reference.
|
||||
OpaqueMut,
|
||||
}
|
||||
|
||||
impl DiplomatStructAttribute {
|
||||
/// Parses a [`DiplomatStructAttribute`] from an array of [`syn::Attribute`]s.
|
||||
/// If more than one kind is found, an error is returned containing all the
|
||||
/// ones encountered, since all the current attributes are disjoint.
|
||||
fn parse(attrs: &[syn::Attribute]) -> Result<Option<Self>, Vec<Self>> {
|
||||
let mut buf = String::with_capacity(32);
|
||||
let mut res = Ok(None);
|
||||
for attr in attrs {
|
||||
buf.clear();
|
||||
write!(&mut buf, "{}", attr.path().to_token_stream()).unwrap();
|
||||
let parsed = match buf.as_str() {
|
||||
"diplomat :: out" => Some(Self::Out),
|
||||
"diplomat :: opaque" => Some(Self::TypeAttr(DiplomatTypeAttribute::Opaque)),
|
||||
"diplomat :: opaque_mut" => Some(Self::TypeAttr(DiplomatTypeAttribute::OpaqueMut)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(parsed) = parsed {
|
||||
match res {
|
||||
Ok(None) => res = Ok(Some(parsed)),
|
||||
Ok(Some(first)) => res = Err(vec![first, parsed]),
|
||||
Err(ref mut errors) => errors.push(parsed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl DiplomatTypeAttribute {
|
||||
/// Parses a [`DiplomatTypeAttribute`] from an array of [`syn::Attribute`]s.
|
||||
/// If more than one kind is found, an error is returned containing all the
|
||||
/// ones encountered, since all the current attributes are disjoint.
|
||||
fn parse(attrs: &[syn::Attribute]) -> Result<Option<Self>, Vec<Self>> {
|
||||
let mut buf = String::with_capacity(32);
|
||||
let mut res = Ok(None);
|
||||
for attr in attrs {
|
||||
buf.clear();
|
||||
write!(&mut buf, "{}", attr.path().to_token_stream()).unwrap();
|
||||
let parsed = match buf.as_str() {
|
||||
"diplomat :: opaque" => Some(Self::Opaque),
|
||||
"diplomat :: opaque_mut" => Some(Self::OpaqueMut),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(parsed) = parsed {
|
||||
match res {
|
||||
Ok(None) => res = Ok(Some(parsed)),
|
||||
Ok(Some(first)) => res = Err(vec![first, parsed]),
|
||||
Err(ref mut errors) => errors.push(parsed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct Module {
|
||||
pub name: Ident,
|
||||
pub imports: Vec<(Path, Ident)>,
|
||||
pub declared_types: BTreeMap<Ident, CustomType>,
|
||||
pub declared_traits: BTreeMap<Ident, Trait>,
|
||||
pub declared_functions: BTreeMap<Ident, Function>,
|
||||
pub sub_modules: Vec<Module>,
|
||||
pub attrs: Attrs,
|
||||
}
|
||||
|
||||
/// Contains all items needed to build an AST representation of a given [`Module`],
|
||||
/// as we traverse through [`syn::ItemMod`]. We build this up in [`ModuleBuilder::add`]
|
||||
struct ModuleBuilder {
|
||||
custom_types_by_name: BTreeMap<Ident, CustomType>,
|
||||
custom_traits_by_name: BTreeMap<Ident, Trait>,
|
||||
/// Types that are private (so if we encounter their impl blocks, they can be safely ignored)
|
||||
private_types_by_name: BTreeSet<Ident>,
|
||||
functions_by_name: BTreeMap<Ident, Function>,
|
||||
sub_modules: Vec<Module>,
|
||||
imports: Vec<(Path, Ident)>,
|
||||
/// As we traverse through the module, are we inside of #[diplomat::bridge]?
|
||||
/// If so, then `analyze_types` is set to true, and types, functions, and traits are all updated according to information parsed.
|
||||
///
|
||||
/// Otherwise, we traverse through modules until we find a module marked by #[diplomat::bridge]
|
||||
analyze_types: bool,
|
||||
/// Are we to only analyze public structs or enums?
|
||||
skip_private_items: bool,
|
||||
type_parent_attrs: Attrs,
|
||||
impl_parent_attrs: Attrs,
|
||||
mod_macros: Macros,
|
||||
}
|
||||
|
||||
impl ModuleBuilder {
|
||||
fn add(&mut self, a: &Item) {
|
||||
match a {
|
||||
Item::Use(u) => {
|
||||
if self.analyze_types {
|
||||
extract_imports(&Path::empty(), &u.tree, &mut self.imports);
|
||||
}
|
||||
}
|
||||
Item::Struct(strct) => {
|
||||
if self.analyze_types {
|
||||
if self.skip_private_items && !matches!(strct.vis, syn::Visibility::Public(..))
|
||||
{
|
||||
self.private_types_by_name.insert((&strct.ident).into());
|
||||
return;
|
||||
}
|
||||
let custom_type = match DiplomatStructAttribute::parse(&strct.attrs[..]) {
|
||||
Ok(None) => {
|
||||
CustomType::Struct(Struct::new(strct, false, &self.type_parent_attrs))
|
||||
}
|
||||
Ok(Some(DiplomatStructAttribute::Out)) => {
|
||||
CustomType::Struct(Struct::new(strct, true, &self.type_parent_attrs))
|
||||
}
|
||||
Ok(Some(DiplomatStructAttribute::TypeAttr(
|
||||
DiplomatTypeAttribute::Opaque,
|
||||
))) => CustomType::Opaque(OpaqueType::new_struct(
|
||||
strct,
|
||||
Mutability::Immutable,
|
||||
&self.type_parent_attrs,
|
||||
)),
|
||||
Ok(Some(DiplomatStructAttribute::TypeAttr(
|
||||
DiplomatTypeAttribute::OpaqueMut,
|
||||
))) => CustomType::Opaque(OpaqueType::new_struct(
|
||||
strct,
|
||||
Mutability::Mutable,
|
||||
&self.type_parent_attrs,
|
||||
)),
|
||||
Err(errors) => {
|
||||
panic!("Multiple conflicting Diplomat struct attributes, there can be at most one: {errors:?}");
|
||||
}
|
||||
};
|
||||
|
||||
self.custom_types_by_name
|
||||
.insert(Ident::from(&strct.ident), custom_type);
|
||||
}
|
||||
}
|
||||
|
||||
Item::Enum(enm) => {
|
||||
if self.analyze_types {
|
||||
let ident = (&enm.ident).into();
|
||||
|
||||
if self.skip_private_items && !matches!(enm.vis, syn::Visibility::Public(..)) {
|
||||
self.private_types_by_name.insert(ident);
|
||||
return;
|
||||
}
|
||||
|
||||
let custom_enum = match DiplomatTypeAttribute::parse(&enm.attrs[..]) {
|
||||
Ok(None) => CustomType::Enum(Enum::new(enm, &self.type_parent_attrs)),
|
||||
Ok(Some(DiplomatTypeAttribute::Opaque)) => {
|
||||
CustomType::Opaque(OpaqueType::new_enum(
|
||||
enm,
|
||||
Mutability::Immutable,
|
||||
&self.type_parent_attrs,
|
||||
))
|
||||
}
|
||||
Ok(Some(DiplomatTypeAttribute::OpaqueMut)) => CustomType::Opaque(
|
||||
OpaqueType::new_enum(enm, Mutability::Mutable, &self.type_parent_attrs),
|
||||
),
|
||||
Err(errors) => {
|
||||
panic!("Multiple conflicting Diplomat enum attributes, there can be at most one: {errors:?}");
|
||||
}
|
||||
};
|
||||
self.custom_types_by_name.insert(ident, custom_enum);
|
||||
}
|
||||
}
|
||||
|
||||
Item::Impl(imp) => {
|
||||
if self.analyze_types && imp.trait_.is_none() {
|
||||
let self_path = match imp.self_ty.as_ref() {
|
||||
syn::Type::Path(s) => PathType::from(s),
|
||||
_ => panic!("Self type not found"),
|
||||
};
|
||||
let mut impl_attrs = self.impl_parent_attrs.clone();
|
||||
impl_attrs.add_attrs(&imp.attrs);
|
||||
let method_parent_attrs =
|
||||
impl_attrs.attrs_for_inheritance(AttrInheritContext::MethodFromImpl);
|
||||
let self_ident = self_path.path.elements.last().unwrap();
|
||||
|
||||
// Do a prepass to evaluate macros:
|
||||
let mut impl_item_vec = Vec::new();
|
||||
for i in &imp.items {
|
||||
match i {
|
||||
ImplItem::Fn(f) => {
|
||||
impl_item_vec.push(ImplItem::Fn(f.clone()));
|
||||
}
|
||||
ImplItem::Macro(mac) => {
|
||||
let mut items = self.mod_macros.evaluate_impl_item_macro(mac);
|
||||
impl_item_vec.append(&mut items);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Then only add functions to the block:
|
||||
let mut new_methods = impl_item_vec
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
ImplItem::Fn(m) => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|m| {
|
||||
let is_public = matches!(m.vis, Visibility::Public(_));
|
||||
let has_diplomat_attrs = m.attrs.iter().any(|a| {
|
||||
a.path().segments.iter().next().unwrap().ident == "diplomat"
|
||||
});
|
||||
assert!(
|
||||
is_public || !has_diplomat_attrs,
|
||||
"Non-public method with diplomat attrs found: {self_ident}::{}",
|
||||
m.sig.ident
|
||||
);
|
||||
is_public
|
||||
})
|
||||
.map(|m| {
|
||||
Method::from_syn(
|
||||
m,
|
||||
self_path.clone(),
|
||||
Some(&imp.generics),
|
||||
&method_parent_attrs,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
if self.skip_private_items && self.private_types_by_name.contains(self_ident) {
|
||||
return;
|
||||
}
|
||||
|
||||
match self.custom_types_by_name.get_mut(self_ident)
|
||||
.unwrap_or_else(|| panic!("Diplomat currently requires impls to be in the same module as their self type ({self_ident})")) {
|
||||
CustomType::Struct(strct) => {
|
||||
strct.methods.append(&mut new_methods);
|
||||
}
|
||||
CustomType::Opaque(strct) => {
|
||||
strct.methods.append(&mut new_methods);
|
||||
}
|
||||
CustomType::Enum(enm) => {
|
||||
enm.methods.append(&mut new_methods);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Item::Mod(item_mod) => {
|
||||
self.sub_modules.push(Module::from_syn(item_mod, false));
|
||||
}
|
||||
Item::Trait(trt) => {
|
||||
if self.analyze_types {
|
||||
let ident = (&trt.ident).into();
|
||||
let trt = Trait::new(trt, &self.type_parent_attrs);
|
||||
self.custom_traits_by_name.insert(ident, trt);
|
||||
}
|
||||
}
|
||||
Item::Macro(mac) => {
|
||||
if self.analyze_types {
|
||||
if let Some(i) = &mac.ident {
|
||||
let macro_rules_attr = mac.attrs.iter().find(|a| {
|
||||
a.path()
|
||||
== &syn::parse_str::<syn::Path>("diplomat::macro_rules").unwrap()
|
||||
});
|
||||
|
||||
if macro_rules_attr.is_some() {
|
||||
self.mod_macros.add_item_macro(mac);
|
||||
} else {
|
||||
println!(
|
||||
r#"WARNING: Found macro_rules definition "macro_rules! {i}" with no #[diplomat::macro_rules] attribute. This will not be evaluated in Diplomat bindings."#
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let items = self.mod_macros.evaluate_item_macro(mac);
|
||||
for i in items {
|
||||
self.add(&i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Item::Fn(f) => {
|
||||
if self.analyze_types {
|
||||
let is_public = matches!(f.vis, Visibility::Public(_));
|
||||
let has_diplomat_attrs = f
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|a| a.path().segments.iter().next().unwrap().ident == "diplomat");
|
||||
assert!(
|
||||
is_public || !has_diplomat_attrs,
|
||||
"Non-public function with diplomat attrs found: {}",
|
||||
f.sig.ident
|
||||
);
|
||||
if is_public {
|
||||
let parent_attrs = self
|
||||
.impl_parent_attrs
|
||||
.attrs_for_inheritance(AttrInheritContext::MethodFromImpl);
|
||||
let out = Function::from_syn(f, &parent_attrs);
|
||||
self.functions_by_name.insert(out.name.clone(), out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Module {
|
||||
pub fn all_rust_links(&self) -> HashSet<&RustLink> {
|
||||
let mut rust_links = self
|
||||
.declared_types
|
||||
.values()
|
||||
.flat_map(|t| t.all_rust_links())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
self.sub_modules.iter().for_each(|m| {
|
||||
rust_links.extend(m.all_rust_links().iter());
|
||||
});
|
||||
rust_links
|
||||
}
|
||||
|
||||
pub fn insert_all_types(&self, in_path: Path, out: &mut Env) {
|
||||
let mut mod_symbols = ModuleEnv::new(self.attrs.clone());
|
||||
|
||||
self.imports.iter().for_each(|(path, name)| {
|
||||
mod_symbols.insert(name.clone(), ModSymbol::Alias(path.clone()));
|
||||
});
|
||||
|
||||
self.declared_types.iter().for_each(|(k, v)| {
|
||||
if mod_symbols
|
||||
.insert(k.clone(), ModSymbol::CustomType(v.clone()))
|
||||
.is_some()
|
||||
{
|
||||
panic!("Two types were declared with the same name, this needs to be implemented (key: {k})");
|
||||
}
|
||||
});
|
||||
|
||||
self.declared_traits.iter().for_each(|(k, v)| {
|
||||
if mod_symbols
|
||||
.insert(k.clone(), ModSymbol::Trait(v.clone()))
|
||||
.is_some()
|
||||
{
|
||||
panic!("Two traits were declared with the same name, this needs to be implemented (key: {k})");
|
||||
}
|
||||
});
|
||||
|
||||
self.declared_functions.iter().for_each(|(k, f)| {
|
||||
if mod_symbols.insert(k.clone(), ModSymbol::Function(f.clone())).is_some() {
|
||||
panic!("Two functions were declared with the same name, this needs to be implemented (key: {k})")
|
||||
}
|
||||
});
|
||||
|
||||
let path_to_self = in_path.sub_path(self.name.clone());
|
||||
self.sub_modules.iter().for_each(|m| {
|
||||
m.insert_all_types(path_to_self.clone(), out);
|
||||
mod_symbols.insert(m.name.clone(), ModSymbol::SubModule(m.name.clone()));
|
||||
});
|
||||
|
||||
out.insert(path_to_self, mod_symbols);
|
||||
}
|
||||
|
||||
/// Convert an [`ItemMod`] to a [`Module`].
|
||||
///
|
||||
/// `force_analyze` is for forcibly parsing the module in the case where we know the `#[diplomat::bridge]` attribute should be present,
|
||||
/// but proc_macro (or some other analyzer) has removed the attribute in advance.
|
||||
pub fn from_syn(input: &ItemMod, force_analyze: bool) -> Module {
|
||||
let mod_attrs: Attrs = (&*input.attrs).into();
|
||||
|
||||
let mut mst = ModuleBuilder {
|
||||
custom_types_by_name: BTreeMap::new(),
|
||||
custom_traits_by_name: BTreeMap::new(),
|
||||
private_types_by_name: BTreeSet::new(),
|
||||
functions_by_name: BTreeMap::new(),
|
||||
sub_modules: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
analyze_types: force_analyze
|
||||
|| input
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|a| a.path().to_token_stream().to_string() == "diplomat :: bridge"),
|
||||
skip_private_items: input.attrs.iter().any(|a| {
|
||||
a.path().to_token_stream().to_string() == "diplomat :: skip_private_items"
|
||||
}),
|
||||
impl_parent_attrs: mod_attrs
|
||||
.attrs_for_inheritance(AttrInheritContext::MethodOrImplFromModule),
|
||||
type_parent_attrs: mod_attrs.attrs_for_inheritance(AttrInheritContext::Type),
|
||||
mod_macros: Macros::new(),
|
||||
};
|
||||
|
||||
input
|
||||
.content
|
||||
.as_ref()
|
||||
.map(|t| &t.1[..])
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.for_each(|a| {
|
||||
mst.add(a);
|
||||
});
|
||||
|
||||
Module {
|
||||
name: (&input.ident).into(),
|
||||
imports: mst.imports,
|
||||
declared_types: mst.custom_types_by_name,
|
||||
declared_traits: mst.custom_traits_by_name,
|
||||
declared_functions: mst.functions_by_name,
|
||||
sub_modules: mst.sub_modules,
|
||||
attrs: mod_attrs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_imports(base_path: &Path, use_tree: &UseTree, out: &mut Vec<(Path, Ident)>) {
|
||||
match use_tree {
|
||||
UseTree::Name(name) => out.push((
|
||||
base_path.sub_path((&name.ident).into()),
|
||||
(&name.ident).into(),
|
||||
)),
|
||||
UseTree::Path(path) => {
|
||||
extract_imports(&base_path.sub_path((&path.ident).into()), &path.tree, out)
|
||||
}
|
||||
UseTree::Glob(_) => todo!("Glob imports are not yet supported"),
|
||||
UseTree::Group(group) => {
|
||||
group
|
||||
.items
|
||||
.iter()
|
||||
.for_each(|i| extract_imports(base_path, i, out));
|
||||
}
|
||||
UseTree::Rename(rename) => out.push((
|
||||
base_path.sub_path((&rename.ident).into()),
|
||||
(&rename.rename).into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct File {
|
||||
pub modules: BTreeMap<String, Module>,
|
||||
}
|
||||
|
||||
impl File {
|
||||
/// Fuses all declared types into a single environment `HashMap`.
|
||||
pub fn all_types(&self) -> Env {
|
||||
let mut out = Env::default();
|
||||
let mut top_symbols = ModuleEnv::new(Default::default());
|
||||
|
||||
self.modules.values().for_each(|m| {
|
||||
m.insert_all_types(Path::empty(), &mut out);
|
||||
top_symbols.insert(m.name.clone(), ModSymbol::SubModule(m.name.clone()));
|
||||
});
|
||||
|
||||
out.insert(Path::empty(), top_symbols);
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn all_rust_links(&self) -> HashSet<&RustLink> {
|
||||
self.modules
|
||||
.values()
|
||||
.flat_map(|m| m.all_rust_links().into_iter())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&syn::File> for File {
|
||||
/// Get all custom types across all modules defined in a given file.
|
||||
fn from(file: &syn::File) -> File {
|
||||
let mut out = BTreeMap::new();
|
||||
file.items.iter().for_each(|i| {
|
||||
if let Item::Mod(item_mod) = i {
|
||||
out.insert(
|
||||
item_mod.ident.to_string(),
|
||||
Module::from_syn(item_mod, false),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
File { modules: out }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use insta::{self, Settings};
|
||||
|
||||
use syn;
|
||||
|
||||
use crate::ast::{File, Module};
|
||||
|
||||
#[test]
|
||||
fn simple_mod() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(Module::from_syn(
|
||||
&syn::parse_quote! {
|
||||
mod ffi {
|
||||
struct NonOpaqueStruct {
|
||||
a: i32,
|
||||
b: Box<NonOpaqueStruct>
|
||||
}
|
||||
|
||||
impl NonOpaqueStruct {
|
||||
pub fn new(x: i32) -> NonOpaqueStruct {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
pub fn set_a(&mut self, new_a: i32) {
|
||||
self.a = new_a;
|
||||
}
|
||||
}
|
||||
|
||||
#[diplomat::opaque]
|
||||
struct OpaqueStruct {
|
||||
a: SomeExternalType
|
||||
}
|
||||
|
||||
impl OpaqueStruct {
|
||||
pub fn new() -> Box<OpaqueStruct> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
pub fn get_string(&self) -> String {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn test_function() {}
|
||||
pub fn other_test_function(x : i32) -> NonOpaqueStruct {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
},
|
||||
true
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn method_visibility() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(Module::from_syn(
|
||||
&syn::parse_quote! {
|
||||
#[diplomat::bridge]
|
||||
mod ffi {
|
||||
struct Foo {}
|
||||
|
||||
impl Foo {
|
||||
pub fn pub_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
pub(crate) fn pub_crate_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
pub(super) fn pub_super_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
fn priv_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
true
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_in_non_diplomat_not_analyzed() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(File::from(&syn::parse_quote! {
|
||||
#[diplomat::bridge]
|
||||
mod ffi {
|
||||
struct Foo {}
|
||||
}
|
||||
|
||||
mod other {
|
||||
use something::*;
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_visibility() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(File::from(&syn::parse_quote! {
|
||||
#[diplomat::bridge]
|
||||
#[diplomat::skip_private_items]
|
||||
mod ffi {
|
||||
struct Foo {}
|
||||
|
||||
#[diplomat::opaque]
|
||||
pub struct Opaque{
|
||||
foo: Foo,
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/enums.rs
|
||||
expression: "Enum::new(&syn::parse_quote!\n{\n #[doc = r\" Some docs.\"] #[diplomat::rust_link(foo::Bar, Enum)] enum\n DiscriminantedEnum { Abc = -1, Def = 0, Ghi = 1, Jkl = 2, }\n}, &Default::default())"
|
||||
---
|
||||
name: DiscriminantedEnum
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: Some docs.
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
typ: Enum
|
||||
display: Normal
|
||||
variants:
|
||||
- - Abc
|
||||
- -1
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
- - Def
|
||||
- 0
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
- - Ghi
|
||||
- 1
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
- - Jkl
|
||||
- 2
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
methods: []
|
||||
attrs: {}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/enums.rs
|
||||
expression: "Enum::new(&syn::parse_quote!\n{\n #[doc = r\" Some docs.\"] #[diplomat::rust_link(foo::Bar, Enum)] enum\n MyLocalEnum { Abc, #[doc = r\" Some more docs.\"] Def }\n}, &Default::default())"
|
||||
---
|
||||
name: MyLocalEnum
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: Some docs.
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
typ: Enum
|
||||
display: Normal
|
||||
variants:
|
||||
- - Abc
|
||||
- 0
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
- - Def
|
||||
- 1
|
||||
- - - cfg: Star
|
||||
lines: Some more docs.
|
||||
- []
|
||||
- {}
|
||||
methods: []
|
||||
attrs: {}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/functions.rs
|
||||
expression: "Function::from_syn(&syn::parse_quote! { fn some_func(a : f32, b: f64) {} },\n&Attrs::default())"
|
||||
---
|
||||
name: some_func
|
||||
abi_name: diplomat_external_some_func
|
||||
params:
|
||||
- name: a
|
||||
ty:
|
||||
Primitive: f32
|
||||
attrs: {}
|
||||
- name: b
|
||||
ty:
|
||||
Primitive: f64
|
||||
attrs: {}
|
||||
output_type: ~
|
||||
lifetimes: {}
|
||||
attrs: {}
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/functions.rs
|
||||
expression: "Function::from_syn(&syn::parse_quote!\n{ fn some_func<'a>(a : &'a SomeType) -> Option<&'a SomeType> {} },\n&Attrs::default())"
|
||||
---
|
||||
name: some_func
|
||||
abi_name: diplomat_external_some_func
|
||||
params:
|
||||
- name: a
|
||||
ty:
|
||||
Reference:
|
||||
- Named: a
|
||||
- Immutable
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- SomeType
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
output_type:
|
||||
Option:
|
||||
- Reference:
|
||||
- Named: a
|
||||
- Immutable
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- SomeType
|
||||
lifetimes: []
|
||||
- Stdlib
|
||||
lifetimes:
|
||||
a: []
|
||||
attrs: {}
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/functions.rs
|
||||
expression: "Function::from_syn(&syn::parse_quote!\n{ fn some_func(a : SomeType) -> Option<()> {} }, &Attrs::default())"
|
||||
---
|
||||
name: some_func
|
||||
abi_name: diplomat_external_some_func
|
||||
params:
|
||||
- name: a
|
||||
ty:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- SomeType
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
output_type:
|
||||
Option:
|
||||
- Unit
|
||||
- Stdlib
|
||||
lifetimes: {}
|
||||
attrs: {}
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/methods.rs
|
||||
expression: "Method::from_syn(&syn::parse_quote!\n{\n #[doc = r\" Some docs.\"] #[diplomat::rust_link(foo::Bar::batz, FnInStruct)]\n #[cfg(any(feature = \"foo\", not(feature = \"bar\")))] fn\n foo(x: u64, y: MyCustomStruct) {}\n},\nPathType::new(Path::empty().sub_path(Ident::from(\"MyStructContainingMethod\"))),\nNone, &Attrs::default())"
|
||||
---
|
||||
name: foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: Some docs.
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
- batz
|
||||
typ: FnInStruct
|
||||
display: Normal
|
||||
abi_name: MyStructContainingMethod_foo
|
||||
self_param: ~
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: u64
|
||||
attrs: {}
|
||||
- name: y
|
||||
ty:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyCustomStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
return_type: ~
|
||||
lifetime_env: {}
|
||||
attrs:
|
||||
cfg:
|
||||
- "# [cfg (any (feature = \"foo\" , not (feature = \"bar\")))]"
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/methods.rs
|
||||
expression: "Method::from_syn(&syn::parse_quote!\n{\n #[diplomat::rust_link(foo::Bar::batz, FnInStruct)] fn\n foo(&mut self, x: u64, y: MyCustomStruct) -> u64 { x }\n},\nPathType::new(Path::empty().sub_path(Ident::from(\"MyStructContainingMethod\"))),\nNone, &Attrs::default())"
|
||||
---
|
||||
name: foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
- batz
|
||||
typ: FnInStruct
|
||||
display: Normal
|
||||
abi_name: MyStructContainingMethod_foo
|
||||
self_param:
|
||||
reference:
|
||||
- Anonymous
|
||||
- Mutable
|
||||
path_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: u64
|
||||
attrs: {}
|
||||
- name: y
|
||||
ty:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyCustomStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
return_type:
|
||||
Primitive: u64
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/methods.rs
|
||||
expression: "Method::from_syn(&syn::parse_quote!\n{ fn foo(&self, x: u64, y: MyCustomStruct) {} },\nPathType::new(Path::empty().sub_path(Ident::from(\"MyStructContainingMethod\"))),\nNone, &Attrs::default())"
|
||||
---
|
||||
name: foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
abi_name: MyStructContainingMethod_foo
|
||||
self_param:
|
||||
reference:
|
||||
- Anonymous
|
||||
- Immutable
|
||||
path_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: u64
|
||||
attrs: {}
|
||||
- name: y
|
||||
ty:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyCustomStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
return_type: ~
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/methods.rs
|
||||
expression: "Method::from_syn(&syn::parse_quote!\n{\n #[doc = r\" Some docs.\"] #[doc = r\" Some more docs.\"] #[doc = r\"\"]\n #[doc = r\" Even more docs.\"]\n #[diplomat::rust_link(foo::Bar::batz, FnInEnum)] fn\n foo(x: u64, y: MyCustomStruct) -> u64 { x }\n},\nPathType::new(Path::empty().sub_path(Ident::from(\"MyStructContainingMethod\"))),\nNone, &Attrs::default())"
|
||||
---
|
||||
name: foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: "Some docs.\nSome more docs.\n\nEven more docs."
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
- batz
|
||||
typ: FnInEnum
|
||||
display: Normal
|
||||
abi_name: MyStructContainingMethod_foo
|
||||
self_param: ~
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: u64
|
||||
attrs: {}
|
||||
- name: y
|
||||
ty:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyCustomStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
return_type:
|
||||
Primitive: u64
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/methods.rs
|
||||
expression: "Method::from_syn(&syn::parse_quote!\n{\n #[doc = r\" Some docs.\"] #[diplomat::rust_link(foo::Bar::batz, FnInStruct)]\n fn foo(x: u64, y: MyCustomStruct) {}\n},\nPathType::new(Path::empty().sub_path(Ident::from(\"MyStructContainingMethod\"))),\nNone, &Attrs::default())"
|
||||
---
|
||||
name: foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: Some docs.
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
- batz
|
||||
typ: FnInStruct
|
||||
display: Normal
|
||||
abi_name: MyStructContainingMethod_foo
|
||||
self_param: ~
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- MyStructContainingMethod
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: u64
|
||||
attrs: {}
|
||||
- name: y
|
||||
ty:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyCustomStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
return_type: ~
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/modules.rs
|
||||
expression: "File::from(&syn::parse_quote!\n{\n #[diplomat::bridge] mod ffi { struct Foo {} } mod other\n { use something::*; }\n})"
|
||||
---
|
||||
modules:
|
||||
ffi:
|
||||
name: ffi
|
||||
imports: []
|
||||
declared_types:
|
||||
Foo:
|
||||
Struct:
|
||||
name: Foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
lifetimes: {}
|
||||
fields: []
|
||||
methods: []
|
||||
output_only: false
|
||||
attrs: {}
|
||||
declared_traits: {}
|
||||
declared_functions: {}
|
||||
sub_modules: []
|
||||
attrs: {}
|
||||
other:
|
||||
name: other
|
||||
imports: []
|
||||
declared_types: {}
|
||||
declared_traits: {}
|
||||
declared_functions: {}
|
||||
sub_modules: []
|
||||
attrs: {}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/modules.rs
|
||||
expression: "Module::from_syn(&syn::parse_quote!\n{\n #[diplomat::bridge] mod ffi\n {\n struct Foo {} impl Foo\n {\n pub fn pub_fn() { unimplemented!() } pub(crate) fn pub_crate_fn()\n { unimplemented!() } pub(super) fn pub_super_fn()\n { unimplemented!() } fn priv_fn() { unimplemented!() }\n }\n }\n}, true)"
|
||||
---
|
||||
name: ffi
|
||||
imports: []
|
||||
declared_types:
|
||||
Foo:
|
||||
Struct:
|
||||
name: Foo
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
lifetimes: {}
|
||||
fields: []
|
||||
methods:
|
||||
- name: pub_fn
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
abi_name: Foo_pub_fn
|
||||
self_param: ~
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- Foo
|
||||
lifetimes: []
|
||||
params: []
|
||||
return_type: ~
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
output_only: false
|
||||
attrs: {}
|
||||
declared_traits: {}
|
||||
declared_functions: {}
|
||||
sub_modules: []
|
||||
attrs: {}
|
||||
-189
@@ -1,189 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/modules.rs
|
||||
expression: "Module::from_syn(&syn::parse_quote!\n{\n mod ffi\n {\n struct NonOpaqueStruct { a: i32, b: Box<NonOpaqueStruct> } impl\n NonOpaqueStruct\n {\n pub fn new(x: i32) -> NonOpaqueStruct { unimplemented!(); } pub fn\n set_a(&mut self, new_a: i32) { self.a = new_a; }\n } #[diplomat::opaque] struct OpaqueStruct { a: SomeExternalType } impl\n OpaqueStruct\n {\n pub fn new() -> Box<OpaqueStruct> { unimplemented!(); } pub fn\n get_string(&self) -> String { unimplemented!() }\n } pub fn test_function() {} pub fn other_test_function(x : i32) ->\n NonOpaqueStruct { unimplemented!(); }\n }\n}, true)"
|
||||
---
|
||||
name: ffi
|
||||
imports: []
|
||||
declared_types:
|
||||
NonOpaqueStruct:
|
||||
Struct:
|
||||
name: NonOpaqueStruct
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
lifetimes: {}
|
||||
fields:
|
||||
- - a
|
||||
- Primitive: i32
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
- - b
|
||||
- Box:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- NonOpaqueStruct
|
||||
lifetimes: []
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
methods:
|
||||
- name: new
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
abi_name: NonOpaqueStruct_new
|
||||
self_param: ~
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- NonOpaqueStruct
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: i32
|
||||
attrs: {}
|
||||
return_type:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- NonOpaqueStruct
|
||||
lifetimes: []
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
- name: set_a
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
abi_name: NonOpaqueStruct_set_a
|
||||
self_param:
|
||||
reference:
|
||||
- Anonymous
|
||||
- Mutable
|
||||
path_type:
|
||||
path:
|
||||
elements:
|
||||
- NonOpaqueStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- NonOpaqueStruct
|
||||
lifetimes: []
|
||||
params:
|
||||
- name: new_a
|
||||
ty:
|
||||
Primitive: i32
|
||||
attrs: {}
|
||||
return_type: ~
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
output_only: false
|
||||
attrs: {}
|
||||
OpaqueStruct:
|
||||
Opaque:
|
||||
name: OpaqueStruct
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
lifetimes: {}
|
||||
methods:
|
||||
- name: new
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
abi_name: OpaqueStruct_new
|
||||
self_param: ~
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- OpaqueStruct
|
||||
lifetimes: []
|
||||
params: []
|
||||
return_type:
|
||||
Box:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- OpaqueStruct
|
||||
lifetimes: []
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
- name: get_string
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
abi_name: OpaqueStruct_get_string
|
||||
self_param:
|
||||
reference:
|
||||
- Anonymous
|
||||
- Immutable
|
||||
path_type:
|
||||
path:
|
||||
elements:
|
||||
- OpaqueStruct
|
||||
lifetimes: []
|
||||
attrs: {}
|
||||
self_type:
|
||||
path:
|
||||
elements:
|
||||
- OpaqueStruct
|
||||
lifetimes: []
|
||||
params: []
|
||||
return_type:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- String
|
||||
lifetimes: []
|
||||
lifetime_env: {}
|
||||
attrs: {}
|
||||
mutability: Immutable
|
||||
attrs: {}
|
||||
dtor_abi_name: OpaqueStruct_destroy
|
||||
declared_traits: {}
|
||||
declared_functions:
|
||||
other_test_function:
|
||||
name: other_test_function
|
||||
abi_name: diplomat_external_other_test_function
|
||||
params:
|
||||
- name: x
|
||||
ty:
|
||||
Primitive: i32
|
||||
attrs: {}
|
||||
output_type:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- NonOpaqueStruct
|
||||
lifetimes: []
|
||||
lifetimes: {}
|
||||
attrs: {}
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
test_function:
|
||||
name: test_function
|
||||
abi_name: diplomat_external_test_function
|
||||
params: []
|
||||
output_type: ~
|
||||
lifetimes: {}
|
||||
attrs: {}
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
sub_modules: []
|
||||
attrs: {}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/modules.rs
|
||||
expression: "File::from(&syn::parse_quote!\n{\n #[diplomat::bridge] #[diplomat::skip_private_items] mod ffi\n {\n struct Foo {} #[diplomat::opaque] #[diplomat::skip_private_items] pub struct\n Opaque{ foo: Foo, }\n }\n})"
|
||||
---
|
||||
modules:
|
||||
ffi:
|
||||
name: ffi
|
||||
imports: []
|
||||
declared_types:
|
||||
Opaque:
|
||||
Opaque:
|
||||
name: Opaque
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
lifetimes: {}
|
||||
methods: []
|
||||
mutability: Immutable
|
||||
attrs: {}
|
||||
dtor_abi_name: Opaque_destroy
|
||||
declared_traits: {}
|
||||
declared_functions: {}
|
||||
sub_modules: []
|
||||
attrs: {}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/structs.rs
|
||||
expression: "Struct::new(&syn::parse_quote!\n{\n #[doc = r\" Some docs.\"] #[diplomat::rust_link(foo::Bar, Struct)] struct\n MyLocalStruct { a: i32, b: Box<MyLocalStruct> }\n}, true, &Default::default())"
|
||||
---
|
||||
name: MyLocalStruct
|
||||
docs:
|
||||
- - cfg: Star
|
||||
lines: Some docs.
|
||||
- - path:
|
||||
elements:
|
||||
- foo
|
||||
- Bar
|
||||
typ: Struct
|
||||
display: Normal
|
||||
lifetimes: {}
|
||||
fields:
|
||||
- - a
|
||||
- Primitive: i32
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
- - b
|
||||
- Box:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
- - - cfg: Star
|
||||
lines: ""
|
||||
- []
|
||||
- {}
|
||||
methods: []
|
||||
output_only: true
|
||||
attrs: {}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { DiplomatSliceStr<'a> }, None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- DiplomatSliceStr
|
||||
lifetimes:
|
||||
- Named: a
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { DiplomatSliceMut<'a, f32> }, None)"
|
||||
---
|
||||
PrimitiveSlice:
|
||||
- - Named: a
|
||||
- Mutable
|
||||
- f32
|
||||
- Diplomat
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { :: core :: my_type :: Foo }, None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- core
|
||||
- my_type
|
||||
- Foo
|
||||
lifetimes: []
|
||||
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { :: core :: my_type :: Foo < 'test > },\n None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- core
|
||||
- my_type
|
||||
- Foo
|
||||
lifetimes:
|
||||
- Named: test
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Option<Ref<'object>> }, None)"
|
||||
---
|
||||
Option:
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- Ref
|
||||
lifetimes:
|
||||
- Named: object
|
||||
- Stdlib
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Foo < 'a, 'b, 'c, 'd > }, None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- Foo
|
||||
lifetimes:
|
||||
- Named: a
|
||||
- Named: b
|
||||
- Named: c
|
||||
- Named: d
|
||||
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! {\n very :: long :: path :: to :: my :: Type < 'x, 'y, 'z >\n }, None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- very
|
||||
- long
|
||||
- path
|
||||
- to
|
||||
- my
|
||||
- Type
|
||||
lifetimes:
|
||||
- Named: x
|
||||
- Named: y
|
||||
- Named: z
|
||||
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Result<OkRef<'a, 'b>, ErrRef<'c>> },\n None)"
|
||||
---
|
||||
Result:
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- OkRef
|
||||
lifetimes:
|
||||
- Named: a
|
||||
- Named: b
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- ErrRef
|
||||
lifetimes:
|
||||
- Named: c
|
||||
- Stdlib
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { DiplomatSlice<'a, u16> }, None)"
|
||||
---
|
||||
PrimitiveSlice:
|
||||
- - Named: a
|
||||
- Immutable
|
||||
- u16
|
||||
- Diplomat
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Foo < 'a, 'b > }, None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- Foo
|
||||
lifetimes:
|
||||
- Named: a
|
||||
- Named: b
|
||||
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Box < MyLocalStruct > }, None)"
|
||||
---
|
||||
Box:
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { MyLocalStruct }, None)"
|
||||
---
|
||||
Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Option<MyLocalStruct> }, None)"
|
||||
---
|
||||
Option:
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
- Stdlib
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { & mut MyLocalStruct }, None)"
|
||||
---
|
||||
Reference:
|
||||
- Anonymous
|
||||
- Mutable
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { DiplomatResult<(), MyLocalStruct> },\n None)"
|
||||
---
|
||||
Result:
|
||||
- Unit
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
- Diplomat
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Result<MyLocalStruct, i32> }, None)"
|
||||
---
|
||||
Result:
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
- Primitive: i32
|
||||
- Stdlib
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { Result<(), MyLocalStruct> }, None)"
|
||||
---
|
||||
Result:
|
||||
- Unit
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
- Stdlib
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
---
|
||||
source: core/src/ast/types.rs
|
||||
expression: "TypeName::from_syn(&syn::parse_quote! { DiplomatResult<MyLocalStruct, i32> },\n None)"
|
||||
---
|
||||
Result:
|
||||
- Named:
|
||||
path:
|
||||
elements:
|
||||
- MyLocalStruct
|
||||
lifetimes: []
|
||||
- Primitive: i32
|
||||
- Diplomat
|
||||
@@ -1,85 +0,0 @@
|
||||
use serde::Serialize;
|
||||
|
||||
use super::docs::Docs;
|
||||
use super::{Attrs, Ident, LifetimeEnv, Method, PathType, TypeName};
|
||||
|
||||
/// A struct declaration in an FFI module that is not opaque.
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct Struct {
|
||||
pub name: Ident,
|
||||
pub docs: Docs,
|
||||
pub lifetimes: LifetimeEnv,
|
||||
pub fields: Vec<(Ident, TypeName, Docs, Attrs)>,
|
||||
pub methods: Vec<Method>,
|
||||
pub output_only: bool,
|
||||
pub attrs: Attrs,
|
||||
}
|
||||
|
||||
impl Struct {
|
||||
/// Extract a [`Struct`] metadata value from an AST node.
|
||||
pub fn new(strct: &syn::ItemStruct, output_only: bool, parent_attrs: &Attrs) -> Self {
|
||||
let self_path_type = PathType::extract_self_type(strct);
|
||||
let fields: Vec<_> = strct
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
use quote::ToTokens;
|
||||
// Non-opaque tuple structs will never be allowed
|
||||
let name = field.ident.as_ref().map(Into::into).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"non-opaque tuples structs are disallowed ({:?})",
|
||||
field.ty.to_token_stream().to_string()
|
||||
)
|
||||
});
|
||||
let type_name = TypeName::from_syn(&field.ty, Some(self_path_type.clone()));
|
||||
let docs = Docs::from_attrs(&field.attrs);
|
||||
|
||||
(name, type_name, docs, Attrs::from_attrs(&field.attrs))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let lifetimes = LifetimeEnv::from_struct_item(strct, &fields[..]);
|
||||
let mut attrs = parent_attrs.clone();
|
||||
attrs.add_attrs(&strct.attrs);
|
||||
Struct {
|
||||
name: (&strct.ident).into(),
|
||||
docs: Docs::from_attrs(&strct.attrs),
|
||||
lifetimes,
|
||||
fields,
|
||||
methods: vec![],
|
||||
output_only,
|
||||
attrs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use insta::{self, Settings};
|
||||
|
||||
use syn;
|
||||
|
||||
use super::Struct;
|
||||
|
||||
#[test]
|
||||
fn simple_struct() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(Struct::new(
|
||||
&syn::parse_quote! {
|
||||
/// Some docs.
|
||||
#[diplomat::rust_link(foo::Bar, Struct)]
|
||||
struct MyLocalStruct {
|
||||
a: i32,
|
||||
b: Box<MyLocalStruct>
|
||||
}
|
||||
},
|
||||
true,
|
||||
&Default::default()
|
||||
));
|
||||
});
|
||||
}
|
||||
}
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: core/src/hir/attrs.rs
|
||||
expression: output
|
||||
---
|
||||
Lowering error in Foo::takes_slice: Primitive struct slices are not supported by this backend
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: core/src/hir/type_context.rs
|
||||
expression: output
|
||||
---
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "125df445fc304a116c17fd974712ca2410c8e580"
|
||||
},
|
||||
"path_in_vcs": "core"
|
||||
}
|
||||
Generated
Vendored
+48
-19
@@ -1,6 +1,23 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "annotate-snippets"
|
||||
version = "0.12.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f211a51805bc641f3ad5b7664c77d2547af685cc33b4cd8d31964027a46f13f1"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
@@ -16,9 +33,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "diplomat_core"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"annotate-snippets",
|
||||
"either",
|
||||
"insta",
|
||||
"proc-macro2",
|
||||
@@ -26,18 +43,7 @@ dependencies = [
|
||||
"serde",
|
||||
"smallvec",
|
||||
"strck",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -85,10 +91,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.94"
|
||||
name = "memchr"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
|
||||
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
@@ -129,7 +141,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 2.0.99",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -164,12 +176,29 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
+8
-6
@@ -11,9 +11,9 @@
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
rust-version = "1.88"
|
||||
name = "diplomat_core"
|
||||
version = "0.15.0"
|
||||
version = "0.16.1"
|
||||
authors = [
|
||||
"Shadaj Laddad <shadaj@users.noreply.github.com>",
|
||||
"Manish Goregaokar <manishsmail@gmail.com>",
|
||||
@@ -43,13 +43,14 @@ all-features = true
|
||||
|
||||
[features]
|
||||
hir = ["either"]
|
||||
pretty-print = ["annotate-snippets"]
|
||||
|
||||
[lib]
|
||||
name = "diplomat_core"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.displaydoc]
|
||||
version = "0.2"
|
||||
[dependencies.annotate-snippets]
|
||||
version = "0.12.13"
|
||||
optional = true
|
||||
|
||||
[dependencies.either]
|
||||
@@ -58,7 +59,8 @@ optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.proc-macro2]
|
||||
version = "1.0.27"
|
||||
version = "1.0.106"
|
||||
features = ["span-locations"]
|
||||
|
||||
[dependencies.quote]
|
||||
version = "1.0"
|
||||
@@ -79,7 +81,7 @@ version = "1.0"
|
||||
features = ["ident"]
|
||||
|
||||
[dependencies.syn]
|
||||
version = "2"
|
||||
version = "3.0"
|
||||
features = [
|
||||
"full",
|
||||
"extra-traits",
|
||||
Generated
Vendored
+5
-3
@@ -17,19 +17,21 @@ path = "src/lib.rs"
|
||||
[features]
|
||||
# Enable the higher level IR
|
||||
hir = ["either"]
|
||||
# Pretty print errors
|
||||
pretty-print = ["annotate-snippets"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[dependencies]
|
||||
syn = { version = "2", features = [ "full", "extra-traits" ] }
|
||||
syn = { version = "3.0", features = [ "full", "extra-traits" ] }
|
||||
quote = "1.0"
|
||||
proc-macro2 = "1.0.27"
|
||||
proc-macro2 = { version = "1.0.106", features = ["span-locations"] }
|
||||
serde = { version = "1.0", features = ["derive", "alloc"], default-features = false }
|
||||
displaydoc = { version = "0.2", optional = true }
|
||||
smallvec = "1.9.0"
|
||||
strck = { version = "1.0", features = ["ident"] }
|
||||
either = {version = "1.9.0", optional = true, default-features = false}
|
||||
annotate-snippets = { version = "0.12.13", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
insta = { version = "1.7.1", features = ["yaml"] }
|
||||
File renamed without changes.
File renamed without changes.
Vendored
File renamed without changes.
Vendored
+1
@@ -6,6 +6,7 @@ Diplomat supports generating bindings from Rust to:
|
||||
- C++
|
||||
- Dart
|
||||
- Javascript/Typescript
|
||||
- .NET (C#)
|
||||
- Kotlin (using JNA)
|
||||
- Python (using [nanobind](https://nanobind.readthedocs.io/en/latest/index.html))
|
||||
|
||||
+81
-20
@@ -6,8 +6,13 @@ use std::borrow::Cow;
|
||||
use std::convert::Infallible;
|
||||
use std::str::FromStr;
|
||||
use syn::parse::{Error as ParseError, Parse, ParseStream};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Attribute, Expr, Ident, Lit, LitStr, Meta, MetaList, MetaNameValue, Token};
|
||||
|
||||
use crate::ast::idents::{FromWithSpan, IntoWithSpan};
|
||||
use crate::ast::logging::{create_report, AstReport, ContextLocation};
|
||||
use crate::ast::SpanLocation;
|
||||
|
||||
/// The list of attributes on a type. All attributes except `attrs` (HIR attrs) are
|
||||
/// potentially read by the diplomat macro and the AST backends, anything that is not should
|
||||
/// be added as an HIR attribute ([`crate::hir::Attrs`]).
|
||||
@@ -53,6 +58,8 @@ pub struct Attrs {
|
||||
|
||||
/// For use by [`crate::hir::Attrs::demo_attrs`]
|
||||
pub demo_attrs: Vec<DemoBackendAttr>,
|
||||
|
||||
pub(crate) includes: Vec<IncludeAttribute>,
|
||||
}
|
||||
|
||||
impl Attrs {
|
||||
@@ -67,6 +74,7 @@ impl Attrs {
|
||||
Attr::CRename(rename) => self.abi_rename.extend(&rename),
|
||||
Attr::DemoBackend(attr) => self.demo_attrs.push(attr),
|
||||
Attr::Deprecated(msg) => self.deprecated = Some(msg),
|
||||
Attr::Include(inc) => self.includes.push(inc),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,24 +107,25 @@ impl Attrs {
|
||||
attrs,
|
||||
abi_rename,
|
||||
demo_attrs,
|
||||
includes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn add_attrs(&mut self, attrs: &[Attribute]) {
|
||||
for attr in syn_attr_to_ast_attr(attrs) {
|
||||
pub(crate) fn add_attrs(&mut self, attrs: &[Attribute], attrs_location: &SpanLocation) {
|
||||
for attr in syn_attr_to_ast_attr(attrs, attrs_location) {
|
||||
self.add_attr(attr)
|
||||
}
|
||||
}
|
||||
pub(crate) fn from_attrs(attrs: &[Attribute]) -> Self {
|
||||
pub(crate) fn from_attrs(attrs: &[Attribute], attrs_location: &SpanLocation) -> Self {
|
||||
let mut this = Self::default();
|
||||
this.add_attrs(attrs);
|
||||
this.add_attrs(attrs, attrs_location);
|
||||
this
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&[Attribute]> for Attrs {
|
||||
fn from(other: &[Attribute]) -> Self {
|
||||
Self::from_attrs(other)
|
||||
impl FromWithSpan<&[Attribute]> for Attrs {
|
||||
fn spanned_from(other: &[Attribute], module_location: &SpanLocation) -> Self {
|
||||
Self::from_attrs(other, module_location)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,36 +136,64 @@ enum Attr {
|
||||
CRename(RenameAttr),
|
||||
DemoBackend(DemoBackendAttr),
|
||||
Deprecated(String),
|
||||
Include(IncludeAttribute),
|
||||
// More goes here
|
||||
}
|
||||
|
||||
fn syn_attr_to_ast_attr(attrs: &[Attribute]) -> impl Iterator<Item = Attr> + '_ {
|
||||
fn syn_attr_to_ast_attr<'a>(
|
||||
attrs: &'a [Attribute],
|
||||
attrs_location: &'a SpanLocation,
|
||||
) -> impl Iterator<Item = Attr> + 'a {
|
||||
let cfg_path: syn::Path = syn::parse_str("cfg").unwrap();
|
||||
let dattr_path: syn::Path = syn::parse_str("diplomat::attr").unwrap();
|
||||
let diplomat_cfg_path: syn::Path = syn::parse_str("diplomat::cfg").unwrap();
|
||||
let crename_attr: syn::Path = syn::parse_str("diplomat::abi_rename").unwrap();
|
||||
let demo_path: syn::Path = syn::parse_str("diplomat::demo").unwrap();
|
||||
let include_path: syn::Path = syn::parse_str("diplomat::include").unwrap();
|
||||
let deprecated: syn::Path = syn::parse_str("deprecated").unwrap();
|
||||
attrs.iter().filter_map(move |a| {
|
||||
if a.path() == &cfg_path {
|
||||
Some(Attr::Cfg(a.clone()))
|
||||
} else if a.path() == &dattr_path {
|
||||
Some(Attr::DiplomatBackend(
|
||||
a.parse_args()
|
||||
.expect("Failed to parse malformed diplomat::attr"),
|
||||
))
|
||||
Some(Attr::DiplomatBackend(a.parse_args().unwrap_or_else(|e| {
|
||||
create_report(AstReport::new(
|
||||
"Failed to parse diplomat::attr".into(),
|
||||
Some(e.span().spanned_into(attrs_location)),
|
||||
e.to_string(),
|
||||
vec![ContextLocation::new(
|
||||
a.span().spanned_into(attrs_location),
|
||||
"".into(),
|
||||
)],
|
||||
));
|
||||
})))
|
||||
} else if a.path() == &diplomat_cfg_path {
|
||||
Some(Attr::DiplomatCFGBackend(
|
||||
a.parse_args()
|
||||
.expect("Failed to parse malformed diplomat::cfg"),
|
||||
))
|
||||
Some(Attr::DiplomatCFGBackend(a.parse_args().unwrap_or_else(
|
||||
|e| {
|
||||
create_report(AstReport::new(
|
||||
"Failed to parse diplomat::cfg".into(),
|
||||
Some(e.span().spanned_into(attrs_location)),
|
||||
e.to_string(),
|
||||
vec![ContextLocation::new(
|
||||
a.span().spanned_into(attrs_location),
|
||||
"".into(),
|
||||
)],
|
||||
));
|
||||
},
|
||||
)))
|
||||
} else if a.path() == &crename_attr {
|
||||
Some(Attr::CRename(RenameAttr::from_meta(&a.meta).unwrap()))
|
||||
} else if a.path() == &demo_path {
|
||||
Some(Attr::DemoBackend(
|
||||
a.parse_args()
|
||||
.expect("Failed to parse malformed diplomat::demo"),
|
||||
))
|
||||
Some(Attr::DemoBackend(a.parse_args().unwrap_or_else(|e| {
|
||||
create_report(AstReport::new(
|
||||
"Failed to parse diplomat::demo".into(),
|
||||
Some(e.span().spanned_into(attrs_location)),
|
||||
e.to_string(),
|
||||
vec![ContextLocation::new(
|
||||
a.span().spanned_into(attrs_location),
|
||||
"".into(),
|
||||
)],
|
||||
));
|
||||
})))
|
||||
} else if a.path() == &deprecated {
|
||||
if let Some(Meta::NameValue(MetaNameValue {
|
||||
value:
|
||||
@@ -174,6 +211,18 @@ fn syn_attr_to_ast_attr(attrs: &[Attribute]) -> impl Iterator<Item = Attr> + '_
|
||||
} else {
|
||||
Some(Attr::Deprecated("deprecated".into()))
|
||||
}
|
||||
} else if a.path() == &include_path {
|
||||
Some(Attr::Include(a.parse_args().unwrap_or_else(|e| {
|
||||
create_report(AstReport::new(
|
||||
"Failed to parse diplomat::include".into(),
|
||||
Some(e.span().spanned_into(attrs_location)),
|
||||
e.to_string(),
|
||||
vec![ContextLocation::new(
|
||||
a.span().spanned_into(attrs_location),
|
||||
"".into(),
|
||||
)],
|
||||
));
|
||||
})))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -487,6 +536,18 @@ impl<'a> StandardAttribute<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
|
||||
pub(crate) struct IncludeAttribute {
|
||||
pub(crate) path: String,
|
||||
}
|
||||
|
||||
impl Parse for IncludeAttribute {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let st = input.parse::<LitStr>()?;
|
||||
Ok(Self { path: st.value() })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use insta;
|
||||
+24
-5
@@ -1,10 +1,14 @@
|
||||
use crate::ast::attrs::DiplomatBackendAttrCfg;
|
||||
use crate::ast::idents::IntoWithSpan;
|
||||
use crate::ast::logging::{create_report, AstReport, ContextLocation};
|
||||
use crate::ast::SpanLocation;
|
||||
|
||||
use super::Path;
|
||||
use core::fmt;
|
||||
use quote::ToTokens;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use syn::parse::{self, Parse, ParseStream};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Attribute, Ident, Meta, Token};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
|
||||
@@ -27,8 +31,11 @@ impl Default for DocumentationSection {
|
||||
pub struct Docs(pub Vec<DocumentationSection>, pub Vec<RustLink>);
|
||||
|
||||
impl Docs {
|
||||
pub fn from_attrs(attrs: &[Attribute]) -> Self {
|
||||
Self(Self::get_doc_lines(attrs), Self::get_rust_link(attrs))
|
||||
pub fn from_attrs(attrs: &[Attribute], attrs_location: &SpanLocation) -> Self {
|
||||
Self(
|
||||
Self::get_doc_lines(attrs),
|
||||
Self::get_rust_link(attrs, attrs_location),
|
||||
)
|
||||
}
|
||||
|
||||
fn get_doc_lines(attrs: &[Attribute]) -> Vec<DocumentationSection> {
|
||||
@@ -65,11 +72,23 @@ impl Docs {
|
||||
sections
|
||||
}
|
||||
|
||||
fn get_rust_link(attrs: &[Attribute]) -> Vec<RustLink> {
|
||||
fn get_rust_link(attrs: &[Attribute], attrs_location: &SpanLocation) -> Vec<RustLink> {
|
||||
attrs
|
||||
.iter()
|
||||
.filter(|i| i.path().to_token_stream().to_string() == "diplomat :: rust_link")
|
||||
.map(|i| i.parse_args().expect("Malformed attribute"))
|
||||
.map(|i| {
|
||||
i.parse_args().unwrap_or_else(|e| {
|
||||
create_report(AstReport::new(
|
||||
"Could not read rust link".into(),
|
||||
Some(e.span().spanned_into(attrs_location)),
|
||||
e.to_string(),
|
||||
vec![ContextLocation::new(
|
||||
i.span().spanned_into(attrs_location),
|
||||
"".into(),
|
||||
)],
|
||||
));
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -104,7 +123,7 @@ pub struct RustLink {
|
||||
impl Parse for RustLink {
|
||||
fn parse(input: ParseStream<'_>) -> parse::Result<Self> {
|
||||
let path = input.parse()?;
|
||||
let path = Path::from_syn(&path);
|
||||
let path = Path::from_syn(&path, &super::SpanLocation::LocalSource(input.to_string()));
|
||||
let _comma: Token![,] = input.parse()?;
|
||||
let ty_ident: Ident = input.parse()?;
|
||||
let typ = match &*ty_ident.to_string() {
|
||||
+30
-12
@@ -1,5 +1,9 @@
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::ast::idents::IntoWithSpan;
|
||||
use crate::ast::logging::create_simple_report;
|
||||
use crate::ast::SpanLocation;
|
||||
|
||||
use super::docs::Docs;
|
||||
use super::{AttrInheritContext, Attrs, Ident, Method};
|
||||
use quote::ToTokens;
|
||||
@@ -18,29 +22,37 @@ pub struct Enum {
|
||||
|
||||
impl Enum {
|
||||
/// Extract an [`Enum`] metadata value from an AST node.
|
||||
pub fn new(enm: &syn::ItemEnum, parent_attrs: &Attrs) -> Enum {
|
||||
pub fn new(enm: &syn::ItemEnum, parent_attrs: &Attrs, module_location: &SpanLocation) -> Enum {
|
||||
let mut last_discriminant = -1;
|
||||
if !enm.generics.params.is_empty() {
|
||||
// Generic types are not allowed.
|
||||
// Assuming all enums cannot have lifetimes? We don't even have a
|
||||
// `lifetimes` field. If we change our minds we can adjust this later
|
||||
// and update the `CustomType::lifetimes` API accordingly.
|
||||
panic!("Enums cannot have generic parameters");
|
||||
create_simple_report(
|
||||
(&enm.ident).spanned_into(module_location),
|
||||
"Enums cannot have generic parameters.".into(),
|
||||
"Suggestion: remove generics".into(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut attrs = parent_attrs.clone();
|
||||
attrs.add_attrs(&enm.attrs);
|
||||
attrs.add_attrs(&enm.attrs, module_location);
|
||||
let variant_parent_attrs = attrs.attrs_for_inheritance(AttrInheritContext::Variant);
|
||||
|
||||
Enum {
|
||||
name: (&enm.ident).into(),
|
||||
docs: Docs::from_attrs(&enm.attrs),
|
||||
name: (&enm.ident).spanned_into(module_location),
|
||||
docs: Docs::from_attrs(&enm.attrs, module_location),
|
||||
variants: enm
|
||||
.variants
|
||||
.iter()
|
||||
.map(|v| {
|
||||
if !matches!(v.fields, syn::Fields::Unit) {
|
||||
panic!("Enums cannot have fields, we only support C-like enums");
|
||||
create_simple_report(
|
||||
(&v.ident).spanned_into(module_location),
|
||||
"Enums cannot have fields, we only support C-like enums".into(),
|
||||
"Remove field variant".into(),
|
||||
);
|
||||
}
|
||||
let new_discriminant = v
|
||||
.discriminant
|
||||
@@ -52,18 +64,22 @@ impl Enum {
|
||||
if let Ok(syn::Lit::Int(ref lit_int)) = lit {
|
||||
lit_int.base10_parse::<isize>().unwrap()
|
||||
} else {
|
||||
panic!("Expected a discriminant to be a constant integer");
|
||||
create_simple_report(
|
||||
(&v.ident).spanned_into(module_location),
|
||||
"Enum discriminants must be constant integers".into(),
|
||||
"Expected discriminant to be a constant integer".into(),
|
||||
);
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| last_discriminant + 1);
|
||||
|
||||
last_discriminant = new_discriminant;
|
||||
let mut v_attrs = variant_parent_attrs.clone();
|
||||
v_attrs.add_attrs(&v.attrs);
|
||||
v_attrs.add_attrs(&v.attrs, module_location);
|
||||
(
|
||||
(&v.ident).into(),
|
||||
(&v.ident).spanned_into(module_location),
|
||||
new_discriminant,
|
||||
Docs::from_attrs(&v.attrs),
|
||||
Docs::from_attrs(&v.attrs, module_location),
|
||||
v_attrs,
|
||||
)
|
||||
})
|
||||
@@ -98,7 +114,8 @@ mod tests {
|
||||
Def
|
||||
}
|
||||
},
|
||||
&Default::default()
|
||||
&Default::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
});
|
||||
}
|
||||
@@ -120,7 +137,8 @@ mod tests {
|
||||
Jkl = 2,
|
||||
}
|
||||
},
|
||||
&Default::default()
|
||||
&Default::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
});
|
||||
}
|
||||
+41
-14
@@ -1,7 +1,11 @@
|
||||
use serde::Serialize;
|
||||
use syn::ItemFn;
|
||||
|
||||
use crate::ast::{Attrs, Docs, Ident, LifetimeEnv, Param, PathType, TypeName};
|
||||
use crate::ast::{
|
||||
idents::{FromWithSpan, IntoWithSpan},
|
||||
logging::{create_report, AstReport, ContextLocation},
|
||||
Attrs, Docs, Ident, LifetimeEnv, Param, PathType, SpanLocation, TypeName,
|
||||
};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -19,14 +23,26 @@ pub struct Function {
|
||||
}
|
||||
|
||||
impl Function {
|
||||
pub(crate) fn from_syn(f: &ItemFn, parent_attrs: &Attrs) -> Function {
|
||||
let ident: Ident = (&f.sig.ident).into();
|
||||
if f.sig.receiver().is_some() {
|
||||
panic!("Cannot use self parameter in free function {ident:?}")
|
||||
pub(crate) fn from_syn(
|
||||
f: &ItemFn,
|
||||
parent_attrs: &Attrs,
|
||||
module_location: &SpanLocation,
|
||||
) -> Function {
|
||||
let ident: Ident = (&f.sig.ident).spanned_into(module_location);
|
||||
if let Some(recv) = f.sig.receiver() {
|
||||
create_report(AstReport::new(
|
||||
"Cannot use self parameter in free function.".into(),
|
||||
Some(f.sig.ident.span().spanned_into(module_location)),
|
||||
"".into(),
|
||||
vec![ContextLocation::new(
|
||||
recv.self_token.span.spanned_into(module_location),
|
||||
"Suggestion: remove self param.".into(),
|
||||
)],
|
||||
));
|
||||
}
|
||||
|
||||
let mut attrs = parent_attrs.clone();
|
||||
attrs.add_attrs(&f.attrs);
|
||||
attrs.add_attrs(&f.attrs, module_location);
|
||||
|
||||
let concat_func_ident = if attrs.abi_rename.is_empty() {
|
||||
format!("diplomat_external_{ident}")
|
||||
@@ -36,7 +52,7 @@ impl Function {
|
||||
|
||||
let extern_ident = syn::Ident::new(&concat_func_ident, f.sig.ident.span());
|
||||
|
||||
let path_type = PathType::from(&f.sig);
|
||||
let path_type = PathType::spanned_from(&f.sig, module_location);
|
||||
|
||||
let all_params = f
|
||||
.sig
|
||||
@@ -44,7 +60,9 @@ impl Function {
|
||||
.iter()
|
||||
.filter_map(|a| match a {
|
||||
syn::FnArg::Receiver(_) => None,
|
||||
syn::FnArg::Typed(ref t) => Some(Param::from_syn(t, path_type.clone())),
|
||||
syn::FnArg::Typed(ref t) => {
|
||||
Some(Param::from_syn(t, path_type.clone(), module_location))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -52,20 +70,26 @@ impl Function {
|
||||
syn::ReturnType::Type(_, return_typ) => Some(TypeName::from_syn(
|
||||
return_typ.as_ref(),
|
||||
Some(path_type.clone()),
|
||||
module_location,
|
||||
)),
|
||||
syn::ReturnType::Default => None,
|
||||
};
|
||||
|
||||
let lifetimes = LifetimeEnv::from_function_item(f, &all_params[..], output_type.as_ref());
|
||||
let lifetimes = LifetimeEnv::from_function_item(
|
||||
f,
|
||||
&all_params[..],
|
||||
output_type.as_ref(),
|
||||
module_location,
|
||||
);
|
||||
|
||||
Self {
|
||||
name: ident,
|
||||
abi_name: (&extern_ident).into(),
|
||||
abi_name: (&extern_ident).spanned_into(module_location),
|
||||
params: all_params,
|
||||
output_type,
|
||||
lifetimes,
|
||||
attrs,
|
||||
docs: Docs::from_attrs(&f.attrs),
|
||||
docs: Docs::from_attrs(&f.attrs, module_location),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,7 +110,8 @@ mod tests {
|
||||
|
||||
}
|
||||
},
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
}
|
||||
|
||||
@@ -98,7 +123,8 @@ mod tests {
|
||||
|
||||
}
|
||||
},
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
}
|
||||
|
||||
@@ -110,7 +136,8 @@ mod tests {
|
||||
|
||||
}
|
||||
},
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
use quote::{ToTokens, TokenStreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::{Borrow, Cow};
|
||||
use std::fmt;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Equivalent to `proc_macro2::LineColumn`
|
||||
#[derive(Hash, Eq, PartialEq, Serialize, Clone, Debug)]
|
||||
pub struct LineColumn {
|
||||
/// The 1-indexed row of where we are in a file
|
||||
/// (Alternatively, the offset by the number of newline characters + 1)
|
||||
pub line: usize,
|
||||
/// The 0-indexed column of where we are in a file
|
||||
/// (Alternatively, the offset by newline characters plus this amount)
|
||||
pub col: usize,
|
||||
}
|
||||
|
||||
/// Equivalent to `proc_macro2::Span`.
|
||||
#[derive(Hash, Eq, PartialEq, Serialize, Clone, Debug)]
|
||||
pub struct Span {
|
||||
pub start: LineColumn,
|
||||
pub end: LineColumn,
|
||||
/// The range in bytes of the span. Used mostly to determine length.
|
||||
pub range: Range<usize>,
|
||||
/// Equivalent to `proc_macro2::Span::file`, but we have to allow for internal testing or
|
||||
/// spaces where we simply don't know where we've acquired this Span from.
|
||||
pub span_location: SpanLocation,
|
||||
}
|
||||
|
||||
#[derive(Hash, Eq, PartialEq, Serialize, Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum SpanLocation {
|
||||
/// For testing or when accessing SpanLocation is not possible.
|
||||
/// Will render as <location unknown> on rendering an error.
|
||||
None,
|
||||
/// An absolute path to a rust file.
|
||||
FilePath(String),
|
||||
/// Does not exist in a file, full source text that is used locally.
|
||||
LocalSource(String),
|
||||
}
|
||||
|
||||
/// An identifier, analogous to `syn::Ident` and `proc_macro2::Ident`.
|
||||
#[derive(Eq, Serialize, Clone, Debug)]
|
||||
pub struct Ident(Cow<'static, str>, Option<Span>);
|
||||
|
||||
impl Ident {
|
||||
/// Validate a string
|
||||
fn validate(string: &str) -> syn::Result<()> {
|
||||
syn::parse_str::<syn::Ident>(string).map(|_| {})
|
||||
}
|
||||
|
||||
pub fn to_syn(&self) -> syn::Ident {
|
||||
syn::Ident::new(self.as_str(), proc_macro2::Span::call_site())
|
||||
}
|
||||
|
||||
/// Get the `&str` representation.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn span(&self) -> Option<Span> {
|
||||
self.1.clone()
|
||||
}
|
||||
|
||||
/// An [`Ident`] containing "this".
|
||||
pub const THIS: Self = Ident(Cow::Borrowed("this"), None);
|
||||
}
|
||||
|
||||
/// Helper
|
||||
pub(crate) trait FromWithSpan<T>: Sized {
|
||||
fn spanned_from(value: T, module_location: &SpanLocation) -> Self;
|
||||
}
|
||||
|
||||
pub(crate) trait IntoWithSpan<T>: Sized {
|
||||
fn spanned_into(self, module_location: &SpanLocation) -> T;
|
||||
}
|
||||
|
||||
impl<T, U> IntoWithSpan<U> for T
|
||||
where
|
||||
U: FromWithSpan<T>,
|
||||
{
|
||||
fn spanned_into(self, module_location: &SpanLocation) -> U {
|
||||
FromWithSpan::spanned_from(self, module_location)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Ident {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Ident {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.0.cmp(&other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Ident {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Ident {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.eq(&other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for Ident {
|
||||
fn from(string: &'static str) -> Self {
|
||||
Self::validate(string).unwrap();
|
||||
Self(Cow::from(string), None)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Ident {
|
||||
fn from(string: String) -> Self {
|
||||
Self::validate(&string).unwrap();
|
||||
Self(Cow::from(string), None)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Ident {
|
||||
/// The derived `Deserialize` allows for creating `Ident`s that do not uphold
|
||||
/// the proper invariants. This custom impl ensures that this cannot happen.
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
Ok(Ident::from(String::deserialize(deserializer)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Borrow<str> for Ident {
|
||||
fn borrow(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Ident {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
self.as_str().fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWithSpan<&syn::Ident> for Ident {
|
||||
fn spanned_from(ident: &syn::Ident, span_location: &SpanLocation) -> Self {
|
||||
Self(
|
||||
Cow::from(ident.to_string()),
|
||||
Some(ident.span().spanned_into(span_location)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWithSpan<proc_macro2::Span> for Span {
|
||||
fn spanned_from(span: proc_macro2::Span, span_location: &SpanLocation) -> Self {
|
||||
let start = span.start();
|
||||
let end = span.end();
|
||||
Span {
|
||||
start: LineColumn {
|
||||
line: start.line,
|
||||
col: start.column,
|
||||
},
|
||||
end: LineColumn {
|
||||
line: end.line,
|
||||
col: end.column,
|
||||
},
|
||||
range: span.byte_range(),
|
||||
span_location: span_location.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for Ident {
|
||||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
|
||||
tokens.append(self.to_syn());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::ast::Module;
|
||||
|
||||
#[test]
|
||||
fn test_span_parsing() {
|
||||
let crate_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let file = std::fs::read_to_string(
|
||||
std::path::Path::new(crate_dir).join("src/ast/snapshots/span_testing.txt"),
|
||||
)
|
||||
.expect("Could not read file");
|
||||
let f = syn::parse_str::<syn::ItemMod>(&file);
|
||||
let inner = match f {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
let span = e.span();
|
||||
panic!(
|
||||
"File parsing error: {e:?} ./snapshots/span_testing.txt:{}:{}",
|
||||
span.start().line,
|
||||
span.start().column
|
||||
)
|
||||
}
|
||||
};
|
||||
let file = Module::from_syn(
|
||||
&inner,
|
||||
true,
|
||||
None,
|
||||
&super::SpanLocation::FilePath("./snapshots/span_testing.txt".into()),
|
||||
);
|
||||
insta::assert_yaml_snapshot!(file);
|
||||
}
|
||||
}
|
||||
+102
-35
@@ -2,6 +2,13 @@ use proc_macro2::Span;
|
||||
use quote::{quote, ToTokens};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use syn::spanned::Spanned;
|
||||
|
||||
use crate::ast::{
|
||||
idents::{FromWithSpan, IntoWithSpan},
|
||||
logging::{create_report, AstReport, ContextLocation},
|
||||
SpanLocation,
|
||||
};
|
||||
|
||||
use super::{Attrs, Docs, Ident, Param, SelfParam, TraitSelfParam, TypeName};
|
||||
|
||||
@@ -34,14 +41,16 @@ impl<'de> Deserialize<'de> for NamedLifetime {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&syn::Lifetime> for NamedLifetime {
|
||||
fn from(lt: &syn::Lifetime) -> Self {
|
||||
Lifetime::from(lt).to_named().expect("cannot be static")
|
||||
impl FromWithSpan<&syn::Lifetime> for NamedLifetime {
|
||||
fn spanned_from(lt: &syn::Lifetime, module_location: &SpanLocation) -> Self {
|
||||
Lifetime::spanned_from(lt, module_location)
|
||||
.to_named()
|
||||
.expect("cannot be static")
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&NamedLifetime> for NamedLifetime {
|
||||
fn from(this: &NamedLifetime) -> Self {
|
||||
impl FromWithSpan<&NamedLifetime> for NamedLifetime {
|
||||
fn spanned_from(this: &NamedLifetime, _module_location: &SpanLocation) -> Self {
|
||||
this.clone()
|
||||
}
|
||||
}
|
||||
@@ -100,15 +109,16 @@ impl LifetimeEnv {
|
||||
self_param: Option<&SelfParam>,
|
||||
params: &[Param],
|
||||
return_type: Option<&TypeName>,
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
let mut this = LifetimeEnv::new();
|
||||
// The impl generics _must_ be loaded into the env first, since the method
|
||||
// generics might use lifetimes defined in the impl, and `extend_generics`
|
||||
// panics if `'a: 'b` where `'b` isn't declared by the time it finishes.
|
||||
if let Some(generics) = impl_generics {
|
||||
this.extend_generics(generics);
|
||||
this.extend_generics(generics, module_location);
|
||||
}
|
||||
this.extend_generics(&method.sig.generics);
|
||||
this.extend_generics(&method.sig.generics, module_location);
|
||||
|
||||
if let Some(self_param) = self_param {
|
||||
this.extend_implicit_lifetime_bounds(&self_param.to_typename(), None);
|
||||
@@ -141,6 +151,8 @@ impl LifetimeEnv {
|
||||
this.extend_implicit_lifetime_bounds(return_type, None);
|
||||
}
|
||||
} else {
|
||||
// Currently this is impossible to reach,
|
||||
// we only call from_trait_item when trait_fct_item is syn::TraitItem::Fn
|
||||
panic!(
|
||||
"Diplomat traits can only have associated methods and no other associated items."
|
||||
)
|
||||
@@ -148,9 +160,17 @@ impl LifetimeEnv {
|
||||
this
|
||||
}
|
||||
|
||||
pub fn from_trait(trt: &syn::ItemTrait) -> Self {
|
||||
if trt.generics.lifetimes().next().is_some() {
|
||||
panic!("Diplomat traits are not allowed to have any lifetime parameters")
|
||||
pub fn from_trait(trt: &syn::ItemTrait, module_location: &SpanLocation) -> Self {
|
||||
if let Some(lt) = trt.generics.lifetimes().next() {
|
||||
create_report(AstReport::new(
|
||||
"Diplomat traits are not allowed to have any lifetime parameters.".into(),
|
||||
Some(trt.ident.span().spanned_into(module_location)),
|
||||
"".into(),
|
||||
vec![ContextLocation::new(
|
||||
lt.span().spanned_into(module_location),
|
||||
"Remove lifetime annotations".into(),
|
||||
)],
|
||||
));
|
||||
}
|
||||
LifetimeEnv::new()
|
||||
}
|
||||
@@ -158,9 +178,10 @@ impl LifetimeEnv {
|
||||
pub fn from_enum_item(
|
||||
enm: &syn::ItemEnum,
|
||||
variant_fields: &[(Option<Ident>, TypeName, Docs, Attrs)],
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
let mut this = LifetimeEnv::new();
|
||||
this.extend_generics(&enm.generics);
|
||||
this.extend_generics(&enm.generics, module_location);
|
||||
for (_, typ, _, _) in variant_fields {
|
||||
this.extend_implicit_lifetime_bounds(typ, None);
|
||||
}
|
||||
@@ -173,9 +194,10 @@ impl LifetimeEnv {
|
||||
pub fn from_struct_item(
|
||||
strct: &syn::ItemStruct,
|
||||
fields: &[(Ident, TypeName, Docs, Attrs)],
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
let mut this = LifetimeEnv::new();
|
||||
this.extend_generics(&strct.generics);
|
||||
this.extend_generics(&strct.generics, module_location);
|
||||
for (_, typ, _, _) in fields {
|
||||
this.extend_implicit_lifetime_bounds(typ, None);
|
||||
}
|
||||
@@ -186,9 +208,10 @@ impl LifetimeEnv {
|
||||
f: &syn::ItemFn,
|
||||
params: &[Param],
|
||||
return_type: Option<&TypeName>,
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
let mut this = LifetimeEnv::new();
|
||||
this.extend_generics(&f.sig.generics);
|
||||
this.extend_generics(&f.sig.generics, module_location);
|
||||
for param in params {
|
||||
this.extend_implicit_lifetime_bounds(¶m.ty, None);
|
||||
}
|
||||
@@ -246,23 +269,47 @@ impl LifetimeEnv {
|
||||
}
|
||||
|
||||
/// Add the lifetimes from generic parameters and where bounds.
|
||||
fn extend_generics(&mut self, generics: &syn::Generics) {
|
||||
fn extend_generics(&mut self, generics: &syn::Generics, module_location: &SpanLocation) {
|
||||
let generic_bounds = generics.params.iter().map(|generic| match generic {
|
||||
syn::GenericParam::Type(_) => panic!("generic types are unsupported"),
|
||||
syn::GenericParam::Type(_) => {
|
||||
create_report(AstReport::new(
|
||||
"Generic types are unsupported.".into(),
|
||||
Some(generic.span().spanned_into(module_location)),
|
||||
"Suggestion: Remove generic type.".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
syn::GenericParam::Lifetime(def) => (&def.lifetime, &def.bounds),
|
||||
syn::GenericParam::Const(_) => panic!("const generics are unsupported"),
|
||||
syn::GenericParam::Const(_) => {
|
||||
create_report(AstReport::new(
|
||||
"Const generics are unsupported.".into(),
|
||||
Some(generic.span().spanned_into(module_location)),
|
||||
"Suggestion: Remove const generic.".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
let generic_defs = generic_bounds.clone().map(|(lifetime, _)| lifetime);
|
||||
|
||||
self.extend_lifetimes(generic_defs);
|
||||
self.extend_lifetimes(generic_defs, module_location);
|
||||
self.extend_bounds(generic_bounds);
|
||||
|
||||
if let Some(ref where_clause) = generics.where_clause {
|
||||
self.extend_bounds(where_clause.predicates.iter().map(|pred| match pred {
|
||||
syn::WherePredicate::Type(_) => panic!("trait bounds are unsupported"),
|
||||
syn::WherePredicate::Type(_) => create_report(AstReport::new(
|
||||
"Trait bounds are unsupported.".into(),
|
||||
Some(pred.span().spanned_into(module_location)),
|
||||
"Suggestion: Remove type predicate.".into(),
|
||||
vec![],
|
||||
)),
|
||||
syn::WherePredicate::Lifetime(pred) => (&pred.lifetime, &pred.bounds),
|
||||
_ => panic!("Found unknown kind of where predicate"),
|
||||
_ => create_report(AstReport::new(
|
||||
"Unrecognized where predicate.".into(),
|
||||
Some(pred.span().spanned_into(module_location)),
|
||||
"".into(),
|
||||
vec![],
|
||||
)),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -303,22 +350,30 @@ impl LifetimeEnv {
|
||||
}
|
||||
|
||||
/// Add isolated lifetimes to the graph.
|
||||
fn extend_lifetimes<'a, L, I>(&mut self, iter: I)
|
||||
fn extend_lifetimes<'a, L, I>(&mut self, iter: I, module_location: &SpanLocation)
|
||||
where
|
||||
NamedLifetime: PartialEq<L> + From<&'a L>,
|
||||
NamedLifetime: PartialEq<L> + FromWithSpan<&'a L>,
|
||||
L: 'a,
|
||||
I: IntoIterator<Item = &'a L>,
|
||||
{
|
||||
for lifetime in iter {
|
||||
if self.id(lifetime).is_some() {
|
||||
panic!(
|
||||
"lifetime name `{}` declared twice in the same scope",
|
||||
NamedLifetime::from(lifetime)
|
||||
);
|
||||
if let Some(idx) = self.id(lifetime) {
|
||||
let context_locations = if let Some(sp) = self.nodes[idx].lifetime.0.span() {
|
||||
vec![ContextLocation::new(sp, "Defined first here.".into())]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let lt = NamedLifetime::spanned_from(lifetime, module_location);
|
||||
create_report(AstReport::new(
|
||||
"Lifetime declared twice in the same scope".into(),
|
||||
lt.0.span(),
|
||||
format!("Lifetime {lt} already exists."),
|
||||
context_locations,
|
||||
));
|
||||
}
|
||||
|
||||
self.nodes.push(LifetimeNode {
|
||||
lifetime: lifetime.into(),
|
||||
lifetime: lifetime.spanned_into(module_location),
|
||||
shorter: vec![],
|
||||
longer: vec![],
|
||||
});
|
||||
@@ -337,7 +392,7 @@ impl LifetimeEnv {
|
||||
/// only ever occur when deserializing an invalid [`LifetimeEnv`].
|
||||
fn extend_bounds<'a, L, B, I>(&mut self, iter: I)
|
||||
where
|
||||
NamedLifetime: PartialEq<L> + From<&'a L>,
|
||||
NamedLifetime: PartialEq<L>,
|
||||
L: 'a,
|
||||
B: IntoIterator<Item = &'a L>,
|
||||
I: IntoIterator<Item = (&'a L, B)>,
|
||||
@@ -427,8 +482,18 @@ impl<'de> Deserialize<'de> for LifetimeEnv {
|
||||
let m: BTreeMap<NamedLifetime, Vec<NamedLifetime>> =
|
||||
Deserialize::deserialize(deserializer)?;
|
||||
|
||||
let span_loc = if let Some(k) = m.keys().next() {
|
||||
if let Some(sp) = k.0.span() {
|
||||
sp.span_location
|
||||
} else {
|
||||
SpanLocation::None
|
||||
}
|
||||
} else {
|
||||
SpanLocation::None
|
||||
};
|
||||
|
||||
let mut this = LifetimeEnv::new();
|
||||
this.extend_lifetimes(m.keys());
|
||||
this.extend_lifetimes(m.keys(), &span_loc);
|
||||
this.extend_bounds(m.iter());
|
||||
Ok(this)
|
||||
}
|
||||
@@ -510,19 +575,21 @@ impl ToTokens for Lifetime {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&syn::Lifetime> for Lifetime {
|
||||
fn from(lt: &syn::Lifetime) -> Self {
|
||||
impl FromWithSpan<&syn::Lifetime> for Lifetime {
|
||||
fn spanned_from(lt: &syn::Lifetime, module_location: &SpanLocation) -> Self {
|
||||
if lt.ident == "static" {
|
||||
Self::Static
|
||||
} else {
|
||||
Self::Named(NamedLifetime((<.ident).into()))
|
||||
Self::Named(NamedLifetime((<.ident).spanned_into(module_location)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Option<syn::Lifetime>> for Lifetime {
|
||||
fn from(lt: &Option<syn::Lifetime>) -> Self {
|
||||
lt.as_ref().map(Into::into).unwrap_or(Self::Anonymous)
|
||||
impl FromWithSpan<&Option<syn::Lifetime>> for Lifetime {
|
||||
fn spanned_from(lt: &Option<syn::Lifetime>, module_location: &SpanLocation) -> Self {
|
||||
lt.as_ref()
|
||||
.map(|lt| lt.spanned_into(module_location))
|
||||
.unwrap_or(Self::Anonymous)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::ast::{idents::Span, Ident, SpanLocation};
|
||||
|
||||
/// For overwriting by tests.
|
||||
static WRITER: RwLock<&(dyn Fn() -> Box<dyn std::io::Write> + Send + Sync)> =
|
||||
RwLock::new(&(|| Box::new(std::io::stderr())));
|
||||
|
||||
pub(crate) struct ContextLocation {
|
||||
// Allow for pretty-print:
|
||||
#[allow(unused)]
|
||||
location: Span,
|
||||
// Allow for pretty-print:
|
||||
#[allow(unused)]
|
||||
label: String,
|
||||
}
|
||||
|
||||
impl ContextLocation {
|
||||
pub fn new(location: Span, label: String) -> Self {
|
||||
Self { location, label }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AstReport {
|
||||
title: String,
|
||||
primary_loc: Option<Span>,
|
||||
primary_label: String,
|
||||
// Used for pretty-printing, not ugly printing:
|
||||
#[allow(unused)]
|
||||
context_locations: Vec<ContextLocation>,
|
||||
}
|
||||
|
||||
impl AstReport {
|
||||
pub fn new(
|
||||
title: String,
|
||||
primary_loc: Option<Span>,
|
||||
primary_label: String,
|
||||
context_locations: Vec<ContextLocation>,
|
||||
) -> Self {
|
||||
Self {
|
||||
title,
|
||||
primary_loc,
|
||||
primary_label,
|
||||
context_locations,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_simple_report(id: Ident, title: String, label: String) -> ! {
|
||||
create_report(AstReport {
|
||||
title,
|
||||
primary_loc: id.span(),
|
||||
primary_label: label,
|
||||
context_locations: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
/// Bytes range has not been stabilized in Rust macro.
|
||||
/// We can't tell if we're in a proc macro context,
|
||||
/// so we just check if the range doesn't make sense:
|
||||
fn evaluate_bytes(sp: &super::idents::Span, src: &str) -> std::ops::Range<usize> {
|
||||
if sp.range.is_empty() && (sp.start.line != sp.end.line || sp.end.col - sp.start.col > 0) {
|
||||
match sp.span_location {
|
||||
SpanLocation::None => 0..0,
|
||||
_ => {
|
||||
// Need an accurate byte count that accounts for both:
|
||||
// CRLF and LF endings, so we just make sure to split on the end at `\n` (LF):
|
||||
let split = src.split_inclusive('\n');
|
||||
let mut start_byte = 0usize;
|
||||
let mut end_byte = src.len();
|
||||
let mut running_byte_total = 0usize;
|
||||
for (idx, st) in split.enumerate() {
|
||||
if (idx + 1) == sp.start.line {
|
||||
start_byte = running_byte_total + sp.start.col;
|
||||
}
|
||||
if (idx + 1) == sp.end.line {
|
||||
end_byte = running_byte_total + sp.end.col;
|
||||
break;
|
||||
}
|
||||
running_byte_total += st.len();
|
||||
}
|
||||
start_byte..end_byte
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sp.range.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_report(report: AstReport) -> ! {
|
||||
use std::io::Write;
|
||||
let mut out = WRITER.read().unwrap()();
|
||||
|
||||
let span = report.primary_loc;
|
||||
let src = if let Some(sp) = &span {
|
||||
match &sp.span_location {
|
||||
SpanLocation::FilePath(f) => {
|
||||
let st = std::fs::read_to_string(f);
|
||||
if let Ok(s) = st {
|
||||
s
|
||||
} else {
|
||||
panic!("Could not read source file {f}: {:?}", st.unwrap_err());
|
||||
}
|
||||
}
|
||||
SpanLocation::LocalSource(src) => src.clone(),
|
||||
SpanLocation::None => "<unknown location>".into(),
|
||||
}
|
||||
} else {
|
||||
"<No associated span>".into()
|
||||
};
|
||||
|
||||
let bytes_range = span.as_ref().map(|sp| evaluate_bytes(sp, &src));
|
||||
|
||||
if let Some(b) = &bytes_range {
|
||||
// If we go past the length, then we've somehow got the wrong SpanLocation.
|
||||
if matches!(
|
||||
span.as_ref().map(|s| &s.span_location),
|
||||
Some(SpanLocation::FilePath(..)) | Some(SpanLocation::LocalSource(..))
|
||||
) && b.end > src.len()
|
||||
{
|
||||
panic!(
|
||||
"Span source improperly calculated. Got range {} > {}. Original error: {}: {}",
|
||||
b.end,
|
||||
src.len(),
|
||||
report.title,
|
||||
report.primary_label
|
||||
);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "pretty-print")]
|
||||
{
|
||||
use annotate_snippets::{renderer::DecorStyle, Level, Renderer, Snippet};
|
||||
let report = if let Some(sp) = span {
|
||||
use annotate_snippets::{Annotation, AnnotationKind};
|
||||
|
||||
let annotations = report.context_locations.iter().map(|l| {
|
||||
let bytes = evaluate_bytes(&l.location, &src);
|
||||
AnnotationKind::Context.span(bytes).label(&l.label)
|
||||
});
|
||||
|
||||
&[Level::ERROR.primary_title(&report.title).element(
|
||||
Snippet::<Annotation>::source(&src)
|
||||
.path(match sp.span_location {
|
||||
SpanLocation::FilePath(f) => Some(f),
|
||||
_ => None,
|
||||
})
|
||||
.annotation(
|
||||
AnnotationKind::Primary
|
||||
.span(bytes_range.unwrap())
|
||||
.label(report.primary_label),
|
||||
)
|
||||
.annotations(annotations),
|
||||
)]
|
||||
} else {
|
||||
&[Level::ERROR
|
||||
.primary_title(&report.title)
|
||||
.element(Level::ERROR.message(report.primary_label))]
|
||||
};
|
||||
let renderer = Renderer::styled().decor_style(DecorStyle::Unicode);
|
||||
writeln!(out, "{}", renderer.render(report)).expect("Could not write report.");
|
||||
}
|
||||
#[cfg(not(feature = "pretty-print"))]
|
||||
{
|
||||
let (location, excerpt_pre, excerpt, excerpt_post) = if let Some(sp) = span {
|
||||
let range = bytes_range.unwrap();
|
||||
let start = sp.start.line;
|
||||
// Columns are 0-indexed, but most editors use 1-indexing:
|
||||
let col = sp.start.col + 1;
|
||||
let span_location = match &sp.span_location {
|
||||
SpanLocation::FilePath(f) => f.clone(),
|
||||
SpanLocation::LocalSource(..) => "<Inline source>".into(),
|
||||
SpanLocation::None => "<Unknown location>".into(),
|
||||
};
|
||||
let range_pre = range.start.saturating_sub(5);
|
||||
let range_post = std::cmp::min(range.end.saturating_add(5), src.len());
|
||||
match sp.span_location {
|
||||
SpanLocation::None => (span_location, "", "<Excerpt not available>", ""),
|
||||
_ => (
|
||||
format!("{span_location}:{start}:{col}"),
|
||||
&src[range_pre..range.start],
|
||||
&src[range.start..range.end],
|
||||
&src[range.end..range_post],
|
||||
),
|
||||
}
|
||||
} else {
|
||||
(
|
||||
"<No associated span>".into(),
|
||||
"",
|
||||
"<Excerpt not available>",
|
||||
"",
|
||||
)
|
||||
};
|
||||
write!(out, "Diplomat error: ").expect("Could not write to report.");
|
||||
writeln!(out, "{}", report.title).expect("Could not write to report.");
|
||||
writeln!(out, "In {location}:").expect("Could not write to report.");
|
||||
|
||||
let excerpt_pre_trimmed = excerpt_pre.trim_start();
|
||||
|
||||
if !excerpt_pre.is_empty() {
|
||||
write!(out, "...{}", excerpt_pre_trimmed).expect("Could not write to report.");
|
||||
}
|
||||
|
||||
write!(out, "{excerpt}").expect("Could not write to report.");
|
||||
|
||||
if !excerpt_post.is_empty() {
|
||||
writeln!(out, "{}...", excerpt_post.trim_end()).expect("Could not write to report.");
|
||||
}
|
||||
|
||||
// Add visible separation between the label and the excerpt.
|
||||
if !excerpt.is_empty() {
|
||||
// This works well for most one-line excerpts.
|
||||
// The pretty-printer tends to handle whitespacing better, however.
|
||||
writeln!(
|
||||
out,
|
||||
"{}{}",
|
||||
" ".repeat(3 + excerpt_pre_trimmed.len()),
|
||||
"^".repeat(excerpt.len())
|
||||
)
|
||||
.expect("Could not write to report.");
|
||||
}
|
||||
|
||||
write!(out, "{}", report.primary_label).expect("Could not write to report.");
|
||||
}
|
||||
out.flush().expect("Could not write to output.");
|
||||
// Rust-analyzer will not show error messages unless we panic,
|
||||
// This just tells rust-analyzer users to check stderr:
|
||||
panic!("Diplomat error: {} (check stderr for more)", report.title);
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(feature = "pretty-print")))]
|
||||
mod tests {
|
||||
use std::fmt::Write;
|
||||
|
||||
use crate::ast::ModuleIncludeInfo;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct StderrWrapper {
|
||||
buf: String,
|
||||
}
|
||||
impl std::io::Write for StderrWrapper {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let st = str::from_utf8(buf).expect("Could not read utf8");
|
||||
self.buf.write_str(st).expect("Could not write str");
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
insta::assert_snapshot!(self.buf);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn reader_fn() -> Box<dyn std::io::Write> {
|
||||
Box::new(StderrWrapper { buf: String::new() })
|
||||
}
|
||||
|
||||
fn parse_file_hook_errors(file_loc: &str, suffix: &str) {
|
||||
let folder_pth_name = format!("src/ast/snapshots/span_testing");
|
||||
let folder_pth = std::path::Path::new(&folder_pth_name);
|
||||
let file_path = folder_pth.join(file_loc);
|
||||
|
||||
let mut settings = insta::Settings::clone_current();
|
||||
settings.set_snapshot_suffix(format!("{file_loc}_{suffix}"));
|
||||
settings.set_snapshot_path("snapshots/span_testing");
|
||||
let _drop = settings.bind_to_scope();
|
||||
|
||||
let st = std::fs::read_to_string(&file_path).expect("Could not read file.");
|
||||
let p = syn::parse_str::<syn::ItemMod>(&st).expect("Could not parse syn mod");
|
||||
crate::ast::Module::from_syn(
|
||||
&p,
|
||||
true,
|
||||
Some(ModuleIncludeInfo {
|
||||
base_path: &folder_pth,
|
||||
cache: None,
|
||||
}),
|
||||
&crate::ast::SpanLocation::FilePath(format!("{}/{file_loc}", folder_pth_name)),
|
||||
);
|
||||
}
|
||||
|
||||
const FILES_TO_TEST: &[&str] = &[
|
||||
"duplicate_attrs.rs",
|
||||
"enum_field_variant.rs",
|
||||
"attr_on_non_pub.rs",
|
||||
"nonstd_result.rs",
|
||||
"self_in_free_func.rs",
|
||||
"lifetime_on_trait.rs",
|
||||
"generic_types.rs",
|
||||
"where_pred.rs",
|
||||
"lifetime_redefine.rs",
|
||||
"undefined_macro.rs",
|
||||
"macro_parse_error.rs",
|
||||
"macro_expansion_error.rs",
|
||||
"self_type.rs",
|
||||
"param_invalid_type.rs",
|
||||
"undefined_type.rs",
|
||||
"non_opaque_tuple.rs",
|
||||
"generic_type.rs",
|
||||
"free_func_generics.rs",
|
||||
"trait_bound_generics.rs",
|
||||
"mut_string.rs",
|
||||
"slice_of_slice.rs",
|
||||
"owned_slice.rs",
|
||||
"box_type_arg.rs",
|
||||
"missing_angle_brackets.rs",
|
||||
"option_type_args.rs",
|
||||
"option_without_angle_brackets.rs",
|
||||
"invalid_slice.rs",
|
||||
"tuples.rs",
|
||||
"multi_traits.rs",
|
||||
"result_type_args.rs",
|
||||
"result_angle_brackets.rs",
|
||||
"lifetime_callback_param.rs",
|
||||
"unsupported_fn_type.rs",
|
||||
"ns_lifetime.rs",
|
||||
"unsupported_bound.rs",
|
||||
"unsupported_type.rs",
|
||||
"slice_no_type.rs",
|
||||
"malformed_attr.rs",
|
||||
"malformed_cfg.rs",
|
||||
"malformed_demo.rs",
|
||||
"malformed_include.rs",
|
||||
"malformed_rust_link.rs",
|
||||
"error_in_included.rs",
|
||||
];
|
||||
|
||||
fn test_file_list(suffix: &'static str) {
|
||||
{
|
||||
let mut inner = super::WRITER.try_write().unwrap();
|
||||
*inner = &reader_fn;
|
||||
}
|
||||
let mut results = vec![];
|
||||
for f in FILES_TO_TEST {
|
||||
let t = std::thread::spawn(|| {
|
||||
parse_file_hook_errors(f, suffix);
|
||||
});
|
||||
results.push((f, t.join()));
|
||||
}
|
||||
for (f, res) in results {
|
||||
match res {
|
||||
Ok(_) => {}
|
||||
Err(p) => {
|
||||
if let Some(st) = p.downcast_ref::<String>() {
|
||||
if !st.contains("Diplomat error") {
|
||||
panic!("{f}: {st}");
|
||||
}
|
||||
} else {
|
||||
panic!("{f}: Could not convert error to string.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "pretty-print"))]
|
||||
#[test]
|
||||
fn test_errors_ugly() {
|
||||
test_file_list("ugly");
|
||||
}
|
||||
}
|
||||
+86
-25
@@ -13,9 +13,15 @@ use syn::{
|
||||
token, Error, Ident, ImplItem, ImplItemMacro, Item, ItemMacro, Token,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
use crate::ast::{
|
||||
idents::IntoWithSpan,
|
||||
logging::{create_report, create_simple_report, AstReport},
|
||||
SpanLocation,
|
||||
};
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Macros {
|
||||
defs: BTreeMap<Ident, MacroDef>,
|
||||
pub(crate) defs: BTreeMap<Ident, MacroDef>,
|
||||
}
|
||||
|
||||
impl Macros {
|
||||
@@ -26,6 +32,7 @@ impl Macros {
|
||||
}
|
||||
|
||||
pub fn add_item_macro(&mut self, input: &ItemMacro) {
|
||||
// This should never be called without a macro_rules! def:
|
||||
assert!(
|
||||
input.ident.is_some(),
|
||||
"Expected macro_rules! def. Got {input:?}"
|
||||
@@ -37,7 +44,12 @@ impl Macros {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn evaluate_item_macro(&self, input: &ItemMacro) -> Vec<Item> {
|
||||
pub fn evaluate_item_macro(
|
||||
&self,
|
||||
input: &ItemMacro,
|
||||
module_location: &SpanLocation,
|
||||
) -> Vec<Item> {
|
||||
// This should never be called without an ident attached:
|
||||
assert!(input.ident.is_none(), "Expected macro usage. Got {input:?}");
|
||||
let m = input.mac.parse_body::<TokenStream>();
|
||||
if let Ok(mac) = m {
|
||||
@@ -45,9 +57,9 @@ impl Macros {
|
||||
let ident = input.mac.path.segments.last().unwrap().ident.clone();
|
||||
|
||||
if let Some(def) = self.defs.get(&ident) {
|
||||
def.evaluate(mac)
|
||||
def.evaluate(mac, module_location)
|
||||
} else {
|
||||
panic!("Could not find definition for {ident}. Have you tried creating a #[diplomat::macro_rules] macro_rules! {ident} definition?");
|
||||
create_simple_report((&ident).spanned_into(module_location), format!("Macro {ident}! undefined."), format!("Suggestion: Create #[diplomat::macro_rules] macro_rules! {ident} definition before this item."));
|
||||
}
|
||||
} else {
|
||||
// We handle errors automatically in `diplomat/macro`
|
||||
@@ -55,16 +67,20 @@ impl Macros {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn evaluate_impl_item_macro(&self, input: &ImplItemMacro) -> Vec<ImplItem> {
|
||||
pub fn evaluate_impl_item_macro(
|
||||
&self,
|
||||
input: &ImplItemMacro,
|
||||
module_location: &SpanLocation,
|
||||
) -> Vec<ImplItem> {
|
||||
let m: syn::Result<TokenStream> = input.mac.parse_body();
|
||||
// FIXME: Extremely hacky. In the future for importing macros, we'll want to do something else.
|
||||
let path_ident = input.mac.path.segments.last().unwrap().ident.clone();
|
||||
|
||||
if let Ok(matched) = m {
|
||||
if let Some(def) = self.defs.get(&path_ident) {
|
||||
def.evaluate(matched)
|
||||
def.evaluate(matched, module_location)
|
||||
} else {
|
||||
panic!("Could not find definition for {path_ident}. Have you tried creating a #[diplomat::macro_rules] macro_rules! {path_ident} definition?");
|
||||
create_simple_report((&path_ident).spanned_into(module_location), format!("Macro {path_ident}! undefined."), format!("Suggestion: Create #[diplomat::macro_rules] macro_rules! {path_ident} definition before this item."));
|
||||
}
|
||||
} else {
|
||||
// We handle errors automatically in `diplomat/macro`
|
||||
@@ -379,7 +395,7 @@ impl MacroUse {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
/// A token representing part of a macro's arguments.
|
||||
/// Used for determining how to parse [`MacroUse`].
|
||||
/// First constructed with [`MacroMatcher::parse`] inside of [`MacroDef::parse`]. Then, we compare with [`MacroUse::parse_macro_matcher`].
|
||||
@@ -446,7 +462,7 @@ impl Parse for MacroMatch {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
/// Represents any given macro definition's arguments, and information on how to parse them for use.
|
||||
/// A MacroMatcher is a delimited list of [`MacroMatch`]es. When you call the macro `example!(...)`, the macro matcher is the parentheses delimited tokens: `(...)`.
|
||||
/// Used to compare a [`MacroDef`] against a [`MacroUse`] when parsing arguments.
|
||||
@@ -485,7 +501,7 @@ impl Parse for MacroMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
/// Struct for defining a macro (i.e., `macro_rules! example`)
|
||||
pub struct MacroDef {
|
||||
@@ -532,7 +548,11 @@ impl MacroDef {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_group(matched: &MacroUse, inner: Cursor) -> TokenStream {
|
||||
fn parse_group(
|
||||
matched: &MacroUse,
|
||||
inner: Cursor,
|
||||
group_location: &SpanLocation,
|
||||
) -> TokenStream {
|
||||
let mut stream = TokenStream::new();
|
||||
|
||||
let mut c = inner;
|
||||
@@ -544,16 +564,28 @@ impl MacroDef {
|
||||
matched.args[&i].to_tokens(&mut stream);
|
||||
c = next;
|
||||
} else {
|
||||
panic!("Expected ident next to $, got {tt:?}");
|
||||
create_report(AstReport::new(
|
||||
"Expected ident when expanding macro argument.".to_string(),
|
||||
Some(tt.span().spanned_into(group_location)),
|
||||
"Need ident after $ to replace with variable".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
} else {
|
||||
panic!("Expected token tree.");
|
||||
create_report(AstReport::new(
|
||||
"Expected token tree.".to_string(),
|
||||
Some(next.span().spanned_into(group_location)),
|
||||
"".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
}
|
||||
TokenTree::Group(g) => {
|
||||
let (inner, _, next) = c.group(g.delimiter()).unwrap();
|
||||
let group =
|
||||
proc_macro2::Group::new(g.delimiter(), Self::parse_group(matched, inner));
|
||||
let group = proc_macro2::Group::new(
|
||||
g.delimiter(),
|
||||
Self::parse_group(matched, inner, group_location),
|
||||
);
|
||||
// Once we detect a group, we push it to the array for syn to evaluate.
|
||||
stream.append(group);
|
||||
c = next;
|
||||
@@ -568,7 +600,7 @@ impl MacroDef {
|
||||
stream
|
||||
}
|
||||
|
||||
fn evaluate_buf(&self, matched: MacroUse) -> TokenStream {
|
||||
fn evaluate_buf(&self, matched: MacroUse, buf_location: &SpanLocation) -> TokenStream {
|
||||
let mut stream = TokenStream::new();
|
||||
|
||||
let buf = TokenBuffer::new2(self.body.clone());
|
||||
@@ -582,17 +614,29 @@ impl MacroDef {
|
||||
matched.args[&i].to_tokens(&mut stream);
|
||||
c = next;
|
||||
} else {
|
||||
panic!("Expected ident next to $, got {tt:?}");
|
||||
create_report(AstReport::new(
|
||||
"Expected ident when expanding macro argument.".to_string(),
|
||||
Some(tt.span().spanned_into(buf_location)),
|
||||
"Need ident after $ to replace with variable".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
} else {
|
||||
panic!("Expected token tree.");
|
||||
create_report(AstReport::new(
|
||||
"Expected token tree.".to_string(),
|
||||
Some(next.span().spanned_into(buf_location)),
|
||||
"".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
}
|
||||
TokenTree::Group(g) => {
|
||||
let (inner, _, next) = c.group(g.delimiter()).unwrap();
|
||||
// We need to read inside of any groups to find and replace `$` idents.
|
||||
let group =
|
||||
proc_macro2::Group::new(g.delimiter(), Self::parse_group(&matched, inner));
|
||||
let group = proc_macro2::Group::new(
|
||||
g.delimiter(),
|
||||
Self::parse_group(&matched, inner, buf_location),
|
||||
);
|
||||
stream.append(group);
|
||||
c = next;
|
||||
}
|
||||
@@ -606,16 +650,33 @@ impl MacroDef {
|
||||
stream
|
||||
}
|
||||
|
||||
fn evaluate<T: Parse + Debug>(&self, matched: TokenStream) -> Vec<T> {
|
||||
let macro_use = MacroUse::parse(self, matched).unwrap_or_else(|e| panic!("{}", e));
|
||||
let stream = self.evaluate_buf(macro_use);
|
||||
fn evaluate<T: Parse + Debug>(
|
||||
&self,
|
||||
matched: TokenStream,
|
||||
use_location: &SpanLocation,
|
||||
) -> Vec<T> {
|
||||
let macro_use = MacroUse::parse(self, matched).unwrap_or_else(|e| {
|
||||
create_report(AstReport::new(
|
||||
e.to_string(),
|
||||
Some(e.span().spanned_into(use_location)),
|
||||
"Error parsing macro here".into(),
|
||||
vec![],
|
||||
));
|
||||
});
|
||||
let stream = self.evaluate_buf(macro_use, use_location);
|
||||
|
||||
// Now we have a stream to read through. We read through the whole thing and assume each thing we read is a top level item.
|
||||
let maybe_list = syn::parse_str::<ItemList<T>>(&stream.to_string());
|
||||
if let Ok(i) = maybe_list {
|
||||
i.items
|
||||
} else {
|
||||
panic!("Macro expansion error: {:?}", maybe_list.unwrap_err());
|
||||
let e = maybe_list.unwrap_err();
|
||||
create_report(AstReport::new(
|
||||
e.to_string(),
|
||||
Some(e.span().spanned_into(use_location)),
|
||||
"Error expanding macro here".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
+75
-28
@@ -1,5 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::ControlFlow;
|
||||
use syn::spanned::Spanned;
|
||||
|
||||
use crate::ast::idents::IntoWithSpan;
|
||||
use crate::ast::logging::{create_report, AstReport};
|
||||
use crate::ast::SpanLocation;
|
||||
|
||||
use super::docs::Docs;
|
||||
use super::{Attrs, Ident, Lifetime, LifetimeEnv, Mutability, PathType, TypeName};
|
||||
@@ -48,9 +53,10 @@ impl Method {
|
||||
self_path_type: PathType,
|
||||
impl_generics: Option<&syn::Generics>,
|
||||
impl_attrs: &Attrs,
|
||||
module_location: &SpanLocation,
|
||||
) -> Method {
|
||||
let mut attrs = impl_attrs.clone();
|
||||
attrs.add_attrs(&m.attrs);
|
||||
attrs.add_attrs(&m.attrs, module_location);
|
||||
|
||||
let self_ident = self_path_type.path.elements.last().unwrap();
|
||||
let method_ident = &m.sig.ident;
|
||||
@@ -66,14 +72,16 @@ impl Method {
|
||||
.iter()
|
||||
.filter_map(|a| match a {
|
||||
syn::FnArg::Receiver(_) => None,
|
||||
syn::FnArg::Typed(ref t) => Some(Param::from_syn(t, self_path_type.clone())),
|
||||
syn::FnArg::Typed(ref t) => {
|
||||
Some(Param::from_syn(t, self_path_type.clone(), module_location))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let self_param = m
|
||||
.sig
|
||||
.receiver()
|
||||
.map(|rec| SelfParam::from_syn(rec, self_path_type.clone()));
|
||||
.map(|rec| SelfParam::from_syn(rec, self_path_type.clone(), module_location));
|
||||
|
||||
let return_ty = match &m.sig.output {
|
||||
syn::ReturnType::Type(_, return_typ) => {
|
||||
@@ -82,6 +90,7 @@ impl Method {
|
||||
Some(TypeName::from_syn(
|
||||
return_typ.as_ref(),
|
||||
Some(self_path_type.clone()),
|
||||
module_location,
|
||||
))
|
||||
}
|
||||
syn::ReturnType::Default => None,
|
||||
@@ -93,12 +102,13 @@ impl Method {
|
||||
self_param.as_ref(),
|
||||
&all_params[..],
|
||||
return_ty.as_ref(),
|
||||
module_location,
|
||||
);
|
||||
|
||||
Method {
|
||||
name: Ident::from(method_ident),
|
||||
docs: Docs::from_attrs(&m.attrs),
|
||||
abi_name: Ident::from(&extern_ident),
|
||||
name: (method_ident).spanned_into(module_location),
|
||||
docs: Docs::from_attrs(&m.attrs, module_location),
|
||||
abi_name: (&extern_ident).spanned_into(module_location),
|
||||
self_param,
|
||||
self_type: Some(self_path_type),
|
||||
params: all_params,
|
||||
@@ -238,6 +248,24 @@ pub struct SelfParam {
|
||||
pub attrs: Attrs,
|
||||
}
|
||||
|
||||
fn receiver_to_reference(
|
||||
rec: &syn::Receiver,
|
||||
module_location: &SpanLocation,
|
||||
) -> Option<(Lifetime, Mutability)> {
|
||||
match &rec.kind {
|
||||
syn::ReceiverKind::Reference(_, lt, mt) => {
|
||||
Some((lt.spanned_into(module_location), Mutability::from_syn(mt)))
|
||||
}
|
||||
syn::ReceiverKind::Value => None,
|
||||
_ => create_report(AstReport::new(
|
||||
"Unsupported receiver".into(),
|
||||
Some(rec.span().spanned_into(module_location)),
|
||||
"Diplomat only supports `&[mut] self` references or `[mut] self` values.".into(),
|
||||
vec![],
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
impl SelfParam {
|
||||
pub fn to_typename(&self) -> TypeName {
|
||||
let typ = TypeName::Named(self.path_type.clone());
|
||||
@@ -247,14 +275,15 @@ impl SelfParam {
|
||||
typ
|
||||
}
|
||||
|
||||
pub fn from_syn(rec: &syn::Receiver, path_type: PathType) -> Self {
|
||||
pub fn from_syn(
|
||||
rec: &syn::Receiver,
|
||||
path_type: PathType,
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
SelfParam {
|
||||
reference: rec
|
||||
.reference
|
||||
.as_ref()
|
||||
.map(|(_, lt)| (lt.into(), Mutability::from_syn(&rec.mutability))),
|
||||
reference: receiver_to_reference(rec, module_location),
|
||||
path_type,
|
||||
attrs: Attrs::from_attrs(&rec.attrs),
|
||||
attrs: Attrs::from_attrs(&rec.attrs, module_location),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,12 +309,13 @@ impl TraitSelfParam {
|
||||
typ
|
||||
}
|
||||
|
||||
pub fn from_syn(rec: &syn::Receiver, path_trait: PathType) -> Self {
|
||||
pub fn from_syn(
|
||||
rec: &syn::Receiver,
|
||||
path_trait: PathType,
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
TraitSelfParam {
|
||||
reference: rec
|
||||
.reference
|
||||
.as_ref()
|
||||
.map(|(_, lt)| (lt.into(), Mutability::from_syn(&rec.mutability))),
|
||||
reference: receiver_to_reference(rec, module_location),
|
||||
path_trait,
|
||||
}
|
||||
}
|
||||
@@ -314,17 +344,28 @@ impl Param {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_syn(t: &syn::PatType, self_path_type: PathType) -> Self {
|
||||
pub fn from_syn(
|
||||
t: &syn::PatType,
|
||||
self_path_type: PathType,
|
||||
module_location: &SpanLocation,
|
||||
) -> Self {
|
||||
let ident = match t.pat.as_ref() {
|
||||
syn::Pat::Ident(ident) => ident,
|
||||
_ => panic!("Unexpected param type"),
|
||||
_ => {
|
||||
create_report(AstReport::new(
|
||||
"Unexpected param type".into(),
|
||||
Some(t.pat.span().spanned_into(module_location)),
|
||||
"Expected ident".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let attrs = Attrs::from_attrs(&t.attrs);
|
||||
let attrs = Attrs::from_attrs(&t.attrs, module_location);
|
||||
|
||||
Param {
|
||||
name: (&ident.ident).into(),
|
||||
ty: TypeName::from_syn(&t.ty, Some(self_path_type)),
|
||||
name: (&ident.ident).spanned_into(module_location),
|
||||
ty: TypeName::from_syn(&t.ty, Some(self_path_type), module_location),
|
||||
attrs,
|
||||
}
|
||||
}
|
||||
@@ -419,7 +460,8 @@ mod tests {
|
||||
},
|
||||
PathType::new(Path::empty().sub_path(Ident::from("MyStructContainingMethod"))),
|
||||
None,
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
|
||||
insta::assert_yaml_snapshot!(Method::from_syn(
|
||||
@@ -435,7 +477,8 @@ mod tests {
|
||||
},
|
||||
PathType::new(Path::empty().sub_path(Ident::from("MyStructContainingMethod"))),
|
||||
None,
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
}
|
||||
|
||||
@@ -452,7 +495,8 @@ mod tests {
|
||||
},
|
||||
PathType::new(Path::empty().sub_path(Ident::from("MyStructContainingMethod"))),
|
||||
None,
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
}
|
||||
|
||||
@@ -466,7 +510,8 @@ mod tests {
|
||||
},
|
||||
PathType::new(Path::empty().sub_path(Ident::from("MyStructContainingMethod"))),
|
||||
None,
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
|
||||
insta::assert_yaml_snapshot!(Method::from_syn(
|
||||
@@ -478,7 +523,8 @@ mod tests {
|
||||
},
|
||||
PathType::new(Path::empty().sub_path(Ident::from("MyStructContainingMethod"))),
|
||||
None,
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
));
|
||||
}
|
||||
|
||||
@@ -488,7 +534,8 @@ mod tests {
|
||||
&syn::parse_quote! { $($tokens)* },
|
||||
PathType::new(Path::empty().sub_path(Ident::from("MyStructContainingMethod"))),
|
||||
None,
|
||||
&Attrs::default()
|
||||
&Attrs::default(),
|
||||
&crate::ast::SpanLocation::None
|
||||
);
|
||||
|
||||
let borrowed_params = method.borrowed_params();
|
||||
+4
-2
@@ -10,7 +10,7 @@ mod methods;
|
||||
pub use methods::{BorrowedParams, Method, Param, SelfParam, TraitSelfParam};
|
||||
|
||||
mod modules;
|
||||
pub use modules::{File, Module};
|
||||
pub use modules::{File, Module, ModuleIncludeInfo};
|
||||
|
||||
mod structs;
|
||||
pub use structs::Struct;
|
||||
@@ -40,10 +40,12 @@ mod paths;
|
||||
pub use paths::Path;
|
||||
|
||||
mod idents;
|
||||
pub use idents::Ident;
|
||||
pub use idents::{Ident, SpanLocation};
|
||||
|
||||
mod docs;
|
||||
pub use docs::{DocType, Docs, RustLink, RustLinkDisplay};
|
||||
|
||||
mod macros;
|
||||
pub use macros::{MacroDef, MacroUse, Macros};
|
||||
|
||||
mod logging;
|
||||
@@ -0,0 +1,870 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use quote::ToTokens;
|
||||
use serde::Serialize;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{ImplItem, Item, ItemMod, UseTree, Visibility};
|
||||
|
||||
use super::{
|
||||
AttrInheritContext, Attrs, CustomType, Enum, Ident, Macros, Method, ModSymbol, Mutability,
|
||||
OpaqueType, Path, PathType, RustLink, Struct, Trait,
|
||||
};
|
||||
use crate::ast::idents::{FromWithSpan, IntoWithSpan};
|
||||
use crate::ast::logging::{create_report, create_simple_report, AstReport};
|
||||
use crate::ast::{Function, SpanLocation};
|
||||
use crate::environment::*;
|
||||
|
||||
/// Custom Diplomat attribute that can be placed on a struct definition.
|
||||
#[derive(Debug)]
|
||||
enum DiplomatStructAttribute {
|
||||
/// The `#[diplomat::out]` attribute, used for non-opaque structs that
|
||||
/// contain an owned opaque in the form of a `Box`.
|
||||
Out,
|
||||
/// An attribute that can correspond to a type (struct or enum).
|
||||
TypeAttr(DiplomatTypeAttribute),
|
||||
}
|
||||
|
||||
/// Custom Diplomat attribute that can be placed on an enum or struct definition.
|
||||
#[derive(Debug)]
|
||||
enum DiplomatTypeAttribute {
|
||||
/// The `#[diplomat::opaque]` attribute, used for marking a type as opaque.
|
||||
/// Note that opaque structs can be borrowed in return types, but cannot
|
||||
/// be passed into a function behind a mutable reference.
|
||||
Opaque,
|
||||
/// The `#[diplomat::opaque_mut]` attribute, used for marking a type as
|
||||
/// opaque and mutable.
|
||||
/// Note that mutable opaque types can never be borrowed in return types
|
||||
/// (even immutably!), but can be passed into a function behind a mutable
|
||||
/// reference.
|
||||
OpaqueMut,
|
||||
}
|
||||
|
||||
impl DiplomatStructAttribute {
|
||||
/// Parses a [`DiplomatStructAttribute`] from an array of [`syn::Attribute`]s.
|
||||
/// If more than one kind is found, an error is returned containing all the
|
||||
/// ones encountered, since all the current attributes are disjoint.
|
||||
fn parse(attrs: &[syn::Attribute]) -> Result<Option<Self>, Vec<Self>> {
|
||||
let mut buf = String::with_capacity(32);
|
||||
let mut res = Ok(None);
|
||||
for attr in attrs {
|
||||
buf.clear();
|
||||
write!(&mut buf, "{}", attr.path().to_token_stream()).unwrap();
|
||||
let parsed = match buf.as_str() {
|
||||
"diplomat :: out" => Some(Self::Out),
|
||||
"diplomat :: opaque" => Some(Self::TypeAttr(DiplomatTypeAttribute::Opaque)),
|
||||
"diplomat :: opaque_mut" => Some(Self::TypeAttr(DiplomatTypeAttribute::OpaqueMut)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(parsed) = parsed {
|
||||
match res {
|
||||
Ok(None) => res = Ok(Some(parsed)),
|
||||
Ok(Some(first)) => res = Err(vec![first, parsed]),
|
||||
Err(ref mut errors) => errors.push(parsed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
impl DiplomatTypeAttribute {
|
||||
/// Parses a [`DiplomatTypeAttribute`] from an array of [`syn::Attribute`]s.
|
||||
/// If more than one kind is found, an error is returned containing all the
|
||||
/// ones encountered, since all the current attributes are disjoint.
|
||||
fn parse(attrs: &[syn::Attribute]) -> Result<Option<Self>, Vec<Self>> {
|
||||
let mut buf = String::with_capacity(32);
|
||||
let mut res = Ok(None);
|
||||
for attr in attrs {
|
||||
buf.clear();
|
||||
write!(&mut buf, "{}", attr.path().to_token_stream()).unwrap();
|
||||
let parsed = match buf.as_str() {
|
||||
"diplomat :: opaque" => Some(Self::Opaque),
|
||||
"diplomat :: opaque_mut" => Some(Self::OpaqueMut),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(parsed) = parsed {
|
||||
match res {
|
||||
Ok(None) => res = Ok(Some(parsed)),
|
||||
Ok(Some(first)) => res = Err(vec![first, parsed]),
|
||||
Err(ref mut errors) => errors.push(parsed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
/// File name -> List of macro defs
|
||||
type ModuleCacheMap = HashMap<String, BTreeMap<syn::Ident, super::MacroDef>>;
|
||||
|
||||
/// Information for how to parse #[diplomat::include].
|
||||
/// For proc_macro:
|
||||
/// Only needs to know the `base_path` from which to include files from.
|
||||
/// Cache should be set to `None` (proc_macro does not like caching).
|
||||
///
|
||||
/// For HIR:
|
||||
/// Holds a reference to the `base_path` from which to include files from.
|
||||
/// Also holds a reference to a persistent cache (behind a `RefCell`) to store macro information.
|
||||
/// The cache should be created by the top level HIR function.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ModuleIncludeInfo<'a> {
|
||||
/// Where to parse files from.
|
||||
pub(crate) base_path: &'a std::path::Path,
|
||||
/// Cache across Module::from_syn calls.
|
||||
pub(crate) cache: Option<&'a RefCell<ModuleCacheMap>>,
|
||||
}
|
||||
|
||||
impl<'a> ModuleIncludeInfo<'a> {
|
||||
pub fn new(base_path: &'a std::path::Path, cache: Option<&'a RefCell<ModuleCacheMap>>) -> Self {
|
||||
Self { base_path, cache }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct Module {
|
||||
pub name: Ident,
|
||||
pub imports: Vec<(Path, Ident)>,
|
||||
pub declared_types: BTreeMap<Ident, CustomType>,
|
||||
pub declared_traits: BTreeMap<Ident, Trait>,
|
||||
pub declared_functions: BTreeMap<Ident, Function>,
|
||||
pub sub_modules: Vec<Module>,
|
||||
pub attrs: Attrs,
|
||||
}
|
||||
|
||||
/// Contains all items needed to build an AST representation of a given [`Module`],
|
||||
/// as we traverse through [`syn::ItemMod`]. We build this up in [`ModuleBuilder::add`]
|
||||
struct ModuleBuilder<'a> {
|
||||
custom_types_by_name: BTreeMap<Ident, CustomType>,
|
||||
custom_traits_by_name: BTreeMap<Ident, Trait>,
|
||||
/// Types that are private (so if we encounter their impl blocks, they can be safely ignored)
|
||||
private_types_by_name: BTreeSet<Ident>,
|
||||
functions_by_name: BTreeMap<Ident, Function>,
|
||||
sub_modules: Vec<Module>,
|
||||
imports: Vec<(Path, Ident)>,
|
||||
/// As we traverse through the module, are we inside of #[diplomat::bridge]?
|
||||
/// If so, then `analyze_types` is set to true, and types, functions, and traits are all updated according to information parsed.
|
||||
///
|
||||
/// Otherwise, we traverse through modules until we find a module marked by #[diplomat::bridge]
|
||||
analyze_types: bool,
|
||||
/// Are we to only analyze public structs or enums?
|
||||
skip_private_items: bool,
|
||||
type_parent_attrs: Attrs,
|
||||
impl_parent_attrs: Attrs,
|
||||
mod_macros: Macros,
|
||||
include_info: Option<ModuleIncludeInfo<'a>>,
|
||||
/// Where the module is stored as a file.
|
||||
module_location: &'a SpanLocation,
|
||||
}
|
||||
|
||||
impl<'a> ModuleBuilder<'a> {
|
||||
fn add(&mut self, a: &Item) {
|
||||
match a {
|
||||
Item::Use(u) if self.analyze_types => {
|
||||
extract_imports(
|
||||
&Path::empty(),
|
||||
&u.tree,
|
||||
&mut self.imports,
|
||||
self.module_location,
|
||||
);
|
||||
}
|
||||
Item::Struct(strct) if self.analyze_types => {
|
||||
if self.skip_private_items && !matches!(strct.vis, syn::Visibility::Public(..)) {
|
||||
self.private_types_by_name
|
||||
.insert((&strct.ident).spanned_into(self.module_location));
|
||||
return;
|
||||
}
|
||||
let custom_type = match DiplomatStructAttribute::parse(&strct.attrs[..]) {
|
||||
Ok(None) => CustomType::Struct(Struct::new(
|
||||
strct,
|
||||
false,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
)),
|
||||
Ok(Some(DiplomatStructAttribute::Out)) => CustomType::Struct(Struct::new(
|
||||
strct,
|
||||
true,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
)),
|
||||
Ok(Some(DiplomatStructAttribute::TypeAttr(DiplomatTypeAttribute::Opaque))) => {
|
||||
CustomType::Opaque(OpaqueType::new_struct(
|
||||
strct,
|
||||
Mutability::Immutable,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
))
|
||||
}
|
||||
Ok(Some(DiplomatStructAttribute::TypeAttr(
|
||||
DiplomatTypeAttribute::OpaqueMut,
|
||||
))) => CustomType::Opaque(OpaqueType::new_struct(
|
||||
strct,
|
||||
Mutability::Mutable,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
)),
|
||||
Err(errors) => {
|
||||
create_simple_report((&strct.ident).spanned_into(self.module_location), "Multiple conflicting Diplomat struct attributes, there can be at most one.".into(), format!("{errors:?}"));
|
||||
}
|
||||
};
|
||||
|
||||
self.custom_types_by_name.insert(
|
||||
(&strct.ident).spanned_into(self.module_location),
|
||||
custom_type,
|
||||
);
|
||||
}
|
||||
|
||||
Item::Enum(enm) if self.analyze_types => {
|
||||
let ident = (&enm.ident).spanned_into(self.module_location);
|
||||
|
||||
if self.skip_private_items && !matches!(enm.vis, syn::Visibility::Public(..)) {
|
||||
self.private_types_by_name.insert(ident);
|
||||
return;
|
||||
}
|
||||
|
||||
let custom_enum = match DiplomatTypeAttribute::parse(&enm.attrs[..]) {
|
||||
Ok(None) => CustomType::Enum(Enum::new(
|
||||
enm,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
)),
|
||||
Ok(Some(DiplomatTypeAttribute::Opaque)) => {
|
||||
CustomType::Opaque(OpaqueType::new_enum(
|
||||
enm,
|
||||
Mutability::Immutable,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
))
|
||||
}
|
||||
Ok(Some(DiplomatTypeAttribute::OpaqueMut)) => {
|
||||
CustomType::Opaque(OpaqueType::new_enum(
|
||||
enm,
|
||||
Mutability::Mutable,
|
||||
&self.type_parent_attrs,
|
||||
self.module_location,
|
||||
))
|
||||
}
|
||||
Err(errors) => {
|
||||
create_simple_report((&enm.ident).spanned_into(self.module_location), "Multiple conflicting Diplomat enum attributes, there can be at most one.".into(), format!("{errors:?}"));
|
||||
}
|
||||
};
|
||||
self.custom_types_by_name.insert(ident, custom_enum);
|
||||
}
|
||||
|
||||
Item::Impl(imp) if self.analyze_types && imp.trait_.is_none() => {
|
||||
let self_path = match imp.self_ty.as_ref() {
|
||||
syn::Type::Path(s) => PathType::spanned_from(s, self.module_location),
|
||||
_ => {
|
||||
create_report(AstReport::new(
|
||||
"Self type not found".into(),
|
||||
Some(imp.self_ty.span().spanned_into(self.module_location)),
|
||||
"Expected Path type".into(),
|
||||
vec![],
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut impl_attrs = self.impl_parent_attrs.clone();
|
||||
impl_attrs.add_attrs(&imp.attrs, self.module_location);
|
||||
let method_parent_attrs =
|
||||
impl_attrs.attrs_for_inheritance(AttrInheritContext::MethodFromImpl);
|
||||
let self_ident = self_path.path.elements.last().unwrap();
|
||||
|
||||
// Do a prepass to evaluate macros:
|
||||
let mut impl_item_vec = Vec::new();
|
||||
for i in &imp.items {
|
||||
match i {
|
||||
ImplItem::Fn(f) => {
|
||||
impl_item_vec.push(ImplItem::Fn(f.clone()));
|
||||
}
|
||||
ImplItem::Macro(mac) => {
|
||||
let mut items = self
|
||||
.mod_macros
|
||||
.evaluate_impl_item_macro(mac, self.module_location);
|
||||
impl_item_vec.append(&mut items);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Then only add functions to the block:
|
||||
let mut new_methods = impl_item_vec
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
ImplItem::Fn(m) => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|m| {
|
||||
let is_public = matches!(m.vis, Visibility::Public(_));
|
||||
let has_diplomat_attrs = m
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|a| a.path().segments.iter().next().unwrap().ident == "diplomat");
|
||||
if !is_public && has_diplomat_attrs {
|
||||
create_simple_report(
|
||||
(&m.sig.ident).spanned_into(self.module_location),
|
||||
"Found non-public method with diplomat attrs".into(),
|
||||
"Remove #[diplomat::*] attributes.".into(),
|
||||
);
|
||||
}
|
||||
is_public
|
||||
})
|
||||
.map(|m| {
|
||||
Method::from_syn(
|
||||
m,
|
||||
self_path.clone(),
|
||||
Some(&imp.generics),
|
||||
&method_parent_attrs,
|
||||
self.module_location,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
if self.skip_private_items && self.private_types_by_name.contains(self_ident) {
|
||||
return;
|
||||
}
|
||||
|
||||
match self
|
||||
.custom_types_by_name
|
||||
.get_mut(self_ident)
|
||||
.unwrap_or_else(|| {
|
||||
create_simple_report(
|
||||
self_ident.clone(),
|
||||
"Diplomat requires impls to be in the same module as their type".into(),
|
||||
format!("{self_ident} should be defined in the same module."),
|
||||
);
|
||||
}) {
|
||||
CustomType::Struct(strct) => {
|
||||
strct.methods.append(&mut new_methods);
|
||||
}
|
||||
CustomType::Opaque(strct) => {
|
||||
strct.methods.append(&mut new_methods);
|
||||
}
|
||||
CustomType::Enum(enm) => {
|
||||
enm.methods.append(&mut new_methods);
|
||||
}
|
||||
}
|
||||
}
|
||||
Item::Mod(item_mod) => {
|
||||
self.sub_modules.push(Module::from_syn(
|
||||
item_mod,
|
||||
false,
|
||||
self.include_info.clone(),
|
||||
self.module_location,
|
||||
));
|
||||
}
|
||||
Item::Trait(trt) if self.analyze_types => {
|
||||
let ident = (&trt.ident).spanned_into(self.module_location);
|
||||
let trt = Trait::new(trt, &self.type_parent_attrs, self.module_location);
|
||||
self.custom_traits_by_name.insert(ident, trt);
|
||||
}
|
||||
Item::Macro(mac) if self.analyze_types => {
|
||||
if let Some(i) = &mac.ident {
|
||||
let macro_rules_attr = mac.attrs.iter().find(|a| {
|
||||
a.path() == &syn::parse_str::<syn::Path>("diplomat::macro_rules").unwrap()
|
||||
});
|
||||
|
||||
if macro_rules_attr.is_some() {
|
||||
self.mod_macros.add_item_macro(mac);
|
||||
} else {
|
||||
println!(
|
||||
r#"WARNING: Found macro_rules definition "macro_rules! {i}" with no #[diplomat::macro_rules] attribute. This will not be evaluated in Diplomat bindings."#
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let items = self
|
||||
.mod_macros
|
||||
.evaluate_item_macro(mac, self.module_location);
|
||||
for i in items {
|
||||
self.add(&i);
|
||||
}
|
||||
}
|
||||
}
|
||||
Item::Fn(f) if self.analyze_types => {
|
||||
let is_public = matches!(f.vis, Visibility::Public(_));
|
||||
let has_diplomat_attrs = f
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|a| a.path().segments.iter().next().unwrap().ident == "diplomat");
|
||||
if !is_public && has_diplomat_attrs {
|
||||
create_simple_report(
|
||||
(&f.sig.ident).spanned_into(self.module_location),
|
||||
"Found non-public method with diplomat attrs".into(),
|
||||
"Remove #[diplomat::*] attributes.".into(),
|
||||
);
|
||||
}
|
||||
if is_public {
|
||||
let parent_attrs = self
|
||||
.impl_parent_attrs
|
||||
.attrs_for_inheritance(AttrInheritContext::MethodFromImpl);
|
||||
let out = Function::from_syn(f, &parent_attrs, self.module_location);
|
||||
self.functions_by_name.insert(out.name.clone(), out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Module {
|
||||
pub fn all_rust_links(&self) -> HashSet<&RustLink> {
|
||||
let mut rust_links = self
|
||||
.declared_types
|
||||
.values()
|
||||
.flat_map(|t| t.all_rust_links())
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
self.sub_modules.iter().for_each(|m| {
|
||||
rust_links.extend(m.all_rust_links().iter());
|
||||
});
|
||||
rust_links
|
||||
}
|
||||
|
||||
pub fn insert_all_types(&self, in_path: Path, out: &mut Env) {
|
||||
let mut mod_symbols = ModuleEnv::new(self.attrs.clone());
|
||||
|
||||
self.imports.iter().for_each(|(path, name)| {
|
||||
mod_symbols.insert(name.clone(), ModSymbol::Alias(path.clone()));
|
||||
});
|
||||
|
||||
self.declared_types.iter().for_each(|(k, v)| {
|
||||
if mod_symbols
|
||||
.insert(k.clone(), ModSymbol::CustomType(v.clone()))
|
||||
.is_some()
|
||||
{
|
||||
create_simple_report(
|
||||
k.clone(),
|
||||
"Two types were declared with the same name (this is currently unsupported)"
|
||||
.into(),
|
||||
"Duplicate type".into(),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.declared_traits.iter().for_each(|(k, v)| {
|
||||
if mod_symbols
|
||||
.insert(k.clone(), ModSymbol::Trait(v.clone()))
|
||||
.is_some()
|
||||
{
|
||||
create_simple_report(
|
||||
k.clone(),
|
||||
"Two traits were declared with the same name (this is currently unsupported)"
|
||||
.into(),
|
||||
"Duplicate trait".into(),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
self.declared_functions.iter().for_each(|(k, f)| {
|
||||
if mod_symbols.insert(k.clone(), ModSymbol::Function(f.clone())).is_some() {
|
||||
create_simple_report(k.clone(), "Two functions were declared with the same name (this is currently unsupported)".into(), "Duplicate function".into());
|
||||
}
|
||||
});
|
||||
|
||||
let path_to_self = in_path.sub_path(self.name.clone());
|
||||
self.sub_modules.iter().for_each(|m| {
|
||||
m.insert_all_types(path_to_self.clone(), out);
|
||||
mod_symbols.insert(m.name.clone(), ModSymbol::SubModule(m.name.clone()));
|
||||
});
|
||||
|
||||
out.insert(path_to_self, mod_symbols);
|
||||
}
|
||||
|
||||
/// Convert an [`ItemMod`] to a [`Module`].
|
||||
///
|
||||
/// `force_analyze` is for forcibly parsing the module in the case where we know the `#[diplomat::bridge]` attribute should be present,
|
||||
/// but proc_macro (or some other analyzer) has removed the attribute in advance.
|
||||
pub fn from_syn<'a>(
|
||||
input: &ItemMod,
|
||||
force_analyze: bool,
|
||||
include_info: Option<ModuleIncludeInfo<'a>>,
|
||||
module_location: &SpanLocation,
|
||||
) -> Module {
|
||||
let mod_attrs: Attrs = (&*input.attrs).spanned_into(module_location);
|
||||
|
||||
let mod_macros = if let Some(inc) = &include_info {
|
||||
let defs = parse_macro_file(input, force_analyze, inc.clone(), module_location)
|
||||
.unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Could not parse macro definitions in {:?}: {e}",
|
||||
inc.base_path
|
||||
)
|
||||
});
|
||||
Macros { defs }
|
||||
} else {
|
||||
Macros::new()
|
||||
};
|
||||
|
||||
let mut mst = ModuleBuilder {
|
||||
custom_types_by_name: BTreeMap::new(),
|
||||
custom_traits_by_name: BTreeMap::new(),
|
||||
private_types_by_name: BTreeSet::new(),
|
||||
functions_by_name: BTreeMap::new(),
|
||||
sub_modules: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
analyze_types: force_analyze
|
||||
|| input
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|a| a.path().to_token_stream().to_string() == "diplomat :: bridge"),
|
||||
skip_private_items: input.attrs.iter().any(|a| {
|
||||
a.path().to_token_stream().to_string() == "diplomat :: skip_private_items"
|
||||
}),
|
||||
impl_parent_attrs: mod_attrs
|
||||
.attrs_for_inheritance(AttrInheritContext::MethodOrImplFromModule),
|
||||
type_parent_attrs: mod_attrs.attrs_for_inheritance(AttrInheritContext::Type),
|
||||
mod_macros,
|
||||
include_info,
|
||||
module_location,
|
||||
};
|
||||
|
||||
input
|
||||
.content
|
||||
.as_ref()
|
||||
.map(|t| &t.1[..])
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.for_each(|a| {
|
||||
mst.add(a);
|
||||
});
|
||||
|
||||
Module {
|
||||
name: (&input.ident).spanned_into(module_location),
|
||||
imports: mst.imports,
|
||||
declared_types: mst.custom_types_by_name,
|
||||
declared_traits: mst.custom_traits_by_name,
|
||||
declared_functions: mst.functions_by_name,
|
||||
sub_modules: mst.sub_modules,
|
||||
attrs: mod_attrs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_imports(
|
||||
base_path: &Path,
|
||||
use_tree: &UseTree,
|
||||
out: &mut Vec<(Path, Ident)>,
|
||||
module_location: &SpanLocation,
|
||||
) {
|
||||
match use_tree {
|
||||
UseTree::Name(name) => out.push((
|
||||
base_path.sub_path((&name.ident).spanned_into(module_location)),
|
||||
(&name.ident).spanned_into(module_location),
|
||||
)),
|
||||
UseTree::Path(path) => extract_imports(
|
||||
&base_path.sub_path((&path.ident).spanned_into(module_location)),
|
||||
&path.tree,
|
||||
out,
|
||||
module_location,
|
||||
),
|
||||
UseTree::Glob(_) => todo!("Glob imports are not yet supported"),
|
||||
UseTree::Group(group) => {
|
||||
group
|
||||
.items
|
||||
.iter()
|
||||
.for_each(|i| extract_imports(base_path, i, out, module_location));
|
||||
}
|
||||
UseTree::Rename(rename) => out.push((
|
||||
base_path.sub_path((&rename.ident).spanned_into(module_location)),
|
||||
(&rename.rename).spanned_into(module_location),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct File {
|
||||
pub modules: BTreeMap<String, Module>,
|
||||
}
|
||||
|
||||
impl File {
|
||||
/// Fuses all declared types into a single environment `HashMap`.
|
||||
pub fn all_types(&self) -> Env {
|
||||
let mut out = Env::default();
|
||||
let mut top_symbols = ModuleEnv::new(Default::default());
|
||||
|
||||
self.modules.values().for_each(|m| {
|
||||
m.insert_all_types(Path::empty(), &mut out);
|
||||
top_symbols.insert(m.name.clone(), ModSymbol::SubModule(m.name.clone()));
|
||||
});
|
||||
|
||||
out.insert(Path::empty(), top_symbols);
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn all_rust_links(&self) -> HashSet<&RustLink> {
|
||||
self.modules
|
||||
.values()
|
||||
.flat_map(|m| m.all_rust_links().into_iter())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn from_syn(
|
||||
file: &syn::File,
|
||||
include_info: Option<ModuleIncludeInfo>,
|
||||
entry_location: &SpanLocation,
|
||||
) -> File {
|
||||
let mut out = BTreeMap::new();
|
||||
file.items.iter().for_each(|i| {
|
||||
if let Item::Mod(item_mod) = i {
|
||||
let module_location = match entry_location {
|
||||
SpanLocation::FilePath(p) => {
|
||||
// Entry location points to a folder, so we can just join to add a subfolder:
|
||||
let pth = std::path::Path::new(p);
|
||||
let new_pth = pth.join(format!("{}.rs", item_mod.ident));
|
||||
if !new_pth.exists() {
|
||||
// We could just be in an item submodule, so we stay in the entry module path:
|
||||
&SpanLocation::FilePath(p.clone())
|
||||
} else {
|
||||
&SpanLocation::FilePath(new_pth.to_string_lossy().into())
|
||||
}
|
||||
}
|
||||
SpanLocation::None => &SpanLocation::None,
|
||||
SpanLocation::LocalSource(..) => unreachable!("Span Location for ast::File should never be LocalSource, we expect a filepath.")
|
||||
};
|
||||
out.insert(
|
||||
item_mod.ident.to_string(),
|
||||
Module::from_syn(item_mod, false, include_info.clone(), module_location),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
File { modules: out }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_macro_file(
|
||||
m: &ItemMod,
|
||||
force_analyze: bool,
|
||||
include_info: ModuleIncludeInfo,
|
||||
module_location: &SpanLocation,
|
||||
) -> Result<BTreeMap<syn::Ident, super::MacroDef>, std::io::Error> {
|
||||
let contains_bridge = m
|
||||
.attrs
|
||||
.iter()
|
||||
.any(|a| a.path().to_token_stream().to_string() == "diplomat :: bridge")
|
||||
|| force_analyze;
|
||||
|
||||
if !contains_bridge {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
|
||||
let attrs: Attrs = (*m.attrs).spanned_into(module_location);
|
||||
|
||||
let mut previously_hit = BTreeMap::<syn::Ident, String>::new();
|
||||
|
||||
let mut ret = BTreeMap::new();
|
||||
for i in &attrs.includes {
|
||||
let mut defs = if let Some(inner) = include_info
|
||||
.cache
|
||||
.as_ref()
|
||||
.and_then(|c| c.borrow().get(&i.path).cloned())
|
||||
{
|
||||
inner
|
||||
} else {
|
||||
let inc_loc = include_info.base_path.join(i.path.clone());
|
||||
let module_location = &SpanLocation::FilePath(inc_loc.to_string_lossy().into());
|
||||
let file_contents = std::fs::read_to_string(inc_loc)?;
|
||||
let syn_file = syn::parse_file(&file_contents).unwrap_or_else(|e| {
|
||||
create_report(AstReport::new(
|
||||
"Error reading file".into(),
|
||||
Some(e.span().spanned_into(module_location)),
|
||||
e.to_string(),
|
||||
vec![],
|
||||
))
|
||||
});
|
||||
// Parse the module (we're just interested in the macros, but this is a quick shortcut to do that)
|
||||
let mut mst = ModuleBuilder {
|
||||
custom_types_by_name: BTreeMap::new(),
|
||||
custom_traits_by_name: BTreeMap::new(),
|
||||
functions_by_name: BTreeMap::new(),
|
||||
sub_modules: vec![],
|
||||
imports: vec![],
|
||||
analyze_types: true,
|
||||
impl_parent_attrs: attrs
|
||||
.attrs_for_inheritance(AttrInheritContext::MethodOrImplFromModule),
|
||||
type_parent_attrs: attrs.attrs_for_inheritance(AttrInheritContext::Type),
|
||||
mod_macros: Macros::new(),
|
||||
include_info: None,
|
||||
private_types_by_name: BTreeSet::new(),
|
||||
skip_private_items: false,
|
||||
module_location,
|
||||
};
|
||||
for i in syn_file.items {
|
||||
mst.add(&i);
|
||||
}
|
||||
|
||||
if let Some(c) = &include_info.cache {
|
||||
c.borrow_mut()
|
||||
.insert(i.path.clone(), mst.mod_macros.defs.clone());
|
||||
}
|
||||
mst.mod_macros.defs
|
||||
};
|
||||
|
||||
// ModuleBuilder catches redefinitions within a given module, but we want to make sure
|
||||
// there are no collisions between multiple #[diplomat::include()] files:
|
||||
for id in defs.keys() {
|
||||
if let Some(pth) = previously_hit.get(id) {
|
||||
create_report(AstReport::new(
|
||||
format!("Duplicate macro definition of {id} found"),
|
||||
Some(id.span().spanned_into(module_location)),
|
||||
format!("Previously defined in {pth}"),
|
||||
vec![],
|
||||
));
|
||||
} else {
|
||||
previously_hit.insert(id.clone(), i.path.clone());
|
||||
}
|
||||
}
|
||||
ret.append(&mut defs);
|
||||
}
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
impl From<&syn::File> for File {
|
||||
/// Get all custom types across all modules defined in a given file.
|
||||
fn from(file: &syn::File) -> File {
|
||||
File::from_syn(file, None, &SpanLocation::None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use insta::{self, Settings};
|
||||
|
||||
use syn;
|
||||
|
||||
use crate::ast::{File, Module, SpanLocation};
|
||||
|
||||
#[test]
|
||||
fn simple_mod() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(Module::from_syn(
|
||||
&syn::parse_quote! {
|
||||
mod ffi {
|
||||
struct NonOpaqueStruct {
|
||||
a: i32,
|
||||
b: Box<NonOpaqueStruct>
|
||||
}
|
||||
|
||||
impl NonOpaqueStruct {
|
||||
pub fn new(x: i32) -> NonOpaqueStruct {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
pub fn set_a(&mut self, new_a: i32) {
|
||||
self.a = new_a;
|
||||
}
|
||||
}
|
||||
|
||||
#[diplomat::opaque]
|
||||
struct OpaqueStruct {
|
||||
a: SomeExternalType
|
||||
}
|
||||
|
||||
impl OpaqueStruct {
|
||||
pub fn new() -> Box<OpaqueStruct> {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
pub fn get_string(&self) -> String {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn test_function() {}
|
||||
pub fn other_test_function(x : i32) -> NonOpaqueStruct {
|
||||
unimplemented!();
|
||||
}
|
||||
}
|
||||
},
|
||||
true,
|
||||
None,
|
||||
&SpanLocation::None,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn method_visibility() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(Module::from_syn(
|
||||
&syn::parse_quote! {
|
||||
#[diplomat::bridge]
|
||||
mod ffi {
|
||||
struct Foo {}
|
||||
|
||||
impl Foo {
|
||||
pub fn pub_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
pub(crate) fn pub_crate_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
pub(super) fn pub_super_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
fn priv_fn() {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
true,
|
||||
None,
|
||||
&SpanLocation::None,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_in_non_diplomat_not_analyzed() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(File::from(&syn::parse_quote! {
|
||||
#[diplomat::bridge]
|
||||
mod ffi {
|
||||
struct Foo {}
|
||||
}
|
||||
|
||||
mod other {
|
||||
use something::*;
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_visibility() {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_sort_maps(true);
|
||||
|
||||
settings.bind(|| {
|
||||
insta::assert_yaml_snapshot!(File::from(&syn::parse_quote! {
|
||||
#[diplomat::bridge]
|
||||
#[diplomat::skip_private_items]
|
||||
mod ffi {
|
||||
struct Foo {}
|
||||
|
||||
#[diplomat::opaque]
|
||||
pub struct Opaque{
|
||||
foo: Foo,
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
Loaded 100 of 662 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user