├── .github └── workflows │ └── rust_nightly.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── java-spaghetti-gen ├── Cargo.toml └── src │ ├── config │ ├── mod.rs │ ├── runtime.rs │ └── toml.rs │ ├── emit_rust │ ├── class_proxy.rs │ ├── classes.rs │ ├── fields.rs │ ├── known_docs_url.rs │ ├── methods.rs │ ├── mod.rs │ ├── modules.rs │ ├── preamble-contents.rs │ └── preamble.rs │ ├── identifiers │ ├── field_mangling_style.rs │ ├── method_mangling_style.rs │ ├── mod.rs │ └── rust_identifier.rs │ ├── main.rs │ ├── parser_util │ ├── class.rs │ ├── field.rs │ ├── id.rs │ ├── method.rs │ └── mod.rs │ ├── run │ ├── mod.rs │ └── run.rs │ └── util │ ├── difference.rs │ ├── generated_file.rs │ ├── mod.rs │ └── progress.rs ├── java-spaghetti ├── Cargo.toml └── src │ ├── array.rs │ ├── as_arg.rs │ ├── as_jvalue.rs │ ├── env.rs │ ├── id_cache.rs │ ├── jni_type.rs │ ├── lib.rs │ ├── refs │ ├── arg.rs │ ├── global.rs │ ├── local.rs │ ├── ref_.rs │ └── return_.rs │ ├── string_chars.rs │ └── vm.rs └── rustfmt.toml /.github/workflows/rust_nightly.yml: -------------------------------------------------------------------------------- 1 | name: Rust - Nightly 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | merge_group: 9 | 10 | env: 11 | CARGO_TERM_COLOR: always 12 | 13 | jobs: 14 | build_and_test: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - run: rustup update nightly && rustup default nightly 19 | - run: rustup component add rustfmt 20 | - name: Check fmt 21 | run: cargo fmt -- --check 22 | - name: Test 23 | run: cargo test 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /scripts/retest.cmd 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = [ 4 | "java-spaghetti", 5 | "java-spaghetti-gen", 6 | ] 7 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (C) the java-spaghetti authors 4 | Copyright (C) 2019 MaulingMonkey 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ☕️🍝 `java-spaghetti` 2 | 3 | Generate type-safe bindings for calling Java APIs from Rust, so you can fearlessly make your humongous Java spaghetti code aglomeration trascend language barriers and occupy an even larger fraction of the universe's space-time. 4 | 5 | ## Differences vs `jni-bindgen` 6 | 7 | This project originally started out as a fork of [`jni-bindgen`](https://github.com/MaulingMonkey/jni-bindgen). 8 | 9 | The main difference is the intended usage: `jni-bindgen` aims to generate crates with bindings for a whole Java API (such as `jni-android-sys`) which 10 | you then use from your crate. `java-spaghetti` is instead designed to generate "mini-bindings" tailored to your project, that you can embed within your crate. This has a few advantages: 11 | 12 | - You can generate a single bindings file for e.g. part of the Android API and your project's classes at the same time, which is better because you end up with only one copy of shared classes like `java.lang.String`. 13 | - Java APIs can get big. `jni-android-sys` uses one Cargo feature per class to avoid compile time bloat, which is [no longer allowed on crates.io](https://blog.rust-lang.org/2023/10/26/broken-badges-and-23k-keywords.html). 14 | 15 | The full list of differences are: 16 | 17 | - Simplified and more consistent API. 18 | - Support for casting and upcasting. 19 | - Added FFI-safe `Return` for returning Java objects from JNI calls. 20 | - Arguments to method calls use a custom `AsArg` trait to make them more ergonomic (doesn't need stuff like `&**foo` or `Some(foo)`). 21 | - You can filter which classes are generated in the TOML config. 22 | - Generated code uses relative paths (`super::...`) instead of absolute paths (`crate::...`), so it works if you place it in a submodule not at the crate root. 23 | - Generated code is a single `.rs` file, there's no support for spltting it in one file per class. You can still run the output through [form](https://github.com/djmcgill/form), if you want. 24 | - Generated code uses cached method IDs and field IDs stored in `OnceLock` to speed up invocations by several times. Used classes are also stored as JNI global references in order to keep the validity of cached IDs. This may not ensure memory safety when class redefinition features (e.g. `java.lang.instrument` which is unavailable on Android) of the JVM are being used. 25 | - Generated code doesn't use macros. 26 | - No support for generating Cargo features per class. 27 | - Modernized rust, updated dependencies. 28 | 29 | ## License 30 | 31 | Licensed under either of 32 | 33 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 34 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 35 | 36 | at your option. 37 | 38 | ## Contribution 39 | 40 | Unless you explicitly state otherwise, any contribution intentionally submitted 41 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 42 | dual licensed as above, without any additional terms or conditions. 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /java-spaghetti-gen/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "java-spaghetti-gen" 3 | version = "0.2.0" 4 | edition = "2024" 5 | description = "Code generator for binding to JVM APIs from Rust" 6 | repository = "https://github.com/Dirbaio/java-spaghetti" 7 | keywords = ["jvm", "jni", "bindgen", "android"] 8 | categories = ["development-tools::ffi"] 9 | license = "MIT OR Apache-2.0" 10 | 11 | [dependencies] 12 | cafebabe = "0.8.0" 13 | clap = { version = "4", features = ["derive"] } 14 | bitflags = "2.8.0" 15 | serde = "1.0.197" 16 | serde_derive = "1.0.197" 17 | toml = "0.8.10" 18 | zip = "2.2.2" 19 | quote = "1.0.40" 20 | proc-macro2 = "1.0.95" 21 | anyhow = "1.0.98" 22 | 23 | [dev-dependencies] 24 | jni-sys = "0.4.0" 25 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/config/mod.rs: -------------------------------------------------------------------------------- 1 | //! Configuration formats for invoking java-spaghetti 2 | 3 | pub mod runtime; 4 | pub mod toml; 5 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/config/runtime.rs: -------------------------------------------------------------------------------- 1 | //! Runtime configuration formats. By design, this is mostly opaque - create these from tomls instead. 2 | 3 | use std::collections::{HashMap, HashSet}; 4 | use std::ffi::OsString; 5 | use std::path::{Path, PathBuf}; 6 | 7 | use crate::config::toml; 8 | 9 | pub(crate) struct DocPattern { 10 | pub(crate) class_url_pattern: String, 11 | pub(crate) method_url_pattern: Option, 12 | pub(crate) constructor_url_pattern: Option, 13 | pub(crate) field_url_pattern: Option, 14 | pub(crate) jni_prefix: String, 15 | pub(crate) class_namespace_separator: String, 16 | pub(crate) class_inner_class_seperator: String, 17 | pub(crate) argument_namespace_separator: String, 18 | pub(crate) argument_inner_class_seperator: String, 19 | pub(crate) argument_seperator: String, 20 | } 21 | 22 | impl From for DocPattern { 23 | fn from(file: toml::DocumentationPattern) -> Self { 24 | Self { 25 | class_url_pattern: file.class_url_pattern, 26 | method_url_pattern: file.method_url_pattern, 27 | constructor_url_pattern: file.constructor_url_pattern, 28 | field_url_pattern: file.field_url_pattern, 29 | jni_prefix: file.jni_prefix, 30 | class_namespace_separator: file.class_namespace_separator, 31 | class_inner_class_seperator: file.class_inner_class_seperator, 32 | argument_namespace_separator: file.argument_namespace_separator, 33 | argument_inner_class_seperator: file.argument_inner_class_seperator, 34 | argument_seperator: file.argument_seperator, 35 | } 36 | } 37 | } 38 | 39 | /// Runtime configuration. Create from a toml::File. 40 | pub struct Config { 41 | pub(crate) codegen: toml::CodeGen, 42 | pub(crate) doc_patterns: Vec, 43 | pub(crate) input_files: Vec, 44 | pub(crate) output_path: PathBuf, 45 | pub(crate) logging_verbose: bool, 46 | 47 | pub(crate) include_classes: HashSet, 48 | 49 | pub(crate) include_proxies: HashSet, 50 | 51 | pub(crate) ignore_classes: HashSet, 52 | pub(crate) ignore_class_fields: HashSet, 53 | pub(crate) ignore_class_methods: HashSet, 54 | pub(crate) ignore_class_method_sigs: HashSet, 55 | 56 | pub(crate) rename_classes: HashMap, 57 | pub(crate) rename_class_fields: HashMap, 58 | pub(crate) rename_class_methods: HashMap, 59 | pub(crate) rename_class_method_sigs: HashMap, 60 | } 61 | 62 | impl From for Config { 63 | fn from(fwc: toml::FileWithContext) -> Self { 64 | let file = fwc.file; 65 | let dir = fwc.directory; 66 | 67 | let documentation = file.documentation; 68 | let logging = file.logging; 69 | 70 | let mut include_classes: HashSet = HashSet::new(); 71 | for include in file.includes { 72 | include_classes.insert(include); 73 | } 74 | if include_classes.is_empty() { 75 | include_classes.insert("*".to_string()); 76 | } 77 | 78 | let mut include_proxies: HashSet = HashSet::new(); 79 | for include in file.include_proxies { 80 | include_proxies.insert(include); 81 | } 82 | 83 | let mut ignore_classes = HashSet::new(); 84 | let mut ignore_class_fields = HashSet::new(); 85 | let mut ignore_class_methods = HashSet::new(); 86 | let mut ignore_class_method_sigs = HashSet::new(); 87 | for ignore in file.ignores { 88 | // TODO: Warn if sig && !method 89 | // TODO: Warn if field && method 90 | if let Some(method) = ignore.method.as_ref() { 91 | if let Some(sig) = ignore.signature.as_ref() { 92 | ignore_class_method_sigs.insert(format!("{}\x1f{}\x1f{}", ignore.class, method, sig)); 93 | } else { 94 | ignore_class_methods.insert(format!("{}\x1f{}", ignore.class, method)); 95 | } 96 | } else if let Some(field) = ignore.field.as_ref() { 97 | ignore_class_fields.insert(format!("{}\x1f{}", ignore.class, field)); 98 | } else { 99 | ignore_classes.insert(ignore.class.clone()); 100 | } 101 | } 102 | 103 | let mut rename_classes = HashMap::new(); 104 | let mut rename_class_fields = HashMap::new(); 105 | let mut rename_class_methods = HashMap::new(); 106 | let mut rename_class_method_sigs = HashMap::new(); 107 | for rename in file.renames { 108 | // TODO: Warn if sig && !method 109 | // TODO: Warn if field && method 110 | if let Some(method) = rename.method.as_ref() { 111 | if let Some(sig) = rename.signature.as_ref() { 112 | rename_class_method_sigs 113 | .insert(format!("{}\x1f{}\x1f{}", rename.class, method, sig), rename.to.clone()); 114 | } else { 115 | rename_class_methods.insert(format!("{}\x1f{}", rename.class, method), rename.to.clone()); 116 | } 117 | } else if let Some(field) = rename.field.as_ref() { 118 | rename_class_fields.insert(format!("{}\x1f{}", rename.class, field), rename.to.clone()); 119 | } else { 120 | rename_classes.insert(rename.class.clone(), rename.to.clone()); 121 | } 122 | } 123 | 124 | let output_path = resolve_file(file.output.path, &dir); 125 | 126 | Self { 127 | codegen: file.codegen.clone(), 128 | doc_patterns: documentation.patterns.into_iter().map(|pat| pat.into()).collect(), 129 | input_files: file 130 | .input 131 | .files 132 | .into_iter() 133 | .map(|file| resolve_file(file, &dir)) 134 | .collect(), 135 | output_path, 136 | logging_verbose: logging.verbose, 137 | include_classes, 138 | include_proxies, 139 | ignore_classes, 140 | ignore_class_fields, 141 | ignore_class_methods, 142 | ignore_class_method_sigs, 143 | rename_classes, 144 | rename_class_fields, 145 | rename_class_methods, 146 | rename_class_method_sigs, 147 | } 148 | } 149 | } 150 | 151 | fn resolve_file(path: PathBuf, dir: &Path) -> PathBuf { 152 | let path: PathBuf = match path.into_os_string().into_string() { 153 | Ok(string) => OsString::from(expand_vars(string)), 154 | Err(os_string) => os_string, 155 | } 156 | .into(); 157 | 158 | if path.is_relative() { dir.join(path) } else { path } 159 | } 160 | 161 | fn expand_vars(string: String) -> String { 162 | let mut buf = String::new(); 163 | 164 | let mut expanding = false; 165 | for segment in string.split('%') { 166 | if expanding { 167 | if let Ok(replacement) = std::env::var(segment) { 168 | buf.push_str(&replacement[..]); 169 | } else { 170 | println!("cargo:rerun-if-env-changed={}", segment); 171 | buf.push('%'); 172 | buf.push_str(segment); 173 | buf.push('%'); 174 | } 175 | } else { 176 | buf.push_str(segment); 177 | } 178 | expanding = !expanding; 179 | } 180 | assert!( 181 | expanding, 182 | "Uneven number of %s in path: {:?}, would mis-expand into: {:?}", 183 | &string, &buf 184 | ); 185 | buf 186 | } 187 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/class_proxy.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Write; 2 | 3 | use cafebabe::descriptors::{FieldDescriptor, FieldType, ReturnDescriptor}; 4 | use proc_macro2::TokenStream; 5 | use quote::{format_ident, quote}; 6 | 7 | use super::classes::Class; 8 | use super::cstring; 9 | use super::fields::RustTypeFlavor; 10 | use super::methods::Method; 11 | use crate::emit_rust::Context; 12 | use crate::emit_rust::fields::emit_rust_type; 13 | use crate::parser_util::{Id, emit_field_descriptor}; 14 | 15 | impl Class { 16 | pub(crate) fn write_proxy(&self, context: &Context, methods: &[Method]) -> anyhow::Result { 17 | let mut emit_reject_reasons = Vec::new(); 18 | 19 | let mut out = TokenStream::new(); 20 | let mut contents = TokenStream::new(); 21 | 22 | let visibility = if self.java.is_public() { quote!(pub) } else { quote!() }; 23 | let rust_name = format_ident!("{}", &self.rust.struct_name); 24 | 25 | let object = context 26 | .java_to_rust_path(Id("java/lang/Object"), &self.rust.mod_) 27 | .unwrap(); 28 | let throwable = context.throwable_rust_path(&self.rust.mod_); 29 | let rust_proxy_name = format_ident!("{}Proxy", &self.rust.struct_name); 30 | 31 | let mut trait_methods = TokenStream::new(); 32 | 33 | let java_proxy_path = format!( 34 | "{}/{}", 35 | context.config.codegen.proxy_path_prefix, 36 | self.java.path().as_str().replace("$", "_") 37 | ); 38 | 39 | for method in methods { 40 | let Some(rust_name) = method.rust_name() else { continue }; 41 | if method.java.is_static() 42 | || method.java.is_static_init() 43 | || method.java.is_constructor() 44 | || method.java.is_final() 45 | || method.java.is_private() 46 | { 47 | continue; 48 | } 49 | 50 | let mut native_params = Vec::new(); 51 | native_params.push(FieldDescriptor { 52 | dimensions: 0, 53 | field_type: FieldType::Long, 54 | }); 55 | native_params.extend(method.java.descriptor.parameters.iter().cloned()); 56 | let native_name = mangle_native_method( 57 | &java_proxy_path, 58 | &format!("native_{}", method.java.name()), 59 | &native_params, 60 | ); 61 | let native_name = format_ident!("{native_name}"); 62 | let rust_name = format_ident!("{rust_name}"); 63 | 64 | let ret = match &method.java.descriptor.return_type { 65 | ReturnDescriptor::Void => quote!(()), 66 | ReturnDescriptor::Return(desc) => emit_rust_type( 67 | desc, 68 | context, 69 | &self.rust.mod_, 70 | RustTypeFlavor::Return, 71 | &mut emit_reject_reasons, 72 | )?, 73 | }; 74 | 75 | let mut trait_args = TokenStream::new(); 76 | let mut native_args = TokenStream::new(); 77 | let mut native_convert_args = TokenStream::new(); 78 | 79 | for (arg_idx, arg) in method.java.descriptor.parameters.iter().enumerate() { 80 | let arg_name = format_ident!("arg{}", arg_idx); 81 | 82 | let trait_arg_type = emit_rust_type( 83 | arg, 84 | context, 85 | &self.rust.mod_, 86 | RustTypeFlavor::OptionRef, 87 | &mut emit_reject_reasons, 88 | )?; 89 | trait_args.extend(quote!(#arg_name: #trait_arg_type,)); 90 | 91 | let native_arg_type = emit_rust_type( 92 | arg, 93 | context, 94 | &self.rust.mod_, 95 | RustTypeFlavor::Arg, 96 | &mut emit_reject_reasons, 97 | )?; 98 | native_args.extend(quote!(#arg_name: #native_arg_type,)); 99 | if matches!(arg.field_type, FieldType::Object(_)) || arg.dimensions > 0 { 100 | native_convert_args.extend(quote!(#arg_name.into_ref(__jni_env),)); 101 | } else { 102 | native_convert_args.extend(quote!(#arg_name,)); 103 | } 104 | } 105 | 106 | trait_methods.extend(quote!( 107 | fn #rust_name<'env>( 108 | &self, 109 | env: ::java_spaghetti::Env<'env>, 110 | #trait_args 111 | ) -> #ret; 112 | )); 113 | 114 | out.extend(quote!( 115 | #[unsafe(no_mangle)] 116 | extern "system" fn #native_name<'env>( 117 | __jni_env: ::java_spaghetti::Env<'env>, 118 | _class: *mut (), // self class, ignore 119 | ptr: i64, 120 | #native_args 121 | ) -> #ret { 122 | let ptr: *const std::sync::Arc = ::std::ptr::with_exposed_provenance(ptr as usize); 123 | unsafe { 124 | (*ptr).#rust_name(__jni_env, #native_convert_args ) 125 | } 126 | } 127 | )); 128 | } 129 | 130 | let mut native_params = Vec::new(); 131 | native_params.push(FieldDescriptor { 132 | dimensions: 0, 133 | field_type: FieldType::Long, 134 | }); 135 | let native_name = mangle_native_method(&java_proxy_path, "native_finalize", &native_params); 136 | let native_name = format_ident!("{native_name}"); 137 | 138 | out.extend(quote!( 139 | #visibility trait #rust_proxy_name: ::std::marker::Send + ::std::marker::Sync + 'static { 140 | #trait_methods 141 | } 142 | 143 | #[unsafe(no_mangle)] 144 | extern "system" fn #native_name( 145 | __jni_env: ::java_spaghetti::Env<'_>, 146 | _class: *mut (), // self class, ignore 147 | ptr: i64, 148 | ) { 149 | let ptr: *mut std::sync::Arc = ::std::ptr::with_exposed_provenance_mut(ptr as usize); 150 | let _ = unsafe { Box::from_raw(ptr) }; 151 | } 152 | )); 153 | 154 | let java_proxy_path = cstring(&java_proxy_path); 155 | 156 | contents.extend(quote!( 157 | pub fn new_proxy<'env>( 158 | env: ::java_spaghetti::Env<'env>, 159 | proxy: ::std::sync::Arc, 160 | ) -> Result<::java_spaghetti::Local<'env, Self>, ::java_spaghetti::Local<'env, #throwable>> { 161 | static __CLASS: ::std::sync::OnceLock<::java_spaghetti::Global<#object>> = 162 | ::std::sync::OnceLock::new(); 163 | let __jni_class = __CLASS 164 | .get_or_init(|| unsafe { 165 | ::java_spaghetti::Local::from_raw(env, env.require_class(#java_proxy_path),) 166 | .as_global() 167 | }) 168 | .as_raw(); 169 | 170 | let b = ::std::boxed::Box::new(proxy); 171 | let ptr = ::std::boxed::Box::into_raw(b); 172 | 173 | static __METHOD: ::std::sync::OnceLock<::java_spaghetti::JMethodID> = ::std::sync::OnceLock::new(); 174 | unsafe { 175 | let __jni_args = [::java_spaghetti::sys::jvalue { 176 | j: ptr.expose_provenance() as i64, 177 | }]; 178 | let __jni_method = __METHOD 179 | .get_or_init(|| { 180 | ::java_spaghetti::JMethodID::from_raw(env.require_method( 181 | __jni_class, 182 | c"", 183 | c"(J)V", 184 | )) 185 | }) 186 | .as_raw(); 187 | env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr()) 188 | } 189 | } 190 | )); 191 | 192 | out.extend(quote!(impl #rust_name { #contents })); 193 | 194 | if !emit_reject_reasons.is_empty() { 195 | // TODO log 196 | return Ok(TokenStream::new()); 197 | } 198 | 199 | Ok(out) 200 | } 201 | } 202 | 203 | fn mangle_native_method(path: &str, name: &str, args: &[FieldDescriptor]) -> String { 204 | let mut res = String::new(); 205 | res.push_str("Java_"); 206 | res.push_str(&mangle_native(path)); 207 | res.push_str("_"); 208 | res.push_str(&mangle_native(name)); 209 | res.push_str("__"); 210 | for d in args { 211 | res.push_str(&mangle_native(&emit_field_descriptor(d))); 212 | } 213 | 214 | res 215 | } 216 | 217 | fn mangle_native(s: &str) -> String { 218 | let mut res = String::new(); 219 | for c in s.chars() { 220 | match c { 221 | '0'..='9' | 'a'..='z' | 'A'..='Z' => res.push(c), 222 | '/' => res.push_str("_"), 223 | '_' => res.push_str("_1"), 224 | ';' => res.push_str("_2"), 225 | '[' => res.push_str("_3"), 226 | _ => write!(&mut res, "_0{:04x}", c as u16).unwrap(), 227 | } 228 | } 229 | res 230 | } 231 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/classes.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{HashMap, HashSet}; 2 | use std::error::Error; 3 | use std::fmt::Write; 4 | 5 | use proc_macro2::TokenStream; 6 | use quote::{format_ident, quote}; 7 | 8 | use super::cstring; 9 | use super::fields::Field; 10 | use super::known_docs_url::KnownDocsUrl; 11 | use super::methods::Method; 12 | use crate::emit_rust::Context; 13 | use crate::identifiers::{FieldMangling, RustIdentifier}; 14 | use crate::parser_util::{Id, IdPart, JavaClass}; 15 | 16 | #[derive(Debug, Default)] 17 | pub(crate) struct StructPaths { 18 | pub mod_: String, 19 | pub struct_name: String, 20 | } 21 | 22 | impl StructPaths { 23 | pub(crate) fn new(context: &Context, class: Id) -> Result> { 24 | Ok(Self { 25 | mod_: Class::mod_for(context, class)?, 26 | struct_name: Class::name_for(context, class)?, 27 | }) 28 | } 29 | } 30 | 31 | #[derive(Debug)] 32 | pub(crate) struct Class { 33 | pub rust: StructPaths, 34 | pub java: JavaClass, 35 | } 36 | 37 | fn rust_id(id: &str) -> Result> { 38 | Ok(match RustIdentifier::from_str(id) { 39 | RustIdentifier::Identifier(id) => id, 40 | RustIdentifier::KeywordRawSafe(id) => id, 41 | RustIdentifier::KeywordUnderscorePostfix(id) => id, 42 | RustIdentifier::NonIdentifier(id) => io_data_err!( 43 | "Unable to add_class(): java identifier {:?} has no rust equivalent (yet?)", 44 | id 45 | )?, 46 | }) 47 | } 48 | 49 | impl Class { 50 | pub(crate) fn mod_for(_context: &Context, class: Id) -> Result> { 51 | let mut buf = String::new(); 52 | for component in class { 53 | match component { 54 | IdPart::Namespace(id) => { 55 | if !buf.is_empty() { 56 | buf.push_str("::"); 57 | } 58 | buf.push_str(&rust_id(id)?); 59 | } 60 | IdPart::ContainingClass(_) => {} 61 | IdPart::LeafClass(_) => {} 62 | } 63 | } 64 | Ok(buf) 65 | } 66 | 67 | pub(crate) fn name_for(context: &Context, class: Id) -> Result> { 68 | let rename_to = context 69 | .config 70 | .rename_classes 71 | .get(class.as_str()) 72 | .map(|name| name.as_str()) 73 | .ok_or(()); 74 | let mut buf = String::new(); 75 | for component in class.iter() { 76 | match component { 77 | IdPart::Namespace(_) => {} 78 | IdPart::ContainingClass(id) => write!(&mut buf, "{}_", rust_id(id)?)?, 79 | IdPart::LeafClass(id) => write!( 80 | &mut buf, 81 | "{}", 82 | rename_to.map(ToString::to_string).or_else(|_| rust_id(id))? 83 | )?, 84 | } 85 | } 86 | Ok(buf) 87 | } 88 | 89 | pub(crate) fn new(context: &mut Context, java: JavaClass) -> Result> { 90 | let rust = StructPaths::new(context, java.path())?; 91 | 92 | Ok(Self { rust, java }) 93 | } 94 | 95 | pub(crate) fn write(&self, context: &Context) -> anyhow::Result { 96 | // Ignored access_flags: SUPER, SYNTHETIC, ANNOTATION, ABSTRACT 97 | 98 | let keyword = if self.java.is_interface() { 99 | "interface" 100 | } else if self.java.is_enum() { 101 | "enum" 102 | } else if self.java.is_static() { 103 | "static class" 104 | } else if self.java.is_final() { 105 | "final class" 106 | } else { 107 | "class" 108 | }; 109 | 110 | let visibility = if self.java.is_public() { quote!(pub) } else { quote!() }; 111 | let attributes = match self.java.deprecated() { 112 | true => quote!(#[deprecated] ), 113 | false => quote!(), 114 | }; 115 | 116 | let docs = match KnownDocsUrl::from_class(context, self.java.path()) { 117 | Some(url) => format!("{} {} {}", visibility, keyword, url), 118 | None => format!("{} {} {}", visibility, keyword, self.java.path().as_str()), 119 | }; 120 | 121 | let rust_name = format_ident!("{}", &self.rust.struct_name); 122 | 123 | let referencetype_impl = match self.java.is_static() { 124 | true => quote!(), 125 | false => quote!(unsafe impl ::java_spaghetti::ReferenceType for #rust_name {}), 126 | }; 127 | 128 | let mut out = TokenStream::new(); 129 | 130 | let java_path = cstring(self.java.path().as_str()); 131 | 132 | out.extend(quote!( 133 | #[doc = #docs] 134 | #attributes 135 | #visibility enum #rust_name {} 136 | 137 | #referencetype_impl 138 | 139 | unsafe impl ::java_spaghetti::JniType for #rust_name { 140 | fn static_with_jni_type(callback: impl FnOnce(&::std::ffi::CStr) -> R) -> R { 141 | callback(#java_path) 142 | } 143 | } 144 | )); 145 | 146 | // recursively visit all superclasses and superinterfaces. 147 | let mut queue = Vec::new(); 148 | let mut visited = HashSet::new(); 149 | queue.push(self.java.path()); 150 | visited.insert(self.java.path()); 151 | while let Some(path) = queue.pop() { 152 | let class = context.all_classes.get(path.as_str()).unwrap(); 153 | for path2 in self.java.interfaces().map(|i| Id(i)).chain(class.java.super_path()) { 154 | if context.all_classes.contains_key(path2.as_str()) && !visited.contains(&path2) { 155 | let rust_path = context.java_to_rust_path(path2, &self.rust.mod_).unwrap(); 156 | out.extend(quote!( 157 | unsafe impl ::java_spaghetti::AssignableTo<#rust_path> for #rust_name {} 158 | )); 159 | queue.push(path2); 160 | visited.insert(path2); 161 | } 162 | } 163 | } 164 | 165 | let mut contents = TokenStream::new(); 166 | 167 | let object = context 168 | .java_to_rust_path(Id("java/lang/Object"), &self.rust.mod_) 169 | .unwrap(); 170 | 171 | let class = cstring(self.java.path().as_str()); 172 | 173 | contents.extend(quote!( 174 | fn __class_global_ref(__jni_env: ::java_spaghetti::Env) -> ::java_spaghetti::sys::jobject { 175 | static __CLASS: ::std::sync::OnceLock<::java_spaghetti::Global<#object>> = ::std::sync::OnceLock::new(); 176 | __CLASS 177 | .get_or_init(|| unsafe { 178 | ::java_spaghetti::Local::from_raw(__jni_env, __jni_env.require_class(#class)).as_global() 179 | }) 180 | .as_raw() 181 | } 182 | )); 183 | 184 | let mut id_repeats = HashMap::new(); 185 | 186 | let mut methods: Vec = self 187 | .java 188 | .methods() 189 | .map(|m| Method::new(context, &self.java, m)) 190 | .collect(); 191 | let mut fields: Vec = self.java.fields().map(|f| Field::new(context, &self.java, f)).collect(); 192 | 193 | for method in &methods { 194 | if !method.java.is_public() { 195 | continue; 196 | } // Skip private/protected methods 197 | if let Some(name) = method.rust_name() { 198 | *id_repeats.entry(name.to_owned()).or_insert(0) += 1; 199 | } 200 | } 201 | 202 | for field in &fields { 203 | if !field.java.is_public() { 204 | continue; 205 | } // Skip private/protected fields 206 | match field.rust_names.as_ref() { 207 | Ok(FieldMangling::ConstValue(name, _)) => { 208 | *id_repeats.entry(name.to_owned()).or_insert(0) += 1; 209 | } 210 | Ok(FieldMangling::GetSet(get, set)) => { 211 | *id_repeats.entry(get.to_owned()).or_insert(0) += 1; 212 | *id_repeats.entry(set.to_owned()).or_insert(0) += 1; 213 | } 214 | Err(_) => {} 215 | } 216 | } 217 | 218 | for method in &mut methods { 219 | if let Some(name) = method.rust_name() { 220 | let repeats = *id_repeats.get(name).unwrap_or(&0); 221 | let overloaded = repeats > 1; 222 | if overloaded { 223 | method.set_mangling_style(context.config.codegen.method_naming_style_collision); 224 | } 225 | } 226 | 227 | let res = method.emit(context, &self.rust.mod_).unwrap(); 228 | contents.extend(res); 229 | } 230 | 231 | for field in &mut fields { 232 | let res = field.emit(context, &self.rust.mod_).unwrap(); 233 | contents.extend(res); 234 | } 235 | 236 | out.extend(quote!(impl #rust_name { #contents })); 237 | 238 | if context.proxy_included(&self.java.path().as_str()) { 239 | out.extend(self.write_proxy(context, &methods)?); 240 | } 241 | 242 | Ok(out) 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/fields.rs: -------------------------------------------------------------------------------- 1 | use anyhow::anyhow; 2 | use cafebabe::constant_pool::LiteralConstant; 3 | use cafebabe::descriptors::{FieldDescriptor, FieldType}; 4 | use proc_macro2::{Literal, TokenStream}; 5 | use quote::{format_ident, quote}; 6 | 7 | use super::cstring; 8 | use super::known_docs_url::KnownDocsUrl; 9 | use crate::emit_rust::Context; 10 | use crate::identifiers::{FieldMangling, IdentifierManglingError}; 11 | use crate::parser_util::{ClassName, IdBuf, IterableId, JavaClass, JavaField, emit_field_descriptor}; 12 | 13 | pub struct Field<'a> { 14 | pub class: &'a JavaClass, 15 | pub java: JavaField<'a>, 16 | pub rust_names: Result, IdentifierManglingError>, 17 | pub ignored: bool, 18 | } 19 | 20 | impl<'a> Field<'a> { 21 | pub fn new(context: &Context, class: &'a JavaClass, java: &'a cafebabe::FieldInfo<'a>) -> Self { 22 | let java_class_field = format!("{}\x1f{}", class.path().as_str(), &java.name); 23 | let ignored = context.config.ignore_class_fields.contains(&java_class_field); 24 | let renamed_to = context 25 | .config 26 | .rename_class_fields 27 | .get(&java_class_field) 28 | .map(|s| s.as_str()); 29 | 30 | Self { 31 | class, 32 | java: JavaField::from(java), 33 | rust_names: context 34 | .config 35 | .codegen 36 | .field_naming_style 37 | .mangle(JavaField::from(java), renamed_to), 38 | ignored, 39 | } 40 | } 41 | 42 | pub fn emit(&self, context: &Context, mod_: &str) -> anyhow::Result { 43 | let mut emit_reject_reasons = Vec::new(); 44 | 45 | if !self.java.is_public() { 46 | emit_reject_reasons.push("Non-public field"); 47 | } 48 | if self.ignored { 49 | emit_reject_reasons.push("[[ignore]]d"); 50 | } 51 | 52 | let descriptor = &self.java.descriptor(); 53 | 54 | let rust_set_type = emit_rust_type( 55 | descriptor, 56 | context, 57 | mod_, 58 | RustTypeFlavor::ImplAsArg, 59 | &mut emit_reject_reasons, 60 | )?; 61 | let rust_get_type = emit_rust_type( 62 | descriptor, 63 | context, 64 | mod_, 65 | RustTypeFlavor::OptionLocal, 66 | &mut emit_reject_reasons, 67 | )?; 68 | 69 | let static_fragment = match self.java.is_static() { 70 | false => "", 71 | true => "_static", 72 | }; 73 | let field_fragment = emit_fragment_type(descriptor); 74 | 75 | if self.rust_names.is_err() { 76 | emit_reject_reasons.push(match self.java.name() { 77 | "$VALUES" => "Failed to mangle field name: enum $VALUES", // Expected 78 | s if s.starts_with("this$") => "Failed to mangle field name: this$N outer class pointer", // Expected 79 | _ => "ERROR: Failed to mangle field name(s)", 80 | }); 81 | } 82 | 83 | if !emit_reject_reasons.is_empty() { 84 | // TODO log 85 | return Ok(TokenStream::new()); 86 | } 87 | 88 | let keywords = format!( 89 | "{}{}{}{}", 90 | self.java.access().unwrap_or("???"), 91 | if self.java.is_static() { " static" } else { "" }, 92 | if self.java.is_final() { " final" } else { "" }, 93 | if self.java.is_volatile() { " volatile" } else { "" } 94 | ); 95 | 96 | let attributes = if self.java.deprecated() { 97 | quote!(#[deprecated]) 98 | } else { 99 | quote!() 100 | }; 101 | 102 | let mut out = TokenStream::new(); 103 | 104 | let env_param = if self.java.is_static() { 105 | quote!(__jni_env: ::java_spaghetti::Env<'env>) 106 | } else { 107 | quote!(self: &::java_spaghetti::Ref<'env, Self>) 108 | }; 109 | 110 | let docs = match KnownDocsUrl::from_field( 111 | context, 112 | self.class.path().as_str(), 113 | self.java.name(), 114 | self.java.descriptor().clone(), 115 | ) { 116 | Some(url) => format!("{keywords} {url}"), 117 | None => format!("{keywords} {}", self.java.name()), 118 | }; 119 | 120 | match self.rust_names.as_ref().map_err(|e| anyhow!("bad mangling: {e}"))? { 121 | FieldMangling::ConstValue(constant, value) => { 122 | let constant = format_ident!("{}", constant); 123 | let value = emit_constant(&value, descriptor); 124 | let ty = if descriptor.dimensions == 0 125 | && let FieldType::Object(cls) = &descriptor.field_type 126 | && ClassName::from(cls).is_string_class() 127 | { 128 | quote!(&'static str) 129 | } else { 130 | rust_get_type 131 | }; 132 | 133 | out.extend(quote!( 134 | #[doc = #docs] 135 | #attributes 136 | pub const #constant: #ty = #value; 137 | )); 138 | } 139 | FieldMangling::GetSet(get, set) => { 140 | let get = format_ident!("{get}"); 141 | let set = format_ident!("{set}"); 142 | 143 | let env_let = match self.java.is_static() { 144 | false => quote!(let __jni_env = self.env();), 145 | true => quote!(), 146 | }; 147 | let require_field = format_ident!("require{static_fragment}_field"); 148 | let get_field = format_ident!("get{static_fragment}_{field_fragment}_field"); 149 | let set_field = format_ident!("set{static_fragment}_{field_fragment}_field"); 150 | 151 | let this_or_class = match self.java.is_static() { 152 | false => quote!(self.as_raw()), 153 | true => quote!(__jni_class), 154 | }; 155 | 156 | let java_name = cstring(self.java.name()); 157 | let descriptor = cstring(&emit_field_descriptor(self.java.descriptor())); 158 | 159 | let get_docs = format!("**get** {docs}"); 160 | let set_docs = format!("**set** {docs}"); 161 | out.extend(quote!( 162 | #[doc = #get_docs] 163 | #attributes 164 | pub fn #get<'env>(#env_param) -> #rust_get_type { 165 | static __FIELD: ::std::sync::OnceLock<::java_spaghetti::JFieldID> = ::std::sync::OnceLock::new(); 166 | #env_let 167 | let __jni_class = Self::__class_global_ref(__jni_env); 168 | unsafe { 169 | let __jni_field = __FIELD.get_or_init(|| ::java_spaghetti::JFieldID::from_raw(__jni_env.#require_field(__jni_class, #java_name, #descriptor))).as_raw(); 170 | __jni_env.#get_field(#this_or_class, __jni_field) 171 | } 172 | } 173 | )); 174 | 175 | // Setter 176 | if !self.java.is_final() { 177 | let lifetimes = if field_fragment == "object" { 178 | quote!('env, 'obj) 179 | } else { 180 | quote!('env) 181 | }; 182 | 183 | out.extend(quote!( 184 | #[doc = #set_docs] 185 | #attributes 186 | pub fn #set<#lifetimes>(#env_param, value: #rust_set_type) { 187 | static __FIELD: ::std::sync::OnceLock<::java_spaghetti::JFieldID> = ::std::sync::OnceLock::new(); 188 | #env_let 189 | let __jni_class = Self::__class_global_ref(__jni_env); 190 | unsafe { 191 | let __jni_field = __FIELD.get_or_init(|| ::java_spaghetti::JFieldID::from_raw(__jni_env.#require_field(__jni_class, #java_name, #descriptor))).as_raw(); 192 | __jni_env.#set_field(#this_or_class, __jni_field, value); 193 | } 194 | } 195 | )); 196 | } 197 | } 198 | } 199 | 200 | Ok(out) 201 | } 202 | } 203 | 204 | pub fn emit_constant(constant: &LiteralConstant<'_>, descriptor: &FieldDescriptor) -> TokenStream { 205 | if descriptor.field_type == FieldType::Char && descriptor.dimensions == 0 { 206 | return match constant { 207 | LiteralConstant::Integer(value) => { 208 | let value = *value as i16; 209 | quote!(#value) 210 | } 211 | _ => panic!("invalid constant for char {:?}", constant), 212 | }; 213 | } 214 | if descriptor.field_type == FieldType::Boolean && descriptor.dimensions == 0 { 215 | return match constant { 216 | LiteralConstant::Integer(0) => quote!(false), 217 | LiteralConstant::Integer(1) => quote!(true), 218 | _ => panic!("invalid constant for boolean {:?}", constant), 219 | }; 220 | } 221 | 222 | match constant { 223 | LiteralConstant::Integer(value) => { 224 | let value = Literal::i32_unsuffixed(*value); 225 | quote!(#value) 226 | } 227 | LiteralConstant::Long(value) => { 228 | let value = Literal::i64_unsuffixed(*value); 229 | quote!(#value) 230 | } 231 | 232 | LiteralConstant::Float(value) if value.is_infinite() && *value < 0.0 => { 233 | quote!(::std::f32::NEG_INFINITY) 234 | } 235 | LiteralConstant::Float(value) if value.is_infinite() => quote!(::std::f32::INFINITY), 236 | LiteralConstant::Float(value) if value.is_nan() => quote!(::std::f32::NAN), 237 | LiteralConstant::Float(value) => quote!(#value), 238 | 239 | LiteralConstant::Double(value) if value.is_infinite() && *value < 0.0 => { 240 | quote!(::std::f64::NEG_INFINITY) 241 | } 242 | LiteralConstant::Double(value) if value.is_infinite() => quote!(::std::f64::INFINITY), 243 | LiteralConstant::Double(value) if value.is_nan() => quote!(::std::f64::NAN), 244 | LiteralConstant::Double(value) => quote!(#value), 245 | 246 | LiteralConstant::String(value) => quote! {#value}, 247 | LiteralConstant::StringBytes(_) => { 248 | quote!(panic!("Java string constant contains invalid 'Modified UTF8'")) 249 | } 250 | } 251 | } 252 | 253 | pub enum RustTypeFlavor { 254 | ImplAsArg, 255 | OptionLocal, 256 | OptionRef, 257 | Arg, 258 | Return, 259 | } 260 | 261 | fn flavorify(ty: TokenStream, flavor: RustTypeFlavor) -> TokenStream { 262 | match flavor { 263 | RustTypeFlavor::ImplAsArg => quote!(impl ::java_spaghetti::AsArg<#ty>), 264 | RustTypeFlavor::OptionLocal => quote!(::std::option::Option<::java_spaghetti::Local<'env, #ty>>), 265 | RustTypeFlavor::OptionRef => quote!(::std::option::Option<::java_spaghetti::Ref<'env, #ty>>), 266 | RustTypeFlavor::Arg => quote!(::java_spaghetti::Arg<#ty>), 267 | RustTypeFlavor::Return => quote!(::java_spaghetti::Return<'env, #ty>), 268 | } 269 | } 270 | 271 | /// Generates the corresponding Rust type for the Java field type. 272 | pub fn emit_rust_type( 273 | descriptor: &FieldDescriptor, 274 | context: &Context<'_>, 275 | mod_: &str, 276 | flavor: RustTypeFlavor, 277 | reject_reasons: &mut Vec<&'static str>, 278 | ) -> Result { 279 | let res = if descriptor.dimensions == 0 { 280 | match &descriptor.field_type { 281 | FieldType::Boolean => quote!(bool), 282 | FieldType::Byte => quote!(i8), 283 | FieldType::Char => quote!(u16), 284 | FieldType::Short => quote!(i16), 285 | FieldType::Integer => quote!(i32), 286 | FieldType::Long => quote!(i64), 287 | FieldType::Float => quote!(f32), 288 | FieldType::Double => quote!(f64), 289 | FieldType::Object(class_name) => { 290 | let class = IdBuf::from(class_name); 291 | if !context.all_classes.contains_key(class.as_str()) { 292 | reject_reasons.push("ERROR: missing class for field/argument type"); 293 | } 294 | if let Ok(path) = context.java_to_rust_path(class.as_id(), mod_) { 295 | flavorify(path, flavor) 296 | } else { 297 | reject_reasons.push("ERROR: Failed to resolve JNI path to Rust path for class type"); 298 | let class = class.as_str(); 299 | quote!(#class) // XXX 300 | } 301 | } 302 | } 303 | } else { 304 | let throwable = context.throwable_rust_path(mod_); 305 | 306 | let mut res = match &descriptor.field_type { 307 | FieldType::Boolean => quote!(::java_spaghetti::BooleanArray), 308 | FieldType::Byte => quote!(::java_spaghetti::ByteArray), 309 | FieldType::Char => quote!(::java_spaghetti::CharArray), 310 | FieldType::Short => quote!(::java_spaghetti::ShortArray), 311 | FieldType::Integer => quote!(::java_spaghetti::IntArray), 312 | FieldType::Long => quote!(::java_spaghetti::LongArray), 313 | FieldType::Float => quote!(::java_spaghetti::FloatArray), 314 | FieldType::Double => quote!(::java_spaghetti::DoubleArray), 315 | FieldType::Object(class_name) => { 316 | let class = IdBuf::from(class_name); 317 | 318 | if !context.all_classes.contains_key(class.as_str()) { 319 | reject_reasons.push("ERROR: missing class for field type"); 320 | } 321 | 322 | let path = match context.java_to_rust_path(class.as_id(), mod_) { 323 | Ok(path) => path, 324 | Err(_) => { 325 | reject_reasons.push("ERROR: Failed to resolve JNI path to Rust path for class type"); 326 | quote!(???) 327 | } 328 | }; 329 | 330 | quote!(::java_spaghetti::ObjectArray<#path, #throwable>) 331 | } 332 | }; 333 | for _ in 0..(descriptor.dimensions - 1) { 334 | res = quote!(::java_spaghetti::ObjectArray<#res, #throwable>) 335 | } 336 | 337 | flavorify(res, flavor) 338 | }; 339 | Ok(res) 340 | } 341 | 342 | /// Contents of {get,set}_[static_]..._field, call_..._method_a. 343 | pub fn emit_fragment_type(descriptor: &FieldDescriptor) -> &'static str { 344 | if descriptor.dimensions == 0 { 345 | match descriptor.field_type { 346 | FieldType::Boolean => "boolean", 347 | FieldType::Byte => "byte", 348 | FieldType::Char => "char", 349 | FieldType::Short => "short", 350 | FieldType::Integer => "int", 351 | FieldType::Long => "long", 352 | FieldType::Float => "float", 353 | FieldType::Double => "double", 354 | FieldType::Object(_) => "object", 355 | } 356 | } else { 357 | "object" 358 | } 359 | } 360 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/known_docs_url.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Display, Formatter}; 2 | 3 | use cafebabe::descriptors::{FieldDescriptor, FieldType}; 4 | 5 | use super::methods::Method; 6 | use crate::emit_rust::Context; 7 | use crate::parser_util::{Id, IdBuf}; 8 | 9 | pub(crate) struct KnownDocsUrl { 10 | pub(crate) label: String, 11 | pub(crate) url: String, 12 | } 13 | 14 | impl Display for KnownDocsUrl { 15 | fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { 16 | write!(fmt, "[{}]({})", &self.label, &self.url) 17 | } 18 | } 19 | 20 | impl KnownDocsUrl { 21 | pub(crate) fn from_class(context: &Context, java_class: Id) -> Option { 22 | let java_class = java_class.as_str(); 23 | let pattern = context 24 | .config 25 | .doc_patterns 26 | .iter() 27 | .find(|pattern| java_class.starts_with(pattern.jni_prefix.as_str()))?; 28 | 29 | for ch in java_class.chars() { 30 | match ch { 31 | 'a'..='z' => {} 32 | 'A'..='Z' => {} 33 | '0'..='9' => {} 34 | '_' | '$' | '/' => {} 35 | _ch => return None, 36 | } 37 | } 38 | 39 | let last_slash = java_class.rfind('/'); 40 | let no_namespace = if let Some(last_slash) = last_slash { 41 | &java_class[(last_slash + 1)..] 42 | } else { 43 | java_class 44 | }; 45 | 46 | let java_class = java_class 47 | .replace('/', pattern.class_namespace_separator.as_str()) 48 | .replace('$', pattern.class_inner_class_seperator.as_str()); 49 | 50 | Some(KnownDocsUrl { 51 | label: no_namespace.to_owned().replace('$', "."), 52 | url: pattern 53 | .class_url_pattern 54 | .replace("{CLASS}", java_class.as_str()) 55 | .replace("{CLASS.LOWER}", java_class.to_ascii_lowercase().as_str()), 56 | }) 57 | } 58 | 59 | pub(crate) fn from_method(context: &Context, method: &Method) -> Option { 60 | let is_constructor = method.java.is_constructor(); 61 | 62 | let pattern = context 63 | .config 64 | .doc_patterns 65 | .iter() 66 | .find(|pattern| method.class.path().as_str().starts_with(pattern.jni_prefix.as_str()))?; 67 | let url_pattern = if is_constructor { 68 | pattern 69 | .constructor_url_pattern 70 | .as_ref() 71 | .or(pattern.method_url_pattern.as_ref())? 72 | } else { 73 | pattern.method_url_pattern.as_ref()? 74 | }; 75 | 76 | for ch in method.class.path().as_str().chars() { 77 | match ch { 78 | 'a'..='z' => {} 79 | 'A'..='Z' => {} 80 | '0'..='9' => {} 81 | '_' | '$' | '/' => {} 82 | _ch => return None, 83 | } 84 | } 85 | 86 | let java_class = method 87 | .class 88 | .path() 89 | .as_str() 90 | .replace('/', pattern.class_namespace_separator.as_str()) 91 | .replace('$', pattern.class_inner_class_seperator.as_str()); 92 | 93 | let java_outer_class = method 94 | .class 95 | .path() 96 | .as_str() 97 | .rsplit('/') 98 | .next() 99 | .unwrap() 100 | .replace('$', pattern.class_inner_class_seperator.as_str()); 101 | 102 | let java_inner_class = method 103 | .class 104 | .path() 105 | .as_str() 106 | .rsplit('/') 107 | .next() 108 | .unwrap() 109 | .rsplit('$') 110 | .next() 111 | .unwrap(); 112 | 113 | let label = if is_constructor { 114 | java_inner_class 115 | } else { 116 | for ch in method.java.name().chars() { 117 | match ch { 118 | 'a'..='z' => {} 119 | 'A'..='Z' => {} 120 | '0'..='9' => {} 121 | '_' => {} 122 | _ch => return None, 123 | } 124 | } 125 | method.java.name() 126 | }; 127 | 128 | let mut java_args = String::new(); 129 | 130 | let mut prev_was_array = false; 131 | for arg in method.java.descriptor().parameters.iter() { 132 | if prev_was_array { 133 | prev_was_array = false; 134 | java_args.push_str("[]"); 135 | } 136 | 137 | if !java_args.is_empty() { 138 | java_args.push_str(&pattern.argument_seperator[..]); 139 | } 140 | 141 | let obj_arg; 142 | java_args.push_str(match arg.field_type { 143 | FieldType::Boolean => "boolean", 144 | FieldType::Byte => "byte", 145 | FieldType::Char => "char", 146 | FieldType::Short => "short", 147 | FieldType::Integer => "int", 148 | FieldType::Long => "long", 149 | FieldType::Float => "float", 150 | FieldType::Double => "double", 151 | FieldType::Object(ref class_name) => { 152 | let class = IdBuf::from(class_name); 153 | obj_arg = class 154 | .as_str() 155 | .replace('/', pattern.argument_namespace_separator.as_str()) 156 | .replace('$', pattern.argument_inner_class_seperator.as_str()); 157 | obj_arg.as_str() 158 | } 159 | }); 160 | if arg.dimensions > 0 { 161 | for _ in 1..arg.dimensions { 162 | java_args.push_str("[]"); 163 | } 164 | prev_was_array = true; // level 0 165 | } 166 | } 167 | 168 | if prev_was_array { 169 | if method.java.is_varargs() { 170 | java_args.push_str("..."); 171 | } else { 172 | java_args.push_str("[]"); 173 | } 174 | } 175 | 176 | // No {RETURN} support... yet? 177 | 178 | Some(KnownDocsUrl { 179 | label: label.to_owned(), 180 | url: url_pattern 181 | .replace("{CLASS}", java_class.as_str()) 182 | .replace("{CLASS.LOWER}", java_class.to_ascii_lowercase().as_str()) 183 | .replace("{CLASS.OUTER}", java_outer_class.as_str()) 184 | .replace("{CLASS.INNER}", java_inner_class) 185 | .replace("{METHOD}", label) 186 | .replace("{ARGUMENTS}", java_args.as_str()), 187 | }) 188 | } 189 | 190 | pub(crate) fn from_field( 191 | context: &Context, 192 | java_class: &str, 193 | java_field: &str, 194 | _java_descriptor: FieldDescriptor, 195 | ) -> Option { 196 | let pattern = context 197 | .config 198 | .doc_patterns 199 | .iter() 200 | .find(|pattern| java_class.starts_with(pattern.jni_prefix.as_str()))?; 201 | let field_url_pattern = pattern.field_url_pattern.as_ref()?; 202 | 203 | for ch in java_class.chars() { 204 | match ch { 205 | 'a'..='z' => {} 206 | 'A'..='Z' => {} 207 | '0'..='9' => {} 208 | '_' | '$' | '/' => {} 209 | _ch => return None, 210 | } 211 | } 212 | 213 | for ch in java_field.chars() { 214 | match ch { 215 | 'a'..='z' => {} 216 | 'A'..='Z' => {} 217 | '0'..='9' => {} 218 | '_' => {} 219 | _ch => return None, 220 | } 221 | } 222 | 223 | let java_class = java_class 224 | .replace('/', pattern.class_namespace_separator.as_str()) 225 | .replace('$', pattern.class_inner_class_seperator.as_str()); 226 | 227 | // No {RETURN} support... yet? 228 | 229 | Some(KnownDocsUrl { 230 | label: java_field.to_owned(), 231 | url: field_url_pattern 232 | .replace("{CLASS}", java_class.as_str()) 233 | .replace("{CLASS.LOWER}", java_class.to_ascii_lowercase().as_str()) 234 | .replace("{FIELD}", java_field), 235 | }) 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/methods.rs: -------------------------------------------------------------------------------- 1 | use cafebabe::descriptors::ReturnDescriptor; 2 | use proc_macro2::TokenStream; 3 | use quote::{format_ident, quote}; 4 | 5 | use super::cstring; 6 | use super::fields::{RustTypeFlavor, emit_fragment_type, emit_rust_type}; 7 | use super::known_docs_url::KnownDocsUrl; 8 | use crate::emit_rust::Context; 9 | use crate::identifiers::MethodManglingStyle; 10 | use crate::parser_util::{JavaClass, JavaMethod, emit_method_descriptor}; 11 | 12 | pub struct Method<'a> { 13 | pub class: &'a JavaClass, 14 | pub java: JavaMethod<'a>, 15 | rust_name: Option, 16 | mangling_style: MethodManglingStyle, 17 | } 18 | 19 | impl<'a> Method<'a> { 20 | pub fn new(context: &Context, class: &'a JavaClass, java: &'a cafebabe::MethodInfo<'a>) -> Self { 21 | let mut result = Self { 22 | class, 23 | java: JavaMethod::from(java), 24 | rust_name: None, 25 | mangling_style: MethodManglingStyle::Java, // Immediately overwritten below 26 | }; 27 | result.set_mangling_style(context.config.codegen.method_naming_style); // rust_name + mangling_style 28 | result 29 | } 30 | 31 | pub fn rust_name(&self) -> Option<&str> { 32 | self.rust_name.as_deref() 33 | } 34 | 35 | pub fn set_mangling_style(&mut self, style: MethodManglingStyle) { 36 | self.mangling_style = style; 37 | self.rust_name = self 38 | .mangling_style 39 | .mangle(self.java.name(), self.java.descriptor()) 40 | .ok() 41 | } 42 | 43 | pub fn emit(&self, context: &Context, mod_: &str) -> anyhow::Result { 44 | let mut emit_reject_reasons = Vec::new(); 45 | 46 | let java_class_method = format!("{}\x1f{}", self.class.path().as_str(), self.java.name()); 47 | let java_class_method_sig = format!( 48 | "{}\x1f{}\x1f{}", 49 | self.class.path().as_str(), 50 | self.java.name(), 51 | emit_method_descriptor(self.java.descriptor()) 52 | ); 53 | 54 | let ignored = context.config.ignore_class_methods.contains(&java_class_method) 55 | || context.config.ignore_class_method_sigs.contains(&java_class_method_sig); 56 | 57 | let renamed_to = context 58 | .config 59 | .rename_class_methods 60 | .get(&java_class_method) 61 | .or_else(|| context.config.rename_class_method_sigs.get(&java_class_method_sig)); 62 | 63 | let descriptor = self.java.descriptor(); 64 | 65 | let method_name = if let Some(renamed_to) = renamed_to { 66 | renamed_to.clone() 67 | } else if let Some(name) = self.rust_name() { 68 | name.to_owned() 69 | } else { 70 | emit_reject_reasons.push("ERROR: Failed to mangle method name"); 71 | self.java.name().to_owned() 72 | }; 73 | 74 | if !self.java.is_public() { 75 | emit_reject_reasons.push("Non-public method"); 76 | } 77 | if self.java.is_bridge() { 78 | emit_reject_reasons.push("Bridge method - type erasure"); 79 | } 80 | if self.java.is_static_init() { 81 | emit_reject_reasons.push("Static class constructor - never needs to be called by Rust."); 82 | } 83 | if ignored { 84 | emit_reject_reasons.push("[[ignore]]d"); 85 | } 86 | 87 | // Parameter names may or may not be available as extra debug information. Example: 88 | // https://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html 89 | 90 | let mut params_array = TokenStream::new(); // Contents of let __jni_args = [...]; 91 | 92 | // Contents of fn name<'env>(...) { 93 | let mut params_decl = if self.java.is_constructor() || self.java.is_static() { 94 | quote!(__jni_env: ::java_spaghetti::Env<'env>,) 95 | } else { 96 | quote!(self: &::java_spaghetti::Ref<'env, Self>,) 97 | }; 98 | 99 | for (arg_idx, arg) in descriptor.parameters.iter().enumerate() { 100 | let arg_name = format_ident!("arg{}", arg_idx); 101 | let arg_type = emit_rust_type(arg, context, mod_, RustTypeFlavor::ImplAsArg, &mut emit_reject_reasons)?; 102 | 103 | params_array.extend(quote!(::java_spaghetti::AsJValue::as_jvalue(&#arg_name),)); 104 | params_decl.extend(quote!(#arg_name: #arg_type,)); 105 | } 106 | 107 | let mut ret_decl = if let ReturnDescriptor::Return(desc) = &descriptor.return_type { 108 | emit_rust_type( 109 | desc, 110 | context, 111 | mod_, 112 | RustTypeFlavor::OptionLocal, 113 | &mut emit_reject_reasons, 114 | )? 115 | } else { 116 | quote!(()) 117 | }; 118 | 119 | let mut ret_method_fragment = if let ReturnDescriptor::Return(desc) = &descriptor.return_type { 120 | emit_fragment_type(desc) 121 | } else { 122 | "void" 123 | }; 124 | 125 | if self.java.is_constructor() { 126 | if descriptor.return_type == ReturnDescriptor::Void { 127 | ret_method_fragment = "object"; 128 | ret_decl = quote!(::java_spaghetti::Local<'env, Self>); 129 | } else { 130 | emit_reject_reasons.push("ERROR: Constructor should've returned void"); 131 | } 132 | } 133 | 134 | if !emit_reject_reasons.is_empty() { 135 | // TODO log 136 | return Ok(TokenStream::new()); 137 | } 138 | 139 | let mut out = TokenStream::new(); 140 | 141 | let access = if self.java.is_public() { quote!(pub) } else { quote!() }; 142 | let attributes = if self.java.deprecated() { 143 | quote!(#[deprecated]) 144 | } else { 145 | quote!() 146 | }; 147 | 148 | let docs = match KnownDocsUrl::from_method(context, self) { 149 | Some(url) => format!("{url}"), 150 | None => format!("{}", self.java.name()), 151 | }; 152 | 153 | let throwable = context.throwable_rust_path(mod_); 154 | 155 | let env_let = match !self.java.is_constructor() && !self.java.is_static() { 156 | true => quote!(let __jni_env = self.env();), 157 | false => quote!(), 158 | }; 159 | let require_method = match self.java.is_static() { 160 | false => quote!(require_method), 161 | true => quote!(require_static_method), 162 | }; 163 | 164 | let java_name = cstring(self.java.name()); 165 | let descriptor = cstring(&emit_method_descriptor(self.java.descriptor())); 166 | let method_name = format_ident!("{method_name}"); 167 | 168 | let call = if self.java.is_constructor() { 169 | quote!(__jni_env.new_object_a(__jni_class, __jni_method, __jni_args.as_ptr())) 170 | } else if self.java.is_static() { 171 | let call = format_ident!("call_static_{ret_method_fragment}_method_a"); 172 | quote!( __jni_env.#call(__jni_class, __jni_method, __jni_args.as_ptr())) 173 | } else { 174 | let call = format_ident!("call_{ret_method_fragment}_method_a"); 175 | quote!( __jni_env.#call(self.as_raw(), __jni_method, __jni_args.as_ptr())) 176 | }; 177 | 178 | out.extend(quote!( 179 | #[doc = #docs] 180 | #attributes 181 | #access fn #method_name<'env>(#params_decl) -> ::std::result::Result<#ret_decl, ::java_spaghetti::Local<'env, #throwable>> { 182 | static __METHOD: ::std::sync::OnceLock<::java_spaghetti::JMethodID> = ::std::sync::OnceLock::new(); 183 | unsafe { 184 | let __jni_args = [#params_array]; 185 | #env_let 186 | let __jni_class = Self::__class_global_ref(__jni_env); 187 | let __jni_method = __METHOD.get_or_init(|| 188 | ::java_spaghetti::JMethodID::from_raw(__jni_env.#require_method(__jni_class, #java_name, #descriptor)) 189 | ).as_raw(); 190 | 191 | #call 192 | } 193 | } 194 | )); 195 | 196 | Ok(out) 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/mod.rs: -------------------------------------------------------------------------------- 1 | //! Rust generation logic 2 | 3 | mod class_proxy; 4 | mod classes; 5 | mod fields; 6 | mod known_docs_url; 7 | mod methods; 8 | mod modules; 9 | mod preamble; 10 | 11 | use std::collections::{HashMap, HashSet}; 12 | use std::error::Error; 13 | use std::ffi::CString; 14 | use std::io; 15 | use std::rc::Rc; 16 | use std::str::FromStr; 17 | use std::sync::Mutex; 18 | use std::time::Duration; 19 | 20 | use proc_macro2::{Literal, TokenStream}; 21 | use quote::{TokenStreamExt, format_ident, quote}; 22 | 23 | use self::classes::Class; 24 | use self::modules::Module; 25 | use self::preamble::write_preamble; 26 | use crate::{config, parser_util, util}; 27 | 28 | pub struct Context<'a> { 29 | pub(crate) config: &'a config::runtime::Config, 30 | pub(crate) module: Module, 31 | pub(crate) all_classes: HashMap>, 32 | pub(crate) progress: Mutex, 33 | } 34 | 35 | impl<'a> Context<'a> { 36 | pub fn new(config: &'a config::runtime::Config) -> Self { 37 | Self { 38 | config, 39 | module: Default::default(), 40 | all_classes: HashMap::new(), 41 | progress: Mutex::new(util::Progress::with_duration(Duration::from_millis( 42 | if config.logging_verbose { 0 } else { 300 }, 43 | ))), 44 | } 45 | } 46 | 47 | pub(crate) fn throwable_rust_path(&self, mod_: &str) -> TokenStream { 48 | self.java_to_rust_path(parser_util::Id("java/lang/Throwable"), mod_) 49 | .unwrap() 50 | } 51 | 52 | pub fn java_to_rust_path(&self, java_class: parser_util::Id, mod_: &str) -> Result> { 53 | let m = Class::mod_for(self, java_class)?; 54 | let s = Class::name_for(self, java_class)?; 55 | let fqn = format!("{}::{}", m, s); 56 | 57 | // Calculate relative path from B to A. 58 | let b: Vec<&str> = mod_.split("::").collect(); 59 | let a: Vec<&str> = fqn.split("::").collect(); 60 | 61 | let mut ma = &a[..a.len() - 1]; 62 | let mut mb = &b[..]; 63 | while !ma.is_empty() && !mb.is_empty() && ma[0] == mb[0] { 64 | ma = &ma[1..]; 65 | mb = &mb[1..]; 66 | } 67 | 68 | let mut res = TokenStream::new(); 69 | 70 | // for each item left in b, append a `super` 71 | for _ in mb { 72 | res.extend(quote!(super::)); 73 | } 74 | 75 | // for each item in a, append it 76 | for ident in ma { 77 | let ident = format_ident!("{}", ident); 78 | res.extend(quote!(#ident::)); 79 | } 80 | 81 | let ident = format_ident!("{}", a[a.len() - 1]); 82 | res.append(ident); 83 | 84 | Ok(res) 85 | } 86 | 87 | fn class_included(&self, path: &str) -> bool { 88 | self.included(path, &self.config.include_classes) 89 | } 90 | 91 | fn proxy_included(&self, path: &str) -> bool { 92 | self.included(path, &self.config.include_proxies) 93 | } 94 | 95 | fn included(&self, path: &str, set: &HashSet) -> bool { 96 | if set.contains(path) { 97 | return true; 98 | } 99 | if set.contains("*") { 100 | return true; 101 | } 102 | 103 | let mut pat = String::new(); 104 | for p in path.split('/') { 105 | pat.push_str(p); 106 | if pat.len() == path.len() { 107 | break; 108 | } 109 | 110 | pat.push('/'); 111 | pat.push('*'); 112 | if set.contains(&pat) { 113 | return true; 114 | } 115 | pat.pop(); 116 | } 117 | 118 | false 119 | } 120 | 121 | pub fn add_class(&mut self, class: parser_util::JavaClass) -> Result<(), Box> { 122 | if self.config.ignore_classes.contains(class.path().as_str()) { 123 | return Ok(()); 124 | } 125 | if !self.class_included(class.path().as_str()) { 126 | return Ok(()); 127 | } 128 | 129 | let java_path = class.path().as_str().to_string(); 130 | let s = Rc::new(Class::new(self, class)?); 131 | 132 | self.all_classes.insert(java_path, s.clone()); 133 | 134 | let mut rust_mod = &mut self.module; 135 | for fragment in s.rust.mod_.split("::") { 136 | rust_mod = rust_mod.modules.entry(fragment.to_owned()).or_default(); 137 | } 138 | if rust_mod.classes.contains_key(&s.rust.struct_name) { 139 | return io_data_err!( 140 | "Unable to add_class(): java class name {:?} was already added", 141 | &s.rust.struct_name 142 | )?; 143 | } 144 | rust_mod.classes.insert(s.rust.struct_name.clone(), s); 145 | 146 | Ok(()) 147 | } 148 | 149 | pub fn write(&self, out: &mut impl io::Write) -> anyhow::Result<()> { 150 | write_preamble(out)?; 151 | self.module.write(self, out) 152 | } 153 | } 154 | 155 | fn cstring(s: &str) -> Literal { 156 | Literal::c_string(&CString::from_str(s).unwrap()) 157 | } 158 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/modules.rs: -------------------------------------------------------------------------------- 1 | use core::fmt; 2 | use std::collections::BTreeMap; 3 | use std::fmt::Write; 4 | use std::io; 5 | use std::rc::Rc; 6 | 7 | use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree}; 8 | 9 | use super::classes::Class; 10 | use crate::emit_rust::Context; 11 | 12 | #[derive(Debug, Default)] 13 | pub(crate) struct Module { 14 | // For consistent diffs / printing order, these should *not* be HashMaps 15 | pub(crate) classes: BTreeMap>, 16 | pub(crate) modules: BTreeMap, 17 | } 18 | 19 | impl Module { 20 | pub(crate) fn write(&self, context: &Context, out: &mut impl io::Write) -> anyhow::Result<()> { 21 | for (name, module) in self.modules.iter() { 22 | writeln!(out)?; 23 | 24 | writeln!(out, "pub mod {} {{", name)?; 25 | module.write(context, out)?; 26 | writeln!(out, "}}")?; 27 | } 28 | 29 | for (_, class) in self.classes.iter() { 30 | let res = class.write(context)?; 31 | out.write(dumb_format(res).as_bytes())?; 32 | } 33 | 34 | Ok(()) 35 | } 36 | } 37 | 38 | /// Convert tokenstream to string, doing a best-effort formatting 39 | /// inserting newlines at `;` and `{}`. 40 | /// 41 | /// The user is supposed to run the output through `rustfmt`, this is 42 | /// intended just to prevent the output from being a single huge line 43 | /// to make debugging syntax errors easier. 44 | fn dumb_format(ts: TokenStream) -> String { 45 | let mut f = DumbFormatter { 46 | space: false, 47 | after_newline: true, 48 | indent: 1, 49 | f: String::new(), 50 | }; 51 | f.format_tokenstream(ts); 52 | f.f 53 | } 54 | 55 | struct DumbFormatter { 56 | space: bool, 57 | after_newline: bool, 58 | indent: usize, 59 | f: String, 60 | } 61 | 62 | impl DumbFormatter { 63 | fn newline(&mut self) { 64 | self.f.push_str("\n"); 65 | for _ in 0..self.indent { 66 | self.f.push_str(" "); 67 | } 68 | 69 | self.after_newline = true; 70 | } 71 | 72 | fn pre_write(&mut self) { 73 | if self.space && !self.after_newline { 74 | self.f.push_str(" "); 75 | } 76 | self.space = false; 77 | self.after_newline = false; 78 | } 79 | 80 | fn write_str(&mut self, s: &str) { 81 | self.pre_write(); 82 | self.f.push_str(s); 83 | } 84 | 85 | fn write_display(&mut self, d: impl fmt::Display) { 86 | self.pre_write(); 87 | write!(&mut self.f, "{d}").unwrap(); 88 | } 89 | 90 | fn format_tokenstream(&mut self, ts: TokenStream) { 91 | for tt in ts { 92 | match tt { 93 | TokenTree::Group(tt) => { 94 | let (open, close) = match tt.delimiter() { 95 | Delimiter::Parenthesis => ("(", ")"), 96 | Delimiter::Brace => ("{ ", "}"), 97 | Delimiter::Bracket => ("[", "]"), 98 | Delimiter::None => ("", ""), 99 | }; 100 | 101 | self.write_str(open); 102 | let ts = tt.stream(); 103 | let empty = ts.is_empty(); 104 | if tt.delimiter() == Delimiter::Brace && !empty { 105 | self.indent += 1; 106 | self.newline(); 107 | } 108 | self.format_tokenstream(ts); 109 | if tt.delimiter() == Delimiter::Brace && !empty { 110 | self.write_str(" "); 111 | self.indent -= 1; 112 | } 113 | self.write_str(close); 114 | if tt.delimiter() == Delimiter::Brace { 115 | self.newline(); 116 | } 117 | } 118 | TokenTree::Ident(tt) => { 119 | self.write_display(tt); 120 | self.space = true; 121 | } 122 | TokenTree::Punct(tt) => { 123 | self.write_display(&tt); 124 | if tt.spacing() == Spacing::Alone { 125 | self.space = true; 126 | } 127 | 128 | if tt.as_char() == ';' { 129 | self.newline(); 130 | } 131 | } 132 | TokenTree::Literal(tt) => { 133 | self.write_display(tt); 134 | self.space = true; 135 | } 136 | }; 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/preamble-contents.rs: -------------------------------------------------------------------------------- 1 | // WARNING: This file was autogenerated by java-spaghetti. Any changes to this file may be lost!!! 2 | 3 | #![allow(unused_imports)] 4 | #![allow(non_camel_case_types)] // We map Java inner classes to Outer_Inner 5 | #![allow(dead_code)] // We generate structs for private Java types too, just in case. 6 | #![allow(deprecated)] // We're generating deprecated types/methods 7 | #![allow(non_upper_case_globals)] // We might be generating Java style fields/methods 8 | #![allow(non_snake_case)] // We might be generating Java style fields/methods 9 | #![allow(clippy::all)] // we don't ensure generated bindings are clippy-compliant at all. 10 | #![allow(unsafe_code)] // play nice if user has `deny(unsafe_code)` in their crate. 11 | 12 | mod util { 13 | use std::char::DecodeUtf16Error; 14 | use std::fmt; 15 | 16 | use java_spaghetti::sys::jsize; 17 | use java_spaghetti::{Env, JavaDebug, Local, Ref, StringChars, ThrowableType}; 18 | 19 | use super::java::lang::{String as JString, Throwable}; 20 | 21 | impl JavaDebug for Throwable { 22 | fn fmt(self: &Ref<'_, Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result { 23 | writeln!(f, "java::lang::Throwable")?; 24 | 25 | match self.getMessage() { 26 | Ok(Some(message)) => writeln!(f, " getMessage: {:?}", message)?, 27 | Ok(None) => writeln!(f, " getMessage: N/A (returned null)")?, 28 | Err(_) => writeln!(f, " getMessage: N/A (threw an exception!)")?, 29 | } 30 | 31 | match self.getLocalizedMessage() { 32 | Ok(Some(message)) => writeln!(f, " getLocalizedMessage: {:?}", message)?, 33 | Ok(None) => writeln!(f, " getLocalizedMessage: N/A (returned null)")?, 34 | Err(_) => writeln!(f, " getLocalizedMessage: N/A (threw an exception!)")?, 35 | } 36 | 37 | match self.getStackTrace() { 38 | Err(_) => writeln!(f, " getStackTrace: N/A (threw an exception!)")?, 39 | Ok(None) => writeln!(f, " getStackTrace: N/A (returned null)")?, 40 | Ok(Some(stack_trace)) => { 41 | writeln!(f, " getStackTrace:")?; 42 | for frame in stack_trace.iter() { 43 | match frame { 44 | None => writeln!(f, " N/A (frame was null)")?, 45 | Some(frame) => { 46 | let file_line = match (frame.getFileName(), frame.getLineNumber()) { 47 | (Ok(Some(file)), Ok(line)) => { 48 | format!("{}({}):", file.to_string_lossy(), line) 49 | } 50 | (Ok(Some(file)), _) => format!("{}:", file.to_string_lossy()), 51 | (_, _) => "N/A (getFileName threw an exception or returned null)".to_owned(), 52 | }; 53 | 54 | let class_method = match (frame.getClassName(), frame.getMethodName()) { 55 | (Ok(Some(class)), Ok(Some(method))) => { 56 | format!("{}.{}", class.to_string_lossy(), method.to_string_lossy()) 57 | } 58 | (Ok(Some(class)), _) => class.to_string_lossy(), 59 | (_, Ok(Some(method))) => method.to_string_lossy(), 60 | (_, _) => "N/A (getClassName + getMethodName threw exceptions or returned null)" 61 | .to_owned(), 62 | }; 63 | 64 | writeln!(f, " {:120}{}", file_line, class_method)?; 65 | } 66 | } 67 | } 68 | } 69 | } 70 | 71 | // Consider also dumping: 72 | // API level 1+: 73 | // getCause() 74 | // API level 19+: 75 | // getSuppressed() 76 | 77 | Ok(()) 78 | } 79 | } 80 | 81 | impl JString { 82 | /// Create new local string from an Env + AsRef 83 | pub fn from_env_str<'env, S: AsRef>(env: Env<'env>, string: S) -> Local<'env, Self> { 84 | let chars = string.as_ref().encode_utf16().collect::>(); 85 | 86 | let string = unsafe { env.new_string(chars.as_ptr(), chars.len() as jsize) }; 87 | unsafe { Local::from_raw(env, string) } 88 | } 89 | 90 | fn string_chars<'env>(self: &Ref<'env, Self>) -> StringChars<'env> { 91 | unsafe { StringChars::from_env_jstring(self.env(), self.as_raw()) } 92 | } 93 | 94 | /// Returns a new [Ok]\([String]\), or an [Err]\([DecodeUtf16Error]\) if if it contained any invalid UTF16. 95 | /// 96 | /// [Ok]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok 97 | /// [Err]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err 98 | /// [DecodeUtf16Error]: https://doc.rust-lang.org/std/char/struct.DecodeUtf16Error.html 99 | /// [String]: https://doc.rust-lang.org/std/string/struct.String.html 100 | /// [REPLACEMENT_CHARACTER]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html 101 | pub fn to_string(self: &Ref<'_, Self>) -> Result { 102 | self.string_chars().to_string() 103 | } 104 | 105 | /// Returns a new [String] with any invalid UTF16 characters replaced with [REPLACEMENT_CHARACTER]s (`'\u{FFFD}'`.) 106 | /// 107 | /// [String]: https://doc.rust-lang.org/std/string/struct.String.html 108 | /// [REPLACEMENT_CHARACTER]: https://doc.rust-lang.org/std/char/constant.REPLACEMENT_CHARACTER.html 109 | pub fn to_string_lossy(self: &Ref<'_, Self>) -> String { 110 | self.string_chars().to_string_lossy() 111 | } 112 | } 113 | 114 | // OsString doesn't implement Display, so neither does java::lang::String. 115 | impl JavaDebug for JString { 116 | fn fmt(self: &Ref<'_, Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result { 117 | fmt::Debug::fmt(&self.to_string_lossy(), f) // XXX: Unneccessary alloc? Shouldn't use lossy here? 118 | } 119 | } 120 | 121 | impl ThrowableType for Throwable {} 122 | } 123 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/emit_rust/preamble.rs: -------------------------------------------------------------------------------- 1 | use std::io::{self, Write}; 2 | 3 | pub fn write_preamble(out: &mut impl Write) -> io::Result<()> { 4 | write!(out, "{}", include_str!("preamble-contents.rs"))?; 5 | writeln!(out)?; 6 | writeln!(out)?; 7 | Ok(()) 8 | } 9 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/identifiers/field_mangling_style.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Deserialize; 2 | 3 | use crate::identifiers::{IdentifierManglingError, constify_identifier, javaify_identifier, rustify_identifier}; 4 | use crate::parser_util::JavaField; 5 | 6 | pub enum FieldMangling<'a> { 7 | ConstValue(String, cafebabe::constant_pool::LiteralConstant<'a>), 8 | GetSet(String, String), 9 | } 10 | 11 | #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)] 12 | pub struct FieldManglingStyle { 13 | pub const_finals: bool, // Default: true 14 | pub rustify_names: bool, // Default: true 15 | pub getter_pattern: String, // Default: "{NAME}", might consider "get_{NAME}" 16 | pub setter_pattern: String, // Default: "set_{NAME}" 17 | } 18 | 19 | impl Default for FieldManglingStyle { 20 | fn default() -> Self { 21 | Self { 22 | const_finals: true, 23 | rustify_names: true, 24 | getter_pattern: String::from("{NAME}"), 25 | setter_pattern: String::from("set_{NAME}"), 26 | } 27 | } 28 | } 29 | 30 | impl FieldManglingStyle { 31 | pub fn mangle<'a>( 32 | &self, 33 | field: JavaField<'a>, 34 | renamed_to: Option<&str>, 35 | ) -> Result, IdentifierManglingError> { 36 | let field_name = renamed_to.unwrap_or(field.name()); 37 | if let (Some(value), true) = (field.constant().as_ref(), self.const_finals) { 38 | let name = if renamed_to.is_some() { 39 | Ok(field_name.to_owned()) // Don't remangle renames 40 | } else if self.rustify_names { 41 | constify_identifier(field_name) 42 | } else { 43 | javaify_identifier(field_name) 44 | }?; 45 | 46 | Ok(FieldMangling::ConstValue(name, value.clone())) 47 | } else { 48 | Ok(FieldMangling::GetSet( 49 | self.mangle_identifier(self.getter_pattern.replace("{NAME}", field_name).as_str())?, 50 | self.mangle_identifier(self.setter_pattern.replace("{NAME}", field_name).as_str())?, 51 | )) 52 | } 53 | } 54 | 55 | fn mangle_identifier(&self, ident: &str) -> Result { 56 | if self.rustify_names { 57 | rustify_identifier(ident) 58 | } else { 59 | javaify_identifier(ident) 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/identifiers/method_mangling_style.rs: -------------------------------------------------------------------------------- 1 | use cafebabe::descriptors::{FieldType, MethodDescriptor}; 2 | use serde_derive::Deserialize; 3 | 4 | use super::rust_identifier::{IdentifierManglingError, javaify_identifier, rustify_identifier}; 5 | use crate::parser_util::{ClassName, IdPart}; 6 | 7 | #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash)] 8 | #[serde(rename_all = "snake_case")] 9 | pub enum MethodManglingStyle { 10 | /// Leave the original method name alone as much as possible. 11 | /// Constructors will still be renamed from "\" to "new". 12 | /// 13 | /// # Examples: 14 | /// 15 | /// | Java | Rust | 16 | /// | --------- | --------- | 17 | /// | getFoo | getFoo | 18 | /// | \ | new | 19 | Java, 20 | 21 | /// Leave the original method name alone as much as possible... with unqualified typenames appended for disambiguation. 22 | /// Constructors will still be renamed from "\" to "new". 23 | /// 24 | /// # Examples: 25 | /// 26 | /// | Java | Rust | 27 | /// | --------- | ------------- | 28 | /// | getFoo | getFoo_int | 29 | /// | \ | new_Object | 30 | JavaShortSignature, 31 | 32 | /// Leave the original method name alone as much as possible... with qualified typenames appended for disambiguation. 33 | /// Constructors will still be renamed from "\" to "new". 34 | /// 35 | /// # Examples: 36 | /// 37 | /// | Java | Rust | 38 | /// | --------- | --------------------- | 39 | /// | getFoo | getFoo_int | 40 | /// | \ | new_java_lang_Object | 41 | JavaLongSignature, 42 | 43 | /// Rename the method to use rust style naming conventions. 44 | /// 45 | /// # Examples: 46 | /// 47 | /// | Java | Rust | 48 | /// | --------- | --------- | 49 | /// | getFoo | get_foo | 50 | /// | \ | new | 51 | Rustify, 52 | 53 | /// Rename the method to use rust style naming conventions, with unqualified typenames appended for disambiguation. 54 | /// 55 | /// # Examples: 56 | /// 57 | /// | Java | Rust | 58 | /// | --------- | ------------- | 59 | /// | getFoo | get_foo_int | 60 | /// | \ | new_object | 61 | RustifyShortSignature, 62 | 63 | /// Rename the method to use rust style naming conventions, with qualified typenames appended for disambiguation. 64 | /// 65 | /// # Examples: 66 | /// 67 | /// | Java | Rust | 68 | /// | --------- | --------------------- | 69 | /// | getFoo | get_foo_int | 70 | /// | \ | new_java_lang_object | 71 | RustifyLongSignature, 72 | } 73 | 74 | #[test] 75 | fn method_mangling_style_mangle_test() { 76 | use std::borrow::Cow; 77 | 78 | use cafebabe::descriptors::{FieldDescriptor, ReturnDescriptor, UnqualifiedSegment}; 79 | 80 | let desc_no_arg_ret_v = MethodDescriptor { 81 | parameters: Vec::new(), 82 | return_type: ReturnDescriptor::Void, 83 | }; 84 | 85 | let desc_arg_i_ret_v = MethodDescriptor { 86 | parameters: vec![FieldDescriptor { 87 | dimensions: 0, 88 | field_type: FieldType::Integer, 89 | }], 90 | return_type: ReturnDescriptor::Void, 91 | }; 92 | 93 | let desc_arg_obj_ret_v = MethodDescriptor { 94 | parameters: vec![FieldDescriptor { 95 | dimensions: 0, 96 | field_type: FieldType::Object(cafebabe::descriptors::ClassName { 97 | segments: vec![ 98 | UnqualifiedSegment { 99 | name: Cow::Borrowed("java"), 100 | }, 101 | UnqualifiedSegment { 102 | name: Cow::Borrowed("lang"), 103 | }, 104 | UnqualifiedSegment { 105 | name: Cow::Borrowed("Object"), 106 | }, 107 | ], 108 | }), 109 | }], 110 | return_type: ReturnDescriptor::Void, 111 | }; 112 | 113 | for &(name, sig, java, java_short, java_long, rust, rust_short, rust_long) in &[ 114 | ( 115 | "getFoo", 116 | &desc_no_arg_ret_v, 117 | "getFoo", 118 | "getFoo", 119 | "getFoo", 120 | "get_foo", 121 | "get_foo", 122 | "get_foo", 123 | ), 124 | ( 125 | "getFoo", 126 | &desc_arg_i_ret_v, 127 | "getFoo", 128 | "getFoo_int", 129 | "getFoo_int", 130 | "get_foo", 131 | "get_foo_int", 132 | "get_foo_int", 133 | ), 134 | ( 135 | "getFoo", 136 | &desc_arg_obj_ret_v, 137 | "getFoo", 138 | "getFoo_Object", 139 | "getFoo_java_lang_Object", 140 | "get_foo", 141 | "get_foo_object", 142 | "get_foo_java_lang_object", 143 | ), 144 | ("", &desc_no_arg_ret_v, "new", "new", "new", "new", "new", "new"), 145 | ( 146 | "", 147 | &desc_arg_i_ret_v, 148 | "new", 149 | "new_int", 150 | "new_int", 151 | "new", 152 | "new_int", 153 | "new_int", 154 | ), 155 | ( 156 | "", 157 | &desc_arg_obj_ret_v, 158 | "new", 159 | "new_Object", 160 | "new_java_lang_Object", 161 | "new", 162 | "new_object", 163 | "new_java_lang_object", 164 | ), 165 | // TODO: get1DFoo 166 | // TODO: array types (primitive + non-primitive) 167 | ] { 168 | assert_eq!(MethodManglingStyle::Java.mangle(name, sig).unwrap(), java); 169 | assert_eq!( 170 | MethodManglingStyle::JavaShortSignature.mangle(name, sig).unwrap(), 171 | java_short 172 | ); 173 | assert_eq!( 174 | MethodManglingStyle::JavaLongSignature.mangle(name, sig).unwrap(), 175 | java_long 176 | ); 177 | 178 | assert_eq!(MethodManglingStyle::Rustify.mangle(name, sig).unwrap(), rust); 179 | assert_eq!( 180 | MethodManglingStyle::RustifyShortSignature.mangle(name, sig).unwrap(), 181 | rust_short 182 | ); 183 | assert_eq!( 184 | MethodManglingStyle::RustifyLongSignature.mangle(name, sig).unwrap(), 185 | rust_long 186 | ); 187 | } 188 | } 189 | 190 | #[test] 191 | fn mangle_method_name_test() { 192 | use cafebabe::descriptors::{MethodDescriptor, ReturnDescriptor}; 193 | 194 | let desc = MethodDescriptor { 195 | parameters: Vec::new(), 196 | return_type: ReturnDescriptor::Void, 197 | }; 198 | 199 | assert_eq!( 200 | MethodManglingStyle::Rustify.mangle("isFooBar", &desc).unwrap(), 201 | "is_foo_bar" 202 | ); 203 | assert_eq!( 204 | MethodManglingStyle::Rustify.mangle("XMLHttpRequest", &desc).unwrap(), 205 | "xml_http_request" 206 | ); 207 | assert_eq!( 208 | MethodManglingStyle::Rustify.mangle("getFieldID_Input", &desc).unwrap(), 209 | "get_field_id_input" 210 | ); 211 | } 212 | 213 | impl MethodManglingStyle { 214 | pub fn mangle(&self, name: &str, descriptor: &MethodDescriptor) -> Result { 215 | let name = match name { 216 | "" => { 217 | return Err(IdentifierManglingError::EmptyString); 218 | } 219 | "" => "new", 220 | "" => { 221 | return Err(IdentifierManglingError::NotApplicable("Static type ctor")); 222 | } 223 | name => name, 224 | }; 225 | 226 | let (rustify, long_sig) = match self { 227 | MethodManglingStyle::Java => return javaify_identifier(name), 228 | MethodManglingStyle::Rustify => return rustify_identifier(name), 229 | MethodManglingStyle::JavaShortSignature => (false, false), 230 | MethodManglingStyle::JavaLongSignature => (false, true), 231 | MethodManglingStyle::RustifyShortSignature => (true, false), 232 | MethodManglingStyle::RustifyLongSignature => (true, true), 233 | }; 234 | 235 | let mut buffer = name.to_string(); 236 | 237 | for arg in descriptor.parameters.iter() { 238 | match &arg.field_type { 239 | FieldType::Boolean => buffer.push_str("_boolean"), 240 | FieldType::Byte => buffer.push_str("_byte"), 241 | FieldType::Char => buffer.push_str("_char"), 242 | FieldType::Short => buffer.push_str("_short"), 243 | FieldType::Integer => buffer.push_str("_int"), 244 | FieldType::Long => buffer.push_str("_long"), 245 | FieldType::Float => buffer.push_str("_float"), 246 | FieldType::Double => buffer.push_str("_double"), 247 | FieldType::Object(class_name) => { 248 | let class = ClassName::from(class_name); 249 | 250 | if long_sig { 251 | for component in class.iter() { 252 | buffer.push('_'); 253 | match component { 254 | IdPart::Namespace(namespace) => { 255 | buffer.push_str(namespace); 256 | } 257 | IdPart::ContainingClass(cls) => { 258 | buffer.push_str(cls); 259 | } 260 | IdPart::LeafClass(cls) => { 261 | buffer.push_str(cls); 262 | } 263 | } 264 | } 265 | } else { 266 | // short style 267 | if let Some(IdPart::LeafClass(leaf)) = class.iter().last() { 268 | buffer.push('_'); 269 | buffer.push_str(leaf); 270 | } else if arg.dimensions == 0 { 271 | // XXX: `if arg.dimensions == 0` is just keeping the behaviour 272 | // before porting to cafebabe, is it a bug? 273 | buffer.push_str("_unknown"); 274 | } 275 | } 276 | } 277 | }; 278 | for _ in 0..arg.dimensions { 279 | buffer.push_str("_array"); 280 | } 281 | } 282 | 283 | if rustify { 284 | rustify_identifier(&buffer) 285 | } else { 286 | javaify_identifier(&buffer) 287 | } 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/identifiers/mod.rs: -------------------------------------------------------------------------------- 1 | //! JNI and Rust identifier parsing and categorizing utilities 2 | 3 | mod field_mangling_style; 4 | mod method_mangling_style; 5 | mod rust_identifier; 6 | 7 | pub use field_mangling_style::*; 8 | pub use method_mangling_style::*; 9 | pub use rust_identifier::*; 10 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/identifiers/rust_identifier.rs: -------------------------------------------------------------------------------- 1 | /// Categorizes a rust [identifier](https://doc.rust-lang.org/reference/identifiers.html) for use in rust codegen. 2 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 3 | pub enum RustIdentifier { 4 | /// Meets the criteria for a Rust [NON_KEYWORD_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html) 5 | Identifier(String), 6 | 7 | /// Not a rust-safe [identifier](https://doc.rust-lang.org/reference/identifiers.html). Unicode, strange ASCII 8 | /// values, relatively normal ASCII values... you name it. 9 | NonIdentifier(String), 10 | 11 | /// A [keyword](https://doc.rust-lang.org/reference/keywords.html) that has had `r#` prepended to it, because it can 12 | /// be used as a [RAW_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html) 13 | KeywordRawSafe(String), 14 | 15 | /// A [keyword](https://doc.rust-lang.org/reference/keywords.html) that has had `_` postpended to it, because it can 16 | /// *not* be used as a [RAW_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html). 17 | KeywordUnderscorePostfix(String), 18 | } 19 | 20 | impl RustIdentifier { 21 | /// Takes an arbitrary string and tries to treat it as a Rust identifier, doing minor escaping for keywords. 22 | pub fn from_str(s: &str) -> RustIdentifier { 23 | match s { 24 | // [Strict keywords](https://doc.rust-lang.org/reference/keywords.html#strict-keywords) that *are not* valid 25 | // [RAW_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html)s 26 | "crate" => RustIdentifier::KeywordUnderscorePostfix("crate_".to_string()), 27 | "extern" => RustIdentifier::KeywordUnderscorePostfix("extern_".to_string()), 28 | "self" => RustIdentifier::KeywordUnderscorePostfix("self_".to_string()), 29 | "super" => RustIdentifier::KeywordUnderscorePostfix("super_".to_string()), 30 | "Self" => RustIdentifier::KeywordUnderscorePostfix("Self_".to_string()), 31 | 32 | // [Strict keywords](https://doc.rust-lang.org/reference/keywords.html#strict-keywords) that *are* valid 33 | // [RAW_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html)s 34 | "as" => RustIdentifier::KeywordRawSafe("r#as".to_string()), 35 | "break" => RustIdentifier::KeywordRawSafe("r#break".to_string()), 36 | "const" => RustIdentifier::KeywordRawSafe("r#const".to_string()), 37 | "continue" => RustIdentifier::KeywordRawSafe("r#continue".to_string()), 38 | "else" => RustIdentifier::KeywordRawSafe("r#else".to_string()), 39 | "enum" => RustIdentifier::KeywordRawSafe("r#enum".to_string()), 40 | "false" => RustIdentifier::KeywordRawSafe("r#false".to_string()), 41 | "fn" => RustIdentifier::KeywordRawSafe("r#fn".to_string()), 42 | "for" => RustIdentifier::KeywordRawSafe("r#for".to_string()), 43 | "if" => RustIdentifier::KeywordRawSafe("r#if".to_string()), 44 | "impl" => RustIdentifier::KeywordRawSafe("r#impl".to_string()), 45 | "in" => RustIdentifier::KeywordRawSafe("r#in".to_string()), 46 | "let" => RustIdentifier::KeywordRawSafe("r#let".to_string()), 47 | "loop" => RustIdentifier::KeywordRawSafe("r#loop".to_string()), 48 | "match" => RustIdentifier::KeywordRawSafe("r#match".to_string()), 49 | "mod" => RustIdentifier::KeywordRawSafe("r#mod".to_string()), 50 | "move" => RustIdentifier::KeywordRawSafe("r#move".to_string()), 51 | "mut" => RustIdentifier::KeywordRawSafe("r#mut".to_string()), 52 | "pub" => RustIdentifier::KeywordRawSafe("r#pub".to_string()), 53 | "ref" => RustIdentifier::KeywordRawSafe("r#ref".to_string()), 54 | "return" => RustIdentifier::KeywordRawSafe("r#return".to_string()), 55 | "static" => RustIdentifier::KeywordRawSafe("r#static".to_string()), 56 | "struct" => RustIdentifier::KeywordRawSafe("r#struct".to_string()), 57 | "trait" => RustIdentifier::KeywordRawSafe("r#trait".to_string()), 58 | "true" => RustIdentifier::KeywordRawSafe("r#true".to_string()), 59 | "type" => RustIdentifier::KeywordRawSafe("r#type".to_string()), 60 | "unsafe" => RustIdentifier::KeywordRawSafe("r#unsafe".to_string()), 61 | "use" => RustIdentifier::KeywordRawSafe("r#use".to_string()), 62 | "where" => RustIdentifier::KeywordRawSafe("r#where".to_string()), 63 | "while" => RustIdentifier::KeywordRawSafe("r#while".to_string()), 64 | "dyn" => RustIdentifier::KeywordRawSafe("r#dyn".to_string()), 65 | 66 | // [Reserved keywords](https://doc.rust-lang.org/reference/keywords.html#reserved-keywords) that *are* valid 67 | // [RAW_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html)s 68 | "abstract" => RustIdentifier::KeywordRawSafe("r#abstract".to_string()), 69 | "become" => RustIdentifier::KeywordRawSafe("r#become".to_string()), 70 | "box" => RustIdentifier::KeywordRawSafe("r#box".to_string()), 71 | "do" => RustIdentifier::KeywordRawSafe("r#do".to_string()), 72 | "final" => RustIdentifier::KeywordRawSafe("r#final".to_string()), 73 | "macro" => RustIdentifier::KeywordRawSafe("r#macro".to_string()), 74 | "override" => RustIdentifier::KeywordRawSafe("r#override".to_string()), 75 | "priv" => RustIdentifier::KeywordRawSafe("r#priv".to_string()), 76 | "typeof" => RustIdentifier::KeywordRawSafe("r#typeof".to_string()), 77 | "unsized" => RustIdentifier::KeywordRawSafe("r#unsized".to_string()), 78 | "virtual" => RustIdentifier::KeywordRawSafe("r#virtual".to_string()), 79 | "yield" => RustIdentifier::KeywordRawSafe("r#yield".to_string()), 80 | // 2018 edition 81 | "async" => RustIdentifier::KeywordRawSafe("r#async".to_string()), 82 | "await" => RustIdentifier::KeywordRawSafe("r#await".to_string()), 83 | "try" => RustIdentifier::KeywordRawSafe("r#try".to_string()), 84 | 85 | // [Weak keywords](https://doc.rust-lang.org/reference/keywords.html#weak-keywords) that *are* valid 86 | // [RAW_IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html)s 87 | "union" => RustIdentifier::KeywordRawSafe("r#union".to_string()), 88 | 89 | // Not a keyword, but not a valid [IDENTIFIER](https://doc.rust-lang.org/reference/identifiers.html) either. 90 | "" => RustIdentifier::NonIdentifier(s.to_string()), 91 | "_" => RustIdentifier::NonIdentifier(s.to_string()), 92 | s if is_rust_identifier(s) => RustIdentifier::Identifier(s.to_string()), 93 | s if is_rust_identifier(&format!("_{s}")) => RustIdentifier::Identifier(format!("_{s}")), 94 | s => RustIdentifier::NonIdentifier(s.to_string()), 95 | } 96 | } 97 | } 98 | 99 | #[test] 100 | fn rust_identifier_from_str() { 101 | assert_eq!( 102 | RustIdentifier::from_str("foo"), 103 | RustIdentifier::Identifier("foo".to_string()) 104 | ); 105 | assert_eq!( 106 | RustIdentifier::from_str("crate"), 107 | RustIdentifier::KeywordUnderscorePostfix("crate_".to_string()) 108 | ); 109 | assert_eq!( 110 | RustIdentifier::from_str("match"), 111 | RustIdentifier::KeywordRawSafe("r#match".to_string()) 112 | ); 113 | assert_eq!( 114 | RustIdentifier::from_str("föo"), 115 | RustIdentifier::NonIdentifier("föo".to_string()) 116 | ); 117 | assert_eq!( 118 | RustIdentifier::from_str(""), 119 | RustIdentifier::NonIdentifier("".to_string()) 120 | ); 121 | assert_eq!( 122 | RustIdentifier::from_str("_"), 123 | RustIdentifier::NonIdentifier("_".to_string()) 124 | ); 125 | assert_eq!( 126 | RustIdentifier::from_str("_f"), 127 | RustIdentifier::Identifier("_f".to_string()) 128 | ); 129 | assert_eq!( 130 | RustIdentifier::from_str("_1"), 131 | RustIdentifier::Identifier("_1".to_string()) 132 | ); 133 | assert_eq!( 134 | RustIdentifier::from_str("1_"), 135 | RustIdentifier::Identifier("_1_".to_string()) 136 | ); 137 | assert_eq!( 138 | RustIdentifier::from_str("1"), 139 | RustIdentifier::Identifier("_1".to_string()) 140 | ); 141 | } 142 | 143 | fn is_rust_identifier(s: &str) -> bool { 144 | // https://doc.rust-lang.org/reference/identifiers.html 145 | let mut chars = s.chars(); 146 | 147 | // First char 148 | let first_char = if let Some(ch) = chars.next() { ch } else { return false }; 149 | match first_char { 150 | 'a'..='z' => {} 151 | 'A'..='Z' => {} 152 | '_' => { 153 | if s == "_" { 154 | return false; 155 | } 156 | } 157 | _ => return false, 158 | } 159 | 160 | // Subsequent chars 161 | for ch in chars { 162 | match ch { 163 | 'a'..='z' => {} 164 | 'A'..='Z' => {} 165 | '0'..='9' => {} 166 | '_' => {} 167 | _ => return false, 168 | } 169 | } 170 | 171 | true 172 | } 173 | 174 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] 175 | pub enum IdentifierManglingError { 176 | NotApplicable(&'static str), 177 | EmptyString, 178 | NotRustSafe, 179 | UnexpectedCharacter(char), 180 | } 181 | 182 | impl std::error::Error for IdentifierManglingError {} 183 | impl std::fmt::Display for IdentifierManglingError { 184 | fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { 185 | std::fmt::Debug::fmt(self, fmt) 186 | } 187 | } 188 | 189 | pub fn javaify_identifier(name: &str) -> Result { 190 | if name == "_" { 191 | Ok(String::from("__")) 192 | } else { 193 | let mut chars = name.chars(); 194 | 195 | // First character 196 | if let Some(ch) = chars.next() { 197 | match ch { 198 | 'a'..='z' => {} 199 | 'A'..='Z' => {} 200 | '_' => {} 201 | _ => { 202 | return Err(IdentifierManglingError::UnexpectedCharacter(ch)); 203 | } 204 | } 205 | } 206 | 207 | // Subsequent characters 208 | for ch in chars { 209 | match ch { 210 | 'a'..='z' => {} 211 | 'A'..='Z' => {} 212 | '0'..='9' => {} 213 | '_' => {} 214 | _ => { 215 | return Err(IdentifierManglingError::UnexpectedCharacter(ch)); 216 | } 217 | } 218 | } 219 | 220 | match RustIdentifier::from_str(name) { 221 | RustIdentifier::Identifier(_) => Ok(name.to_owned()), 222 | RustIdentifier::NonIdentifier(_) => Err(IdentifierManglingError::NotRustSafe), 223 | RustIdentifier::KeywordRawSafe(s) => Ok(s.to_owned()), 224 | RustIdentifier::KeywordUnderscorePostfix(s) => Ok(s.to_owned()), 225 | } 226 | } 227 | } 228 | 229 | pub fn rustify_identifier(name: &str) -> Result { 230 | if name == "_" { 231 | Ok(String::from("__")) 232 | } else { 233 | let mut chars = name.chars(); 234 | let mut buffer = String::new(); 235 | let mut uppercase = 0; 236 | 237 | // First character 238 | if let Some(ch) = chars.next() { 239 | match ch { 240 | 'a'..='z' => buffer.push(ch), 241 | 'A'..='Z' => { 242 | buffer.push(ch.to_ascii_lowercase()); 243 | uppercase = 1; 244 | } 245 | '_' => buffer.push(ch), 246 | _ => { 247 | return Err(IdentifierManglingError::UnexpectedCharacter(ch)); 248 | } 249 | } 250 | } 251 | 252 | // Subsequent characters 253 | for ch in chars { 254 | if ch.is_ascii_uppercase() { 255 | if uppercase == 0 && !buffer.ends_with('_') { 256 | buffer.push('_'); 257 | } 258 | buffer.push(ch.to_ascii_lowercase()); 259 | uppercase += 1; 260 | } else if ch.is_ascii_alphanumeric() { 261 | if uppercase > 1 { 262 | buffer.insert(buffer.len() - 1, '_'); 263 | } 264 | buffer.push(ch); 265 | uppercase = 0; 266 | } else if ch == '_' { 267 | buffer.push(ch); 268 | uppercase = 0; 269 | } else { 270 | return Err(IdentifierManglingError::UnexpectedCharacter(ch)); 271 | } 272 | } 273 | 274 | match RustIdentifier::from_str(&buffer) { 275 | RustIdentifier::Identifier(_) => Ok(buffer), 276 | RustIdentifier::NonIdentifier(_) => Err(IdentifierManglingError::NotRustSafe), 277 | RustIdentifier::KeywordRawSafe(s) => Ok(s.to_owned()), 278 | RustIdentifier::KeywordUnderscorePostfix(s) => Ok(s.to_owned()), 279 | } 280 | } 281 | } 282 | 283 | pub fn constify_identifier(name: &str) -> Result { 284 | if name == "_" { 285 | Ok(String::from("__")) 286 | } else { 287 | let mut chars = name.chars(); 288 | let mut buffer = String::new(); 289 | let mut uppercase = 0; 290 | let mut lowercase = 0; 291 | 292 | // First character 293 | if let Some(ch) = chars.next() { 294 | match ch { 295 | 'a'..='z' => { 296 | buffer.push(ch.to_ascii_uppercase()); 297 | lowercase = 1; 298 | } 299 | 'A'..='Z' => { 300 | buffer.push(ch); 301 | uppercase = 1; 302 | } 303 | '_' => buffer.push(ch), 304 | _ => { 305 | return Err(IdentifierManglingError::UnexpectedCharacter(ch)); 306 | } 307 | } 308 | } 309 | 310 | // Subsequent characters 311 | for ch in chars { 312 | let is_upper = ch.is_ascii_uppercase(); 313 | let is_lower = ch.is_ascii_lowercase(); 314 | let is_numeric = ch.is_numeric(); 315 | 316 | if is_lower && uppercase > 1 { 317 | buffer.insert(buffer.len() - 1, '_'); 318 | } else if is_upper && lowercase > 0 { 319 | buffer.push('_'); 320 | } 321 | 322 | uppercase = if is_upper { uppercase + 1 } else { 0 }; 323 | lowercase = if is_lower { lowercase + 1 } else { 0 }; 324 | 325 | if is_lower { 326 | buffer.push(ch.to_ascii_uppercase()); 327 | } else if is_upper || is_numeric || ch == '_' { 328 | buffer.push(ch); 329 | } else { 330 | return Err(IdentifierManglingError::UnexpectedCharacter(ch)); 331 | } 332 | } 333 | 334 | match RustIdentifier::from_str(&buffer) { 335 | RustIdentifier::Identifier(_) => Ok(buffer), 336 | RustIdentifier::NonIdentifier(_) => Err(IdentifierManglingError::NotRustSafe), 337 | RustIdentifier::KeywordRawSafe(s) => Ok(s.to_owned()), 338 | RustIdentifier::KeywordUnderscorePostfix(s) => Ok(s.to_owned()), 339 | } 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/main.rs: -------------------------------------------------------------------------------- 1 | // this must go first because of macros. 2 | mod util; 3 | 4 | mod config; 5 | mod emit_rust; 6 | mod identifiers; 7 | mod parser_util; 8 | mod run; 9 | 10 | fn main() { 11 | entry::main(); 12 | } 13 | 14 | mod entry { 15 | use std::path::PathBuf; 16 | 17 | use clap::{Parser, Subcommand}; 18 | 19 | use crate::config; 20 | use crate::run::run; 21 | 22 | /// Autogenerate glue code for access Android JVM APIs from Rust 23 | #[derive(Parser, Debug)] 24 | #[command(version, about)] 25 | struct Cli { 26 | #[command(subcommand)] 27 | cmd: Cmd, 28 | } 29 | 30 | /// Doc comment 31 | #[derive(Subcommand, Debug)] 32 | enum Cmd { 33 | Generate(GenerateCmd), 34 | } 35 | 36 | #[derive(Parser, Debug)] 37 | struct GenerateCmd { 38 | /// Log in more detail 39 | #[arg(short, long)] 40 | verbose: bool, 41 | 42 | /// Sets a custom directory 43 | #[arg(short, long, default_value = ".")] 44 | directory: PathBuf, 45 | } 46 | 47 | pub fn main() { 48 | let cli = Cli::parse(); 49 | 50 | match cli.cmd { 51 | Cmd::Generate(cmd) => { 52 | let config_file = config::toml::File::from_directory(&cmd.directory).unwrap(); 53 | let mut config: config::runtime::Config = config_file.into(); 54 | if cmd.verbose { 55 | config.logging_verbose = true; 56 | } 57 | run(config).unwrap(); 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/parser_util/class.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::marker::PhantomPinned; 3 | use std::pin::Pin; 4 | 5 | pub use cafebabe::ClassAccessFlags; 6 | use cafebabe::attributes::AttributeData; 7 | 8 | use super::Id; 9 | 10 | #[derive(Debug)] 11 | pub struct JavaClass { 12 | #[allow(unused)] 13 | raw_bytes: Pin, PhantomPinned)>>, 14 | inner: cafebabe::ClassFile<'static>, 15 | } 16 | 17 | impl JavaClass { 18 | pub fn read(raw_bytes: Vec) -> Result { 19 | let pinned = Box::pin((raw_bytes, PhantomPinned)); 20 | // SAFETY: `get<'a>(&'a self)` restricts the lifetime parameter of 21 | // the returned referenced `ClassFile`. 22 | let fake_static = unsafe { std::slice::from_raw_parts(pinned.0.as_ptr(), pinned.0.len()) }; 23 | let inner = cafebabe::parse_class(fake_static)?; 24 | Ok(Self { 25 | raw_bytes: pinned, 26 | inner, 27 | }) 28 | } 29 | 30 | // It is probably not possible to implement `Deref` safely. 31 | pub fn get<'a>(&'a self) -> &'a cafebabe::ClassFile<'a> { 32 | // SAFETY: casts `self.inner` into `cafebabe::ClassFile<'a>` forcefully. 33 | // `cafebabe::parse_class` takes immutable &'a [u8], why is the returned 34 | // `ClassFile<'a>` invariant over `'a`? 35 | unsafe { &*(&raw const (self.inner)).cast() } 36 | } 37 | 38 | fn flags(&self) -> ClassAccessFlags { 39 | self.get().access_flags 40 | } 41 | 42 | pub fn is_public(&self) -> bool { 43 | self.flags().contains(ClassAccessFlags::PUBLIC) 44 | } 45 | pub fn is_final(&self) -> bool { 46 | self.flags().contains(ClassAccessFlags::FINAL) 47 | } 48 | pub fn is_static(&self) -> bool { 49 | (self.flags().bits() & 0x0008) != 0 50 | } 51 | #[allow(unused)] 52 | pub fn is_super(&self) -> bool { 53 | self.flags().contains(ClassAccessFlags::SUPER) 54 | } 55 | pub fn is_interface(&self) -> bool { 56 | self.flags().contains(ClassAccessFlags::INTERFACE) 57 | } 58 | #[allow(unused)] 59 | pub fn is_abstract(&self) -> bool { 60 | self.flags().contains(ClassAccessFlags::ABSTRACT) 61 | } 62 | #[allow(unused)] 63 | pub fn is_synthetic(&self) -> bool { 64 | self.flags().contains(ClassAccessFlags::SYNTHETIC) 65 | } 66 | #[allow(unused)] 67 | pub fn is_annotation(&self) -> bool { 68 | self.flags().contains(ClassAccessFlags::ANNOTATION) 69 | } 70 | pub fn is_enum(&self) -> bool { 71 | self.flags().contains(ClassAccessFlags::ENUM) 72 | } 73 | 74 | pub fn path(&self) -> Id<'_> { 75 | Id(self.get().this_class.as_ref()) 76 | } 77 | 78 | pub fn super_path(&self) -> Option> { 79 | self.get().super_class.as_ref().map(|class| Id(class)) 80 | } 81 | 82 | pub fn interfaces(&self) -> std::slice::Iter<'_, Cow<'_, str>> { 83 | self.get().interfaces.iter() 84 | } 85 | 86 | pub fn fields(&self) -> std::slice::Iter<'_, cafebabe::FieldInfo<'_>> { 87 | self.get().fields.iter() 88 | } 89 | 90 | pub fn methods(&self) -> std::slice::Iter<'_, cafebabe::MethodInfo<'_>> { 91 | self.get().methods.iter() 92 | } 93 | 94 | pub fn deprecated(&self) -> bool { 95 | self.get() 96 | .attributes 97 | .iter() 98 | .any(|attr| matches!(attr.data, AttributeData::Deprecated)) 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/parser_util/field.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Write; 2 | 3 | use cafebabe::FieldAccessFlags; 4 | use cafebabe::attributes::AttributeData; 5 | use cafebabe::constant_pool::LiteralConstant; 6 | use cafebabe::descriptors::{FieldDescriptor, FieldType}; 7 | 8 | use super::ClassName; 9 | 10 | #[derive(Clone, Copy, Debug)] 11 | pub struct JavaField<'a> { 12 | java: &'a cafebabe::FieldInfo<'a>, 13 | } 14 | 15 | impl<'a> From<&'a cafebabe::FieldInfo<'a>> for JavaField<'a> { 16 | fn from(value: &'a cafebabe::FieldInfo<'a>) -> Self { 17 | Self { java: value } 18 | } 19 | } 20 | 21 | impl<'a> std::ops::Deref for JavaField<'a> { 22 | type Target = cafebabe::FieldInfo<'a>; 23 | fn deref(&self) -> &Self::Target { 24 | self.java 25 | } 26 | } 27 | 28 | impl<'a> JavaField<'a> { 29 | pub fn name<'s>(&'s self) -> &'a str { 30 | self.java.name.as_ref() 31 | } 32 | 33 | pub fn is_public(&self) -> bool { 34 | self.access_flags.contains(FieldAccessFlags::PUBLIC) 35 | } 36 | pub fn is_private(&self) -> bool { 37 | self.access_flags.contains(FieldAccessFlags::PRIVATE) 38 | } 39 | pub fn is_protected(&self) -> bool { 40 | self.access_flags.contains(FieldAccessFlags::PROTECTED) 41 | } 42 | pub fn is_static(&self) -> bool { 43 | self.access_flags.contains(FieldAccessFlags::STATIC) 44 | } 45 | pub fn is_final(&self) -> bool { 46 | self.access_flags.contains(FieldAccessFlags::FINAL) 47 | } 48 | pub fn is_volatile(&self) -> bool { 49 | self.access_flags.contains(FieldAccessFlags::VOLATILE) 50 | } 51 | #[allow(unused)] 52 | pub fn is_transient(&self) -> bool { 53 | self.access_flags.contains(FieldAccessFlags::TRANSIENT) 54 | } 55 | #[allow(unused)] 56 | pub fn is_synthetic(&self) -> bool { 57 | self.access_flags.contains(FieldAccessFlags::SYNTHETIC) 58 | } 59 | #[allow(unused)] 60 | pub fn is_enum(&self) -> bool { 61 | self.access_flags.contains(FieldAccessFlags::ENUM) 62 | } 63 | 64 | pub fn access(&self) -> Option<&'static str> { 65 | if self.is_private() { 66 | Some("private") 67 | } else if self.is_protected() { 68 | Some("protected") 69 | } else if self.is_public() { 70 | Some("public") 71 | } else { 72 | None 73 | } 74 | } 75 | 76 | pub fn constant<'s>(&'s self) -> Option> { 77 | if !self.is_static() || !self.is_final() { 78 | return None; 79 | } 80 | self.attributes.iter().find_map(|attr| { 81 | if let AttributeData::ConstantValue(c) = &attr.data { 82 | Some(c.clone()) 83 | } else { 84 | None 85 | } 86 | }) 87 | } 88 | 89 | pub fn deprecated(&self) -> bool { 90 | self.attributes 91 | .iter() 92 | .any(|attr| matches!(attr.data, AttributeData::Deprecated)) 93 | } 94 | 95 | pub fn descriptor<'s>(&'s self) -> &'a FieldDescriptor<'a> { 96 | &self.java.descriptor 97 | } 98 | } 99 | 100 | pub fn emit_field_descriptor(descriptor: &FieldDescriptor) -> String { 101 | let mut res = String::new(); 102 | for _ in 0..descriptor.dimensions { 103 | res.push('['); 104 | } 105 | if let FieldType::Object(class_name) = &descriptor.field_type { 106 | res.push('L'); 107 | write!(&mut res, "{}", ClassName::from(class_name)).unwrap(); 108 | res.push(';'); 109 | } else { 110 | let ch = match descriptor.field_type { 111 | FieldType::Boolean => 'Z', 112 | FieldType::Byte => 'B', 113 | FieldType::Char => 'C', 114 | FieldType::Short => 'S', 115 | FieldType::Integer => 'I', 116 | FieldType::Long => 'J', 117 | FieldType::Float => 'F', 118 | FieldType::Double => 'D', 119 | _ => unreachable!(), 120 | }; 121 | res.push(ch) 122 | } 123 | res 124 | } 125 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/parser_util/id.rs: -------------------------------------------------------------------------------- 1 | // Migrated from . 2 | 3 | use std::fmt::Write; 4 | 5 | /// Owned Java class binary name (internal form). 6 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 7 | pub struct IdBuf(String); 8 | 9 | impl IdBuf { 10 | pub fn new(s: String) -> Self { 11 | Self(s) 12 | } 13 | pub fn as_str(&self) -> &str { 14 | self.0.as_str() 15 | } 16 | pub fn as_id(&self) -> Id { 17 | Id(self.0.as_str()) 18 | } 19 | #[allow(dead_code)] 20 | pub fn iter(&self) -> IdIter { 21 | IdIter::new(self.0.as_str()) 22 | } 23 | } 24 | 25 | // XXX: This should really be `#[repr(transparent)] pub struct Id(str);`... 26 | // Also, patterns apparently can't handle Id::new(...) even when it's a const fn. 27 | 28 | /// Borrowed Java class binary name (internal form). 29 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 30 | pub struct Id<'a>(pub &'a str); 31 | 32 | impl<'a> Id<'a> { 33 | pub fn as_str(&self) -> &'a str { 34 | self.0 35 | } 36 | pub fn iter(&self) -> IdIter<'a> { 37 | IdIter::new(self.0) 38 | } 39 | } 40 | 41 | impl<'a> IntoIterator for Id<'a> { 42 | type Item = IdPart<'a>; 43 | type IntoIter = IdIter<'a>; 44 | fn into_iter(self) -> Self::IntoIter { 45 | self.iter() 46 | } 47 | } 48 | 49 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 50 | pub enum IdPart<'a> { 51 | Namespace(&'a str), 52 | ContainingClass(&'a str), 53 | LeafClass(&'a str), 54 | } 55 | 56 | /// Iterates through names of namespaces, superclasses and the "leaf" class 57 | /// in the Java class binary name. 58 | pub struct IdIter<'a> { 59 | rest: &'a str, 60 | } 61 | 62 | impl<'a> IdIter<'a> { 63 | pub fn new(path: &'a str) -> Self { 64 | IdIter { rest: path } 65 | } 66 | } 67 | 68 | impl<'a> Iterator for IdIter<'a> { 69 | type Item = IdPart<'a>; 70 | fn next(&mut self) -> Option { 71 | if let Some(slash) = self.rest.find('/') { 72 | let (namespace, rest) = self.rest.split_at(slash); 73 | self.rest = &rest[1..]; 74 | return Some(IdPart::Namespace(namespace)); 75 | } 76 | 77 | if let Some(dollar) = self.rest.find('$') { 78 | let (class, rest) = self.rest.split_at(dollar); 79 | self.rest = &rest[1..]; 80 | return Some(IdPart::ContainingClass(class)); 81 | } 82 | 83 | if !self.rest.is_empty() { 84 | let class = self.rest; 85 | self.rest = ""; 86 | return Some(IdPart::LeafClass(class)); 87 | } 88 | 89 | None 90 | } 91 | } 92 | 93 | #[test] 94 | fn id_iter_test() { 95 | assert_eq!(Id("").iter().collect::>(), &[]); 96 | 97 | assert_eq!(Id("Bar").iter().collect::>(), &[IdPart::LeafClass("Bar"),]); 98 | 99 | assert_eq!( 100 | Id("java/foo/Bar").iter().collect::>(), 101 | &[ 102 | IdPart::Namespace("java"), 103 | IdPart::Namespace("foo"), 104 | IdPart::LeafClass("Bar"), 105 | ] 106 | ); 107 | 108 | assert_eq!( 109 | Id("java/foo/Bar$Inner").iter().collect::>(), 110 | &[ 111 | IdPart::Namespace("java"), 112 | IdPart::Namespace("foo"), 113 | IdPart::ContainingClass("Bar"), 114 | IdPart::LeafClass("Inner"), 115 | ] 116 | ); 117 | 118 | assert_eq!( 119 | Id("java/foo/Bar$Inner$MoreInner").iter().collect::>(), 120 | &[ 121 | IdPart::Namespace("java"), 122 | IdPart::Namespace("foo"), 123 | IdPart::ContainingClass("Bar"), 124 | IdPart::ContainingClass("Inner"), 125 | IdPart::LeafClass("MoreInner"), 126 | ] 127 | ); 128 | } 129 | 130 | /// Newtype for `cafebabe::descriptors::ClassName`. 131 | /// 132 | /// XXX: cannot get the original string from `cafebabe::descriptors::ClassName`; the binary 133 | /// name is split into `UnqualifiedSegment`s, not caring about Java-specific nested classes. 134 | /// See . 135 | #[derive(Clone, Copy, Debug)] 136 | pub struct ClassName<'a> { 137 | inner: &'a cafebabe::descriptors::ClassName<'a>, 138 | } 139 | 140 | impl<'a> From<&'a cafebabe::descriptors::ClassName<'a>> for ClassName<'a> { 141 | fn from(value: &'a cafebabe::descriptors::ClassName<'a>) -> Self { 142 | Self { inner: value } 143 | } 144 | } 145 | 146 | impl<'a> std::ops::Deref for ClassName<'a> { 147 | type Target = cafebabe::descriptors::ClassName<'a>; 148 | fn deref(&self) -> &Self::Target { 149 | self.inner 150 | } 151 | } 152 | 153 | impl std::fmt::Display for ClassName<'_> { 154 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 155 | let mut segs = self.segments.iter(); 156 | f.write_str(segs.next().unwrap().name.as_ref())?; 157 | for seg in segs { 158 | f.write_char('/')?; 159 | f.write_str(seg.name.as_ref())?; 160 | } 161 | Ok(()) 162 | } 163 | } 164 | 165 | impl<'a> From<&ClassName<'a>> for IdBuf { 166 | fn from(value: &ClassName<'a>) -> Self { 167 | Self::new(value.to_string()) 168 | } 169 | } 170 | 171 | impl<'a> From<&cafebabe::descriptors::ClassName<'a>> for IdBuf { 172 | fn from(value: &cafebabe::descriptors::ClassName<'a>) -> Self { 173 | Self::new(ClassName::from(value).to_string()) 174 | } 175 | } 176 | 177 | impl<'a> ClassName<'a> { 178 | pub fn iter<'s>(&'s self) -> ClassNameIter<'a> { 179 | let segments = &self.inner.segments; 180 | if segments.len() > 1 { 181 | ClassNameIter::RestPath(segments) 182 | } else { 183 | let classes = segments.last().map(|s| s.name.as_ref()).unwrap_or(""); 184 | ClassNameIter::RestClasses(IdIter::new(classes)) 185 | } 186 | } 187 | } 188 | 189 | impl<'a> IntoIterator for ClassName<'a> { 190 | type Item = IdPart<'a>; 191 | type IntoIter = ClassNameIter<'a>; 192 | fn into_iter(self) -> Self::IntoIter { 193 | self.iter() 194 | } 195 | } 196 | 197 | pub enum ClassNameIter<'a> { 198 | RestPath(&'a [cafebabe::descriptors::UnqualifiedSegment<'a>]), 199 | RestClasses(IdIter<'a>), 200 | } 201 | 202 | impl<'a> Iterator for ClassNameIter<'a> { 203 | type Item = IdPart<'a>; 204 | fn next(&mut self) -> Option { 205 | match self { 206 | Self::RestPath(segments) => { 207 | // `segments.len() > 1` must be true at here 208 | let namespace = IdPart::Namespace(&segments[0].name); 209 | *self = if segments.len() - 1 > 1 { 210 | Self::RestPath(&segments[1..]) 211 | } else { 212 | Self::RestClasses(IdIter::new(&segments.last().unwrap().name)) 213 | }; 214 | Some(namespace) 215 | } 216 | Self::RestClasses(id_iter) => id_iter.next(), 217 | } 218 | } 219 | } 220 | 221 | #[allow(unused)] 222 | pub trait IterableId<'a>: IntoIterator> + Copy { 223 | fn is_string_class(self) -> bool { 224 | let mut iter = self.into_iter(); 225 | iter.next() == Some(IdPart::Namespace("java")) 226 | && iter.next() == Some(IdPart::Namespace("lang")) 227 | && iter.next() == Some(IdPart::LeafClass("String")) 228 | && iter.next().is_none() 229 | } 230 | } 231 | 232 | impl<'a> IterableId<'a> for Id<'a> {} 233 | impl<'a> IterableId<'a> for ClassName<'a> {} 234 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/parser_util/method.rs: -------------------------------------------------------------------------------- 1 | use cafebabe::MethodAccessFlags; 2 | use cafebabe::attributes::AttributeData; 3 | use cafebabe::descriptors::{MethodDescriptor, ReturnDescriptor}; 4 | 5 | use super::emit_field_descriptor; 6 | 7 | pub struct JavaMethod<'a> { 8 | java: &'a cafebabe::MethodInfo<'a>, 9 | } 10 | 11 | impl<'a> From<&'a cafebabe::MethodInfo<'a>> for JavaMethod<'a> { 12 | fn from(value: &'a cafebabe::MethodInfo<'a>) -> Self { 13 | Self { java: value } 14 | } 15 | } 16 | 17 | impl<'a> std::ops::Deref for JavaMethod<'a> { 18 | type Target = cafebabe::MethodInfo<'a>; 19 | fn deref(&self) -> &Self::Target { 20 | self.java 21 | } 22 | } 23 | 24 | impl<'a> JavaMethod<'a> { 25 | pub fn name<'s>(&'s self) -> &'a str { 26 | self.java.name.as_ref() 27 | } 28 | 29 | pub fn is_public(&self) -> bool { 30 | self.access_flags.contains(MethodAccessFlags::PUBLIC) 31 | } 32 | #[allow(unused)] 33 | pub fn is_private(&self) -> bool { 34 | self.access_flags.contains(MethodAccessFlags::PRIVATE) 35 | } 36 | #[allow(unused)] 37 | pub fn is_protected(&self) -> bool { 38 | self.access_flags.contains(MethodAccessFlags::PROTECTED) 39 | } 40 | pub fn is_static(&self) -> bool { 41 | self.access_flags.contains(MethodAccessFlags::STATIC) 42 | } 43 | #[allow(unused)] 44 | pub fn is_final(&self) -> bool { 45 | self.access_flags.contains(MethodAccessFlags::FINAL) 46 | } 47 | #[allow(unused)] 48 | pub fn is_synchronized(&self) -> bool { 49 | self.access_flags.contains(MethodAccessFlags::SYNCHRONIZED) 50 | } 51 | pub fn is_bridge(&self) -> bool { 52 | self.access_flags.contains(MethodAccessFlags::BRIDGE) 53 | } 54 | pub fn is_varargs(&self) -> bool { 55 | self.access_flags.contains(MethodAccessFlags::VARARGS) 56 | } 57 | #[allow(unused)] 58 | pub fn is_native(&self) -> bool { 59 | self.access_flags.contains(MethodAccessFlags::NATIVE) 60 | } 61 | #[allow(unused)] 62 | pub fn is_abstract(&self) -> bool { 63 | self.access_flags.contains(MethodAccessFlags::ABSTRACT) 64 | } 65 | #[allow(unused)] 66 | pub fn is_strict(&self) -> bool { 67 | self.access_flags.contains(MethodAccessFlags::STRICT) 68 | } 69 | #[allow(unused)] 70 | pub fn is_synthetic(&self) -> bool { 71 | self.access_flags.contains(MethodAccessFlags::SYNTHETIC) 72 | } 73 | 74 | pub fn is_constructor(&self) -> bool { 75 | self.name() == "" 76 | } 77 | pub fn is_static_init(&self) -> bool { 78 | self.name() == "" 79 | } 80 | 81 | #[allow(unused)] 82 | pub fn access(&self) -> Option<&'static str> { 83 | if self.is_private() { 84 | Some("private") 85 | } else if self.is_protected() { 86 | Some("protected") 87 | } else if self.is_public() { 88 | Some("public") 89 | } else { 90 | None 91 | } 92 | } 93 | 94 | pub fn deprecated(&self) -> bool { 95 | self.attributes 96 | .iter() 97 | .any(|attr| matches!(attr.data, AttributeData::Deprecated)) 98 | } 99 | 100 | pub fn descriptor<'s>(&'s self) -> &'a MethodDescriptor<'a> { 101 | &self.java.descriptor 102 | } 103 | } 104 | 105 | pub fn emit_method_descriptor(descriptor: &MethodDescriptor) -> String { 106 | let mut res = String::new(); 107 | res.push('('); 108 | for arg in descriptor.parameters.iter() { 109 | res.push_str(&emit_field_descriptor(arg)) 110 | } 111 | res.push(')'); 112 | if let ReturnDescriptor::Return(desc) = &descriptor.return_type { 113 | res.push_str(&emit_field_descriptor(desc)) 114 | } else { 115 | res.push('V') 116 | } 117 | res 118 | } 119 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/parser_util/mod.rs: -------------------------------------------------------------------------------- 1 | mod class; 2 | mod field; 3 | mod id; 4 | mod method; 5 | 6 | pub use class::JavaClass; 7 | pub use field::{JavaField, emit_field_descriptor}; 8 | pub use id::*; 9 | pub use method::{JavaMethod, emit_method_descriptor}; 10 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/run/mod.rs: -------------------------------------------------------------------------------- 1 | //! Core generation logic 2 | 3 | mod run; 4 | 5 | pub use run::run; 6 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/run/run.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::fs::File; 3 | use std::io::{self, Read}; 4 | use std::path::Path; 5 | 6 | use crate::config::runtime::Config; 7 | use crate::parser_util::JavaClass; 8 | use crate::{emit_rust, util}; 9 | 10 | /// The core function of this library: Generate Rust code to access Java APIs. 11 | pub fn run(config: impl Into) -> Result<(), Box> { 12 | let config: Config = config.into(); 13 | println!("output: {}", config.output_path.display()); 14 | 15 | let mut context = emit_rust::Context::new(&config); 16 | for file in config.input_files.iter() { 17 | gather_file(&mut context, file)?; 18 | } 19 | 20 | { 21 | let mut out = Vec::with_capacity(4096); 22 | context.write(&mut out)?; 23 | util::write_generated(&context, &config.output_path, &out[..])?; 24 | } 25 | 26 | Ok(()) 27 | } 28 | 29 | fn gather_file(context: &mut emit_rust::Context, path: &Path) -> Result<(), Box> { 30 | let verbose = context.config.logging_verbose; 31 | 32 | context 33 | .progress 34 | .lock() 35 | .unwrap() 36 | .update(format!("reading {}...", path.display()).as_str()); 37 | 38 | let ext = if let Some(ext) = path.extension() { 39 | ext 40 | } else { 41 | return Err(io::Error::new( 42 | io::ErrorKind::InvalidInput, 43 | "Input files must have an extension", 44 | ))?; 45 | }; 46 | 47 | match ext.to_string_lossy().to_ascii_lowercase().as_str() { 48 | "class" => { 49 | let class = JavaClass::read(std::fs::read(path)?)?; 50 | context.add_class(class)?; 51 | } 52 | "jar" => { 53 | let mut jar = zip::ZipArchive::new(io::BufReader::new(File::open(path)?))?; 54 | let n = jar.len(); 55 | 56 | for i in 0..n { 57 | let mut file = jar.by_index(i)?; 58 | if !file.name().ends_with(".class") { 59 | continue; 60 | } 61 | 62 | if verbose { 63 | context 64 | .progress 65 | .lock() 66 | .unwrap() 67 | .update(format!(" reading {:3}/{}: {}...", i, n, file.name()).as_str()); 68 | } 69 | 70 | let mut buf = Vec::new(); 71 | file.read_to_end(&mut buf)?; 72 | let class = JavaClass::read(buf)?; 73 | context.add_class(class)?; 74 | } 75 | } 76 | unknown => { 77 | Err(io::Error::new( 78 | io::ErrorKind::InvalidInput, 79 | format!( 80 | "Input files must have a '.class' or '.jar' extension, not a '.{}' extension", 81 | unknown 82 | ), 83 | ))?; 84 | } 85 | } 86 | Ok(()) 87 | } 88 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/util/difference.rs: -------------------------------------------------------------------------------- 1 | use std::io::{self, *}; 2 | 3 | pub struct Difference { 4 | // XXX: should they exist here? 5 | #[allow(unused)] 6 | pub line_no: u32, 7 | #[allow(unused)] 8 | pub original: String, 9 | #[allow(unused)] 10 | pub rewrite: String, 11 | } 12 | 13 | impl Difference { 14 | /// **WARNING**: leaves self in an inconsistent state on Err. 15 | pub fn find( 16 | original: &mut (impl BufRead + Seek), 17 | rewrite: &mut (impl BufRead + Seek), 18 | ) -> io::Result> { 19 | original.seek(SeekFrom::Start(0))?; 20 | rewrite.seek(SeekFrom::Start(0))?; 21 | 22 | let mut original_line = String::new(); 23 | let mut rewrite_line = String::new(); 24 | 25 | let mut line_no = 0; 26 | loop { 27 | line_no += 1; 28 | 29 | let a = read_line_no_eol(original, &mut original_line)?; 30 | let b = read_line_no_eol(rewrite, &mut rewrite_line)?; 31 | 32 | if a == 0 && b == 0 { 33 | return Ok(None); 34 | } 35 | 36 | if original_line != rewrite_line { 37 | original.seek(SeekFrom::End(0))?; 38 | rewrite.seek(SeekFrom::End(0))?; 39 | return Ok(Some(Difference { 40 | line_no, 41 | original: original_line, 42 | rewrite: rewrite_line, 43 | })); 44 | } 45 | } 46 | } 47 | } 48 | 49 | fn read_line_no_eol(reader: &mut impl BufRead, buffer: &mut String) -> io::Result { 50 | let size = reader.read_line(buffer)?; 51 | while buffer.ends_with('\r') || buffer.ends_with('\n') { 52 | buffer.pop(); 53 | } 54 | Ok(size) 55 | } 56 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/util/generated_file.rs: -------------------------------------------------------------------------------- 1 | use std::fs::{self, *}; 2 | use std::io::{self, BufRead, BufReader, Cursor, ErrorKind}; 3 | use std::path::Path; 4 | 5 | use super::Difference; 6 | use crate::emit_rust; 7 | 8 | const MARKER_COMMENT: &str = 9 | "WARNING: This file was autogenerated by java-spaghetti. Any changes to this file may be lost!!!"; 10 | 11 | pub fn write_generated(context: &emit_rust::Context, path: &impl AsRef, contents: &[u8]) -> io::Result<()> { 12 | let path = path.as_ref(); 13 | let dir = path 14 | .parent() 15 | .ok_or_else(|| io_data_error!("{:?} has no parent directory", path))?; 16 | let _ = create_dir_all(dir); 17 | 18 | match File::open(path) { 19 | Ok(file) => { 20 | let mut original = BufReader::new(file); 21 | let mut first_line = String::new(); 22 | read_line_no_eol(&mut original, &mut first_line)?; 23 | 24 | let mut found_marker = false; 25 | for prefix in &["// ", "# "] { 26 | if first_line.starts_with(prefix) && (&first_line[prefix.len()..] == MARKER_COMMENT) { 27 | found_marker = true; 28 | break; 29 | } 30 | } 31 | 32 | if !found_marker { 33 | return io_data_err!( 34 | "Cannot overwrite {:?}: File exists, and first line {:?} doesn't match expected MARKER_COMMENT {:?}", 35 | path, 36 | first_line, 37 | MARKER_COMMENT 38 | ); 39 | } 40 | 41 | let difference = Difference::find(&mut original, &mut Cursor::new(contents))?; 42 | match difference { 43 | None => { 44 | context 45 | .progress 46 | .lock() 47 | .unwrap() 48 | .update(format!("unchanged: {}...", path.display()).as_str()); 49 | return Ok(()); 50 | } 51 | Some(_difference) => { 52 | context 53 | .progress 54 | .lock() 55 | .unwrap() 56 | .force_update(format!("MODIFIED: {}", path.display()).as_str()); 57 | } 58 | } 59 | } 60 | Err(ref e) if e.kind() == ErrorKind::NotFound => { 61 | context 62 | .progress 63 | .lock() 64 | .unwrap() 65 | .force_update(format!("NEW: {}", path.display()).as_str()); 66 | } 67 | Err(e) => { 68 | return Err(e); 69 | } 70 | }; 71 | 72 | fs::write(path, contents) 73 | } 74 | 75 | fn read_line_no_eol(reader: &mut impl BufRead, buffer: &mut String) -> io::Result { 76 | let size = reader.read_line(buffer)?; 77 | while buffer.ends_with('\r') || buffer.ends_with('\n') { 78 | buffer.pop(); 79 | } 80 | Ok(size) 81 | } 82 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/util/mod.rs: -------------------------------------------------------------------------------- 1 | #![macro_use] 2 | 3 | macro_rules! io_data_error { 4 | ($($arg:tt)*) => {{ 5 | let message = format!($($arg)*); 6 | std::io::Error::new(std::io::ErrorKind::InvalidData, message) 7 | }}; 8 | } 9 | 10 | macro_rules! io_data_err { 11 | ($($arg:tt)*) => { Err(io_data_error!($($arg)*)) }; 12 | } 13 | 14 | mod difference; 15 | mod generated_file; 16 | mod progress; 17 | 18 | pub use difference::Difference; 19 | pub use generated_file::write_generated; 20 | pub use progress::Progress; 21 | -------------------------------------------------------------------------------- /java-spaghetti-gen/src/util/progress.rs: -------------------------------------------------------------------------------- 1 | use std::time::*; 2 | 3 | pub struct Progress { 4 | can_next_log: Instant, 5 | debounce: Duration, 6 | } 7 | 8 | impl Progress { 9 | pub fn with_duration(debounce: Duration) -> Self { 10 | Self { 11 | can_next_log: Instant::now(), 12 | debounce, 13 | } 14 | } 15 | 16 | pub fn can_update(&self) -> bool { 17 | Instant::now() >= self.can_next_log 18 | } 19 | 20 | pub fn force_update(&mut self, msg: &str) { 21 | self.can_next_log = Instant::now() + self.debounce; 22 | println!("{}", msg); 23 | } 24 | 25 | pub fn update(&mut self, msg: &str) { 26 | if !self.can_update() { 27 | return; 28 | } 29 | self.force_update(msg); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java-spaghetti/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "java-spaghetti" 3 | version = "0.2.0" 4 | edition = "2021" 5 | description = "Glue code to accompany the java-spaghetti code generator for binding to JVM APIs from Rust" 6 | documentation = "https://docs.rs/java-spaghetti/" 7 | repository = "https://github.com/Dirbaio/java-spaghetti" 8 | keywords = ["jvm", "jni", "bindgen", "android"] 9 | categories = ["external-ffi-bindings"] 10 | license = "MIT OR Apache-2.0" 11 | 12 | [dependencies] 13 | jni-sys = "0.4.0" 14 | -------------------------------------------------------------------------------- /java-spaghetti/src/array.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{CStr, CString}; 2 | use std::marker::PhantomData; 3 | use std::ops::{Bound, RangeBounds}; 4 | use std::ptr::null_mut; 5 | 6 | use jni_sys::*; 7 | 8 | use crate::{AsArg, Env, JniType, Local, Ref, ReferenceType, ThrowableType}; 9 | 10 | /// A Java Array of some POD-like type such as `bool`, `jbyte`, `jchar`, `jshort`, `jint`, `jlong`, `jfloat`, or `jdouble`. 11 | /// 12 | /// Thread safety of avoiding [race conditions](https://www.ibm.com/docs/en/sdk-java-technology/8?topic=jni-synchronization) 13 | /// is not guaranteed. JNI `GetPrimitiveArrayCritical` cannot ensure exclusive access to the array, so it is not used here. 14 | /// 15 | /// See also [ObjectArray] for arrays of reference types. 16 | /// 17 | /// | JNI Type | PrimitiveArray Implementation | 18 | /// | ------------- | ----------------- | 19 | /// | [bool]\[\] | [BooleanArray] | 20 | /// | [jbyte]\[\] | [ByteArray] | 21 | /// | [jchar]\[\] | [CharArray] | 22 | /// | [jint]\[\] | [IntArray] | 23 | /// | [jlong]\[\] | [LongArray] | 24 | /// | [jfloat]\[\] | [FloatArray] | 25 | /// | [jdouble]\[\] | [DoubleArray] | 26 | /// 27 | pub trait PrimitiveArray: Sized + ReferenceType 28 | where 29 | T: Clone + Default, 30 | { 31 | /// Uses JNI `New{Type}Array` to create a new Java array containing "size" elements. 32 | fn new<'env>(env: Env<'env>, size: usize) -> Local<'env, Self>; 33 | 34 | /// Uses JNI `GetArrayLength` to get the length of the Java array. 35 | fn len(self: &Ref<'_, Self>) -> usize; 36 | 37 | /// Uses JNI `Get{Type}ArrayRegion` to read the contents of the Java array within `[start .. start + elements.len()]`. 38 | /// 39 | /// Panics if the index is out of bound. 40 | fn get_region(self: &Ref<'_, Self>, start: usize, elements: &mut [T]); 41 | 42 | /// Uses JNI `Set{Type}ArrayRegion` to set the contents of the Java array within `[start .. start + elements.len()]`. 43 | /// 44 | /// Panics if the index is out of bound. 45 | fn set_region(self: &Ref<'_, Self>, start: usize, elements: &[T]); 46 | 47 | /// Uses JNI `New{Type}Array` + `Set{Type}ArrayRegion` to create a new Java array containing a copy of "elements". 48 | fn new_from<'env>(env: Env<'env>, elements: &[T]) -> Local<'env, Self> { 49 | let array = Self::new(env, elements.len()); 50 | array.set_region(0, elements); 51 | array 52 | } 53 | 54 | /// Uses JNI `GetArrayLength` + `Get{Type}ArrayRegion` to read the contents of the Java array within given range 55 | /// into a new `Vec`. 56 | /// 57 | /// Panics if the index is out of bound. 58 | fn get_region_as_vec(self: &Ref<'_, Self>, range: impl RangeBounds) -> Vec { 59 | let len = self.len(); 60 | 61 | let start = match range.start_bound() { 62 | Bound::Unbounded => 0, 63 | Bound::Included(n) => *n, 64 | Bound::Excluded(n) => *n + 1, 65 | }; 66 | 67 | let end = match range.end_bound() { 68 | Bound::Unbounded => len, 69 | Bound::Included(n) => *n + 1, 70 | Bound::Excluded(n) => *n, 71 | }; 72 | 73 | assert!(start <= end); 74 | assert!(end <= len); 75 | let vec_len = end - start; 76 | 77 | let mut vec = Vec::new(); 78 | vec.resize(vec_len, Default::default()); 79 | self.get_region(start, &mut vec[..]); 80 | vec 81 | } 82 | 83 | /// Uses JNI `GetArrayLength` + `Get{Type}ArrayRegion` to read the contents of the entire Java array into a new `Vec`. 84 | fn as_vec(self: &Ref<'_, Self>) -> Vec { 85 | self.get_region_as_vec(0..self.len()) 86 | } 87 | } 88 | 89 | macro_rules! primitive_array { 90 | ($name:ident, $type_str:expr, $type:ident { $new_array:ident $set_region:ident $get_region:ident } ) => { 91 | /// A [PrimitiveArray] implementation. 92 | pub enum $name {} 93 | 94 | unsafe impl ReferenceType for $name {} 95 | unsafe impl JniType for $name { 96 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 97 | callback($type_str) 98 | } 99 | } 100 | 101 | impl PrimitiveArray<$type> for $name { 102 | fn new<'env>(env: Env<'env>, size: usize) -> Local<'env, Self> { 103 | assert!(size <= std::i32::MAX as usize); // jsize == jint == i32 104 | let size = size as jsize; 105 | let jnienv = env.as_raw(); 106 | unsafe { 107 | let object = ((**jnienv).v1_2.$new_array)(jnienv, size); 108 | let exception = ((**jnienv).v1_2.ExceptionOccurred)(jnienv); 109 | assert!(exception.is_null()); // Only sane exception here is an OOM exception 110 | Local::from_raw(env, object) 111 | } 112 | } 113 | 114 | fn new_from<'env>(env: Env<'env>, elements: &[$type]) -> Local<'env, Self> { 115 | let array = Self::new(env, elements.len()); 116 | let size = elements.len() as jsize; 117 | let env = array.env().as_raw(); 118 | unsafe { 119 | ((**env).v1_1.$set_region)(env, array.as_raw(), 0, size, elements.as_ptr() as *const _); 120 | } 121 | array 122 | } 123 | 124 | fn len(self: &Ref<'_, Self>) -> usize { 125 | let env = self.env().as_raw(); 126 | unsafe { ((**env).v1_2.GetArrayLength)(env, self.as_raw()) as usize } 127 | } 128 | 129 | fn get_region(self: &Ref<'_, Self>, start: usize, elements: &mut [$type]) { 130 | assert!(start <= std::i32::MAX as usize); // jsize == jint == i32 131 | assert!(elements.len() <= std::i32::MAX as usize); // jsize == jint == i32 132 | let self_len = self.len() as jsize; 133 | let elements_len = elements.len() as jsize; 134 | 135 | let start = start as jsize; 136 | let end = start + elements_len; 137 | assert!(start <= end); 138 | assert!(end <= self_len); 139 | 140 | let env = self.env().as_raw(); 141 | unsafe { 142 | ((**env).v1_1.$get_region)( 143 | env, 144 | self.as_raw(), 145 | start, 146 | elements_len, 147 | elements.as_mut_ptr() as *mut _, 148 | ) 149 | }; 150 | } 151 | 152 | fn set_region(self: &Ref<'_, Self>, start: usize, elements: &[$type]) { 153 | assert!(start <= std::i32::MAX as usize); // jsize == jint == i32 154 | assert!(elements.len() <= std::i32::MAX as usize); // jsize == jint == i32 155 | let self_len = self.len() as jsize; 156 | let elements_len = elements.len() as jsize; 157 | 158 | let start = start as jsize; 159 | let end = start + elements_len; 160 | assert!(start <= end); 161 | assert!(end <= self_len); 162 | 163 | let env = self.env().as_raw(); 164 | unsafe { 165 | ((**env).v1_1.$set_region)( 166 | env, 167 | self.as_raw(), 168 | start, 169 | elements_len, 170 | elements.as_ptr() as *const _, 171 | ) 172 | }; 173 | } 174 | } 175 | }; 176 | } 177 | 178 | primitive_array! { BooleanArray, c"[Z", bool { NewBooleanArray SetBooleanArrayRegion GetBooleanArrayRegion } } 179 | primitive_array! { ByteArray, c"[B", jbyte { NewByteArray SetByteArrayRegion GetByteArrayRegion } } 180 | primitive_array! { CharArray, c"[C", jchar { NewCharArray SetCharArrayRegion GetCharArrayRegion } } 181 | primitive_array! { ShortArray, c"[S", jshort { NewShortArray SetShortArrayRegion GetShortArrayRegion } } 182 | primitive_array! { IntArray, c"[I", jint { NewIntArray SetIntArrayRegion GetIntArrayRegion } } 183 | primitive_array! { LongArray, c"[J", jlong { NewLongArray SetLongArrayRegion GetLongArrayRegion } } 184 | primitive_array! { FloatArray, c"[F", jfloat { NewFloatArray SetFloatArrayRegion GetFloatArrayRegion } } 185 | primitive_array! { DoubleArray, c"[D", jdouble { NewDoubleArray SetDoubleArrayRegion GetDoubleArrayRegion } } 186 | 187 | /// A Java Array of reference types (classes, interfaces, other arrays, etc.) 188 | /// 189 | /// Thread safety of avoiding [race conditions](https://www.ibm.com/docs/en/sdk-java-technology/8?topic=jni-synchronization) 190 | /// is not guaranteed. 191 | /// 192 | /// See also [PrimitiveArray] for arrays of reference types. 193 | pub struct ObjectArray(core::convert::Infallible, PhantomData<(T, E)>); 194 | 195 | unsafe impl ReferenceType for ObjectArray {} 196 | 197 | unsafe impl JniType for ObjectArray { 198 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 199 | T::static_with_jni_type(|inner| { 200 | let inner = inner.to_bytes(); 201 | let mut buf = Vec::with_capacity(inner.len() + 4); 202 | buf.extend_from_slice(b"[L"); 203 | buf.extend_from_slice(inner); 204 | buf.extend_from_slice(b";"); 205 | callback(&CString::new(buf).unwrap()) 206 | }) 207 | } 208 | } 209 | 210 | impl ObjectArray { 211 | /// Uses JNI `NewObjectArray` to create a new Java object array. 212 | pub fn new<'env>(env: Env<'env>, size: usize) -> Local<'env, Self> { 213 | assert!(size <= std::i32::MAX as usize); // jsize == jint == i32 214 | let class = T::static_with_jni_type(|t| unsafe { env.require_class(t) }); 215 | let size = size as jsize; 216 | 217 | let object = unsafe { 218 | let env = env.as_raw(); 219 | let fill = null_mut(); 220 | ((**env).v1_2.NewObjectArray)(env, size, class, fill) 221 | }; 222 | // Only sane exception here is an OOM exception 223 | env.exception_check::().map_err(|_| "OOM").unwrap(); 224 | unsafe { Local::from_raw(env, object) } 225 | } 226 | 227 | /// Iterates through object items of the array. See [ObjectArrayIter]. 228 | pub fn iter<'a, 'env>(self: &'a Ref<'env, Self>) -> ObjectArrayIter<'a, 'env, T, E> { 229 | ObjectArrayIter { 230 | array: self, 231 | index: 0, 232 | length: self.len(), 233 | } 234 | } 235 | 236 | /// Uses JNI `NewObjectArray` to create a new Java object array of the exact size, then sets its items 237 | /// with the iterator of JNI (null?) references. 238 | pub fn new_from<'env>( 239 | env: Env<'env>, 240 | elements: impl ExactSizeIterator + Iterator>, 241 | ) -> Local<'env, Self> { 242 | let size = elements.len(); 243 | let array = Self::new(env, size); 244 | let env = array.env().as_raw(); 245 | for (index, element) in elements.enumerate() { 246 | assert!(index < size); // Should only be violated by an invalid ExactSizeIterator implementation. 247 | unsafe { ((**env).v1_2.SetObjectArrayElement)(env, array.as_raw(), index as jsize, element.as_arg()) }; 248 | } 249 | array 250 | } 251 | 252 | /// Uses JNI `GetArrayLength` to get the length of the Java array. 253 | pub fn len(self: &Ref<'_, Self>) -> usize { 254 | let env = self.env().as_raw(); 255 | unsafe { ((**env).v1_2.GetArrayLength)(env, self.as_raw()) as usize } 256 | } 257 | 258 | /// Gets a local reference of the object item at given `index` in the array. 259 | /// Returns `None` if it is null; returns an exception if the index is invalid. 260 | /// 261 | /// XXX: Expose this via `std::ops::Index`. 262 | pub fn get<'env>(self: &Ref<'env, Self>, index: usize) -> Result>, Local<'env, E>> { 263 | assert!(index <= std::i32::MAX as usize); // jsize == jint == i32 XXX: Should maybe be treated as an exception? 264 | let index = index as jsize; 265 | let env = self.env(); 266 | let result = unsafe { 267 | let env = env.as_raw(); 268 | ((**env).v1_2.GetObjectArrayElement)(env, self.as_raw(), index) 269 | }; 270 | env.exception_check()?; 271 | if result.is_null() { 272 | Ok(None) 273 | } else { 274 | Ok(Some(unsafe { Local::from_raw(env, result) })) 275 | } 276 | } 277 | 278 | /// Sets an element at the given `index` in the array. Returns an exception if the index is invalid. 279 | /// 280 | /// XXX: I don't think there's a way to expose this via `std::ops::IndexMut` sadly? 281 | pub fn set<'env>(self: &Ref<'env, Self>, index: usize, value: impl AsArg) -> Result<(), Local<'env, E>> { 282 | assert!(index <= std::i32::MAX as usize); // jsize == jint == i32 XXX: Should maybe be treated as an exception? 283 | let index = index as jsize; 284 | let env = self.env(); 285 | unsafe { 286 | let env = env.as_raw(); 287 | ((**env).v1_2.SetObjectArrayElement)(env, self.as_raw(), index, value.as_arg()); 288 | } 289 | env.exception_check() 290 | } 291 | } 292 | 293 | /// An iterator over object items of an [ObjectArray]. Local references of object items 294 | /// will be created automatically. 295 | pub struct ObjectArrayIter<'a, 'env, T: ReferenceType, E: ThrowableType> { 296 | array: &'a Ref<'env, ObjectArray>, 297 | index: usize, 298 | length: usize, 299 | } 300 | 301 | impl<'a, 'env, T: ReferenceType, E: ThrowableType> Iterator for ObjectArrayIter<'a, 'env, T, E> { 302 | type Item = Option>; 303 | fn next(&mut self) -> Option { 304 | let index = self.index; 305 | if index < self.length { 306 | self.index = index + 1; 307 | Some(self.array.get(index).unwrap_or(None)) 308 | } else { 309 | None 310 | } 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /java-spaghetti/src/as_arg.rs: -------------------------------------------------------------------------------- 1 | use std::ptr::null_mut; 2 | 3 | use jni_sys::jobject; 4 | 5 | use crate::{AsJValue, AssignableTo, Global, Local, Null, Ref, ReferenceType}; 6 | 7 | /// A marker trait indicating this is a valid JNI reference type for Java method argument 8 | /// type `T`, this can be null. 9 | /// 10 | /// # Safety 11 | /// 12 | /// It should be implemented automatically by `java_spaghetti`. 13 | pub unsafe trait AsArg: Sized + AsJValue { 14 | fn as_arg(&self) -> jobject; 15 | } 16 | 17 | unsafe impl> AsArg for &U { 18 | fn as_arg(&self) -> jobject { 19 | U::as_arg(self) 20 | } 21 | } 22 | 23 | unsafe impl> AsArg for &mut U { 24 | fn as_arg(&self) -> jobject { 25 | U::as_arg(self) 26 | } 27 | } 28 | 29 | unsafe impl AsArg for Null { 30 | fn as_arg(&self) -> jobject { 31 | null_mut() 32 | } 33 | } 34 | 35 | unsafe impl> AsArg for Ref<'_, U> { 36 | fn as_arg(&self) -> jobject { 37 | self.as_raw() 38 | } 39 | } 40 | 41 | unsafe impl> AsArg for Option> { 42 | fn as_arg(&self) -> jobject { 43 | self.as_ref().map(|r| r.as_raw()).unwrap_or(null_mut()) 44 | } 45 | } 46 | 47 | unsafe impl> AsArg for Option<&Ref<'_, U>> { 48 | fn as_arg(&self) -> jobject { 49 | self.map(|r| r.as_raw()).unwrap_or(null_mut()) 50 | } 51 | } 52 | 53 | unsafe impl> AsArg for Local<'_, U> { 54 | fn as_arg(&self) -> jobject { 55 | self.as_raw() 56 | } 57 | } 58 | 59 | unsafe impl> AsArg for Option> { 60 | fn as_arg(&self) -> jobject { 61 | self.as_ref().map(|r| r.as_raw()).unwrap_or(null_mut()) 62 | } 63 | } 64 | 65 | unsafe impl> AsArg for Option<&Local<'_, U>> { 66 | fn as_arg(&self) -> jobject { 67 | self.map(|r| r.as_raw()).unwrap_or(null_mut()) 68 | } 69 | } 70 | 71 | unsafe impl> AsArg for Global { 72 | fn as_arg(&self) -> jobject { 73 | self.as_raw() 74 | } 75 | } 76 | 77 | unsafe impl> AsArg for Option> { 78 | fn as_arg(&self) -> jobject { 79 | self.as_ref().map(|r| r.as_raw()).unwrap_or(null_mut()) 80 | } 81 | } 82 | 83 | unsafe impl> AsArg for Option<&Global> { 84 | fn as_arg(&self) -> jobject { 85 | self.map(|r| r.as_raw()).unwrap_or(null_mut()) 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /java-spaghetti/src/as_jvalue.rs: -------------------------------------------------------------------------------- 1 | use std::ptr::null_mut; 2 | 3 | use jni_sys::*; 4 | 5 | use crate::{Global, Local, Null, Ref, ReferenceType}; 6 | 7 | #[doc(hidden)] // You should generally not be interacting with this type directly, but it must be public for codegen. 8 | /// By implementing this you assert that you're constructing a valid jvalue for the given argument type (e.g. valid 9 | /// jobject pointer if the function is supposed to take a jobject) 10 | pub unsafe trait AsJValue { 11 | fn as_jvalue(&self) -> jvalue; 12 | } 13 | 14 | unsafe impl AsJValue for bool { 15 | fn as_jvalue(&self) -> jvalue { 16 | jvalue { 17 | z: if *self { JNI_TRUE } else { JNI_FALSE }, 18 | } 19 | } 20 | } 21 | unsafe impl AsJValue for jbyte { 22 | fn as_jvalue(&self) -> jvalue { 23 | jvalue { b: *self } 24 | } 25 | } 26 | unsafe impl AsJValue for jchar { 27 | fn as_jvalue(&self) -> jvalue { 28 | jvalue { c: *self } 29 | } 30 | } 31 | unsafe impl AsJValue for jshort { 32 | fn as_jvalue(&self) -> jvalue { 33 | jvalue { s: *self } 34 | } 35 | } 36 | unsafe impl AsJValue for jint { 37 | fn as_jvalue(&self) -> jvalue { 38 | jvalue { i: *self } 39 | } 40 | } 41 | unsafe impl AsJValue for jlong { 42 | fn as_jvalue(&self) -> jvalue { 43 | jvalue { j: *self } 44 | } 45 | } 46 | unsafe impl AsJValue for jfloat { 47 | fn as_jvalue(&self) -> jvalue { 48 | jvalue { f: *self } 49 | } 50 | } 51 | unsafe impl AsJValue for jdouble { 52 | fn as_jvalue(&self) -> jvalue { 53 | jvalue { d: *self } 54 | } 55 | } 56 | 57 | // do NOT implement, no guarantee any given jobject is actually safe! 58 | // unsafe impl AsJValue for jobject { fn as_jvalue(&self) -> jvalue { jvalue { l: *self } } } 59 | 60 | unsafe impl AsJValue for &T { 61 | fn as_jvalue(&self) -> jvalue { 62 | T::as_jvalue(self) 63 | } 64 | } 65 | 66 | unsafe impl AsJValue for &mut T { 67 | fn as_jvalue(&self) -> jvalue { 68 | T::as_jvalue(self) 69 | } 70 | } 71 | 72 | unsafe impl AsJValue for Null { 73 | fn as_jvalue(&self) -> jvalue { 74 | jvalue { l: null_mut() } 75 | } 76 | } 77 | 78 | unsafe impl AsJValue for Ref<'_, T> { 79 | fn as_jvalue(&self) -> jvalue { 80 | jvalue { l: self.as_raw() } 81 | } 82 | } 83 | 84 | unsafe impl AsJValue for Option> { 85 | fn as_jvalue(&self) -> jvalue { 86 | match self { 87 | None => jvalue { l: null_mut() }, 88 | Some(inner) => inner.as_jvalue(), 89 | } 90 | } 91 | } 92 | 93 | unsafe impl AsJValue for Option<&Ref<'_, T>> { 94 | fn as_jvalue(&self) -> jvalue { 95 | match self { 96 | None => jvalue { l: null_mut() }, 97 | Some(inner) => inner.as_jvalue(), 98 | } 99 | } 100 | } 101 | 102 | unsafe impl AsJValue for Local<'_, T> { 103 | fn as_jvalue(&self) -> jvalue { 104 | jvalue { l: self.as_raw() } 105 | } 106 | } 107 | 108 | unsafe impl AsJValue for Option> { 109 | fn as_jvalue(&self) -> jvalue { 110 | match self { 111 | None => jvalue { l: null_mut() }, 112 | Some(inner) => inner.as_jvalue(), 113 | } 114 | } 115 | } 116 | 117 | unsafe impl AsJValue for Option<&Local<'_, T>> { 118 | fn as_jvalue(&self) -> jvalue { 119 | match self { 120 | None => jvalue { l: null_mut() }, 121 | Some(inner) => inner.as_jvalue(), 122 | } 123 | } 124 | } 125 | 126 | unsafe impl AsJValue for Global { 127 | fn as_jvalue(&self) -> jvalue { 128 | jvalue { l: self.as_raw() } 129 | } 130 | } 131 | 132 | unsafe impl AsJValue for Option> { 133 | fn as_jvalue(&self) -> jvalue { 134 | match self { 135 | None => jvalue { l: null_mut() }, 136 | Some(inner) => inner.as_jvalue(), 137 | } 138 | } 139 | } 140 | 141 | unsafe impl AsJValue for Option<&Global> { 142 | fn as_jvalue(&self) -> jvalue { 143 | match self { 144 | None => jvalue { l: null_mut() }, 145 | Some(inner) => inner.as_jvalue(), 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /java-spaghetti/src/id_cache.rs: -------------------------------------------------------------------------------- 1 | //! New types for `jfieldID` and `jmethodID` that implement `Send` and `Sync`. 2 | //! 3 | //! Inspired by: . 4 | //! 5 | //! According to the JNI spec field IDs may be invalidated when the corresponding class is unloaded: 6 | //! 7 | //! 8 | //! You should generally not be interacting with these types directly, but it must be public for codegen. 9 | 10 | use crate::sys::{jfieldID, jmethodID}; 11 | 12 | #[doc(hidden)] 13 | #[repr(transparent)] 14 | pub struct JFieldID { 15 | internal: jfieldID, 16 | } 17 | 18 | // Field IDs are valid across threads (not tied to a JNIEnv) 19 | unsafe impl Send for JFieldID {} 20 | unsafe impl Sync for JFieldID {} 21 | 22 | impl JFieldID { 23 | /// Creates a [`JFieldID`] that wraps the given `raw` [`jfieldID`]. 24 | /// 25 | /// # Safety 26 | /// 27 | /// Expects a valid, non-`null` ID. 28 | pub unsafe fn from_raw(raw: jfieldID) -> Self { 29 | debug_assert!(!raw.is_null(), "from_raw fieldID argument"); 30 | Self { internal: raw } 31 | } 32 | 33 | pub fn as_raw(&self) -> jfieldID { 34 | self.internal 35 | } 36 | } 37 | 38 | #[doc(hidden)] 39 | #[repr(transparent)] 40 | pub struct JMethodID { 41 | internal: jmethodID, 42 | } 43 | 44 | // Method IDs are valid across threads (not tied to a JNIEnv) 45 | unsafe impl Send for JMethodID {} 46 | unsafe impl Sync for JMethodID {} 47 | 48 | impl JMethodID { 49 | /// Creates a [`JMethodID`] that wraps the given `raw` [`jmethodID`]. 50 | /// 51 | /// # Safety 52 | /// 53 | /// Expects a valid, non-`null` ID. 54 | pub unsafe fn from_raw(raw: jmethodID) -> Self { 55 | debug_assert!(!raw.is_null(), "from_raw methodID argument"); 56 | Self { internal: raw } 57 | } 58 | 59 | pub fn as_raw(&self) -> jmethodID { 60 | self.internal 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /java-spaghetti/src/jni_type.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CStr; 2 | 3 | use jni_sys::*; 4 | 5 | /// JNI bindings rely on this type being accurate. 6 | /// 7 | /// **unsafe**: Passing the wrong type can cause unsoundness, since the code that interacts with JNI blindly trusts it's correct. 8 | /// 9 | /// Why the awkward callback style instead of returning `&'static CStr`? Arrays of arrays may need to dynamically 10 | /// construct their type strings, which would need to leak. Worse, we can't easily intern those strings via 11 | /// lazy_static without running into: 12 | /// 13 | /// ```text 14 | /// error[E0401]: can't use generic parameters from outer function 15 | /// ``` 16 | pub unsafe trait JniType { 17 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R; 18 | } 19 | 20 | unsafe impl JniType for () { 21 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 22 | callback(c"V") 23 | } 24 | } 25 | unsafe impl JniType for bool { 26 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 27 | callback(c"Z") 28 | } 29 | } 30 | unsafe impl JniType for jbyte { 31 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 32 | callback(c"B") 33 | } 34 | } 35 | unsafe impl JniType for jchar { 36 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 37 | callback(c"C") 38 | } 39 | } 40 | unsafe impl JniType for jshort { 41 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 42 | callback(c"S") 43 | } 44 | } 45 | unsafe impl JniType for jint { 46 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 47 | callback(c"I") 48 | } 49 | } 50 | unsafe impl JniType for jlong { 51 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 52 | callback(c"J") 53 | } 54 | } 55 | unsafe impl JniType for jfloat { 56 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 57 | callback(c"F") 58 | } 59 | } 60 | unsafe impl JniType for jdouble { 61 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 62 | callback(c"D") 63 | } 64 | } 65 | unsafe impl JniType for &CStr { 66 | fn static_with_jni_type(callback: impl FnOnce(&CStr) -> R) -> R { 67 | callback(c"Ljava/lang/String;") 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /java-spaghetti/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Common glue code between Rust and JNI, used in auto-generated `java-spaghetti` glue code. 2 | //! 3 | //! See also the [Android JNI tips](https://developer.android.com/training/articles/perf-jni) documentation as well as the 4 | //! [Java Native Interface Specification](https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jniTOC.html). 5 | //! 6 | //! Just like [jni-rs](https://docs.rs/jni/latest/jni/), thread safety of accessing Java objects are not guaranteed, unless 7 | //! they are thread-safe by themselves. 8 | 9 | #![feature(arbitrary_self_types)] 10 | 11 | use std::fmt; 12 | 13 | /// public jni-sys reexport. 14 | pub use ::jni_sys as sys; 15 | 16 | mod refs { 17 | mod arg; 18 | mod global; 19 | mod local; 20 | mod ref_; 21 | mod return_; 22 | 23 | pub use arg::*; 24 | pub use global::*; 25 | pub use local::*; 26 | pub use ref_::*; 27 | pub use return_::*; 28 | } 29 | 30 | mod array; 31 | mod as_arg; 32 | mod as_jvalue; 33 | mod env; 34 | mod id_cache; 35 | mod jni_type; 36 | mod string_chars; 37 | mod vm; 38 | 39 | pub use array::*; 40 | pub use as_arg::*; 41 | pub use as_jvalue::*; 42 | pub use env::*; 43 | pub use id_cache::*; 44 | pub use jni_type::JniType; 45 | pub use refs::*; 46 | pub use string_chars::*; 47 | pub use vm::*; 48 | 49 | /// Error returned on failed `.cast()`.` 50 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 51 | pub struct CastError; 52 | 53 | impl std::error::Error for CastError {} 54 | impl fmt::Display for CastError { 55 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 56 | f.write_str("Cast failed") 57 | } 58 | } 59 | 60 | /// A marker type indicating this is a valid exception type that all exceptions thrown by java should be compatible with 61 | pub trait ThrowableType: ReferenceType {} 62 | 63 | /// You should generally not be interacting with this type directly, but it must be public for codegen. 64 | #[doc(hidden)] 65 | pub unsafe trait ReferenceType: JniType + Sized + 'static {} 66 | 67 | /// Marker trait indicating `Self` can be assigned to `T`. 68 | /// 69 | /// # Safety 70 | /// 71 | /// `T` is a superclass or superinterface of `Self`. 72 | pub unsafe trait AssignableTo: ReferenceType {} 73 | 74 | /// A type is always assignable to itself. 75 | unsafe impl AssignableTo for T {} 76 | 77 | /// A trait similar to `Display`. 78 | pub trait JavaDisplay: ReferenceType { 79 | fn fmt(self: &Ref<'_, Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result; 80 | } 81 | 82 | /// A trait similar to `Debug`. Currently it is implemented by `Throwable` in generated bindings. 83 | pub trait JavaDebug: ReferenceType { 84 | fn fmt(self: &Ref<'_, Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result; 85 | } 86 | 87 | /// Represents a Java `null` value. 88 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] 89 | pub struct Null; 90 | -------------------------------------------------------------------------------- /java-spaghetti/src/refs/arg.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use jni_sys::*; 4 | 5 | use crate::{Env, Global, Local, Ref, ReferenceType}; 6 | 7 | /// FFI: Use **Arg\** instead of `jobject`. This represents a (null?) function argument. 8 | /// 9 | /// Unlike most Java reference types from this library, this *can* be null. 10 | /// 11 | /// FFI safe where a `jobject` is safe, assuming you match your types correctly. Using the wrong type may result in 12 | /// soundness issues, but at least on Android mostly seems to just result in JNI aborting execution for the current 13 | /// process when calling methods on an instance of the wrong type. 14 | #[repr(transparent)] 15 | pub struct Arg { 16 | object: jobject, 17 | _class: PhantomData, 18 | } 19 | 20 | impl Arg { 21 | /// # Safety 22 | /// 23 | /// **unsafe**: There's no guarantee the `jobject` being passed is valid or null, nor any means of checking it. 24 | pub unsafe fn from_raw(object: jobject) -> Self { 25 | Self { 26 | object, 27 | _class: PhantomData, 28 | } 29 | } 30 | 31 | /// Returns the raw JNI reference pointer. 32 | pub fn as_raw(&self) -> jobject { 33 | self.object 34 | } 35 | 36 | /// # Safety 37 | /// 38 | /// **unsafe**: This assumes the argument belongs to the given [Env], which is technically unsound. However, 39 | /// the intended use case of immediately converting any [Arg] into [Ref] at the start of a JNI callback, 40 | /// where Java directly invoked your function with an [Env] + arguments, is sound. 41 | pub unsafe fn into_ref<'env>(self, env: Env<'env>) -> Option> { 42 | if self.object.is_null() { 43 | None 44 | } else { 45 | Some(Ref::from_raw(env, self.object)) 46 | } 47 | } 48 | 49 | /// # Safety 50 | /// 51 | /// **unsafe**: This assumes the argument belongs to the given [Env], which is technically unsound. However, 52 | /// the intended use case of immediately converting any [Arg] into [Local] at the start of a JNI callback, 53 | /// where Java directly invoked your function with an [Env] + arguments, is sound. 54 | pub unsafe fn into_local<'env>(self, env: Env<'env>) -> Option> { 55 | self.into_ref(env).map(|r| r.as_local()) 56 | } 57 | 58 | /// This equals [Arg::into_ref] + [Ref::as_global]. 59 | /// 60 | /// # Safety 61 | /// 62 | /// **unsafe**: The same as [Arg::into_ref]. 63 | pub unsafe fn into_global(self, env: Env) -> Option> { 64 | self.into_ref(env).as_ref().map(Ref::as_global) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /java-spaghetti/src/refs/global.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use jni_sys::*; 4 | 5 | use crate::{Env, Local, Ref, ReferenceType, VM}; 6 | 7 | /// A [Global](https://www.ibm.com/docs/en/sdk-java-technology/8?topic=collector-overview-jni-object-references), 8 | /// non-null, reference to a Java object (+ [VM]). 9 | /// 10 | /// Unlike Local, this can be stored statically and shared between threads. This has a few caveats: 11 | /// * You must create a [Ref] before use. 12 | /// * The [Global] can be invalidated if the [VM] is unloaded. 13 | /// 14 | /// **Not FFI Safe:** `#[repr(rust)]`, and exact layout is likely to change - depending on exact features used - in the 15 | /// future. Specifically, on Android, since we're guaranteed to only have a single ambient VM, we can likely store the 16 | /// `*const JavaVM` in static and/or thread local storage instead of lugging it around in every [Global]. Of course, there's 17 | /// no guarantee that's actually an *optimization*... 18 | pub struct Global { 19 | object: jobject, 20 | vm: VM, 21 | pd: PhantomData, 22 | } 23 | 24 | unsafe impl Send for Global {} 25 | unsafe impl Sync for Global {} 26 | 27 | impl Global { 28 | /// Wraps an owned raw JNI global reference, taking the ownership. 29 | /// 30 | /// # Safety 31 | /// 32 | /// `object` must be an owned non-null JNI global reference to an object of type `T`, 33 | /// not to be deleted by another wrapper. 34 | pub unsafe fn from_raw(vm: VM, object: jobject) -> Self { 35 | Self { 36 | object, 37 | vm, 38 | pd: PhantomData, 39 | } 40 | } 41 | 42 | /// Gets the [VM] under which the JNI reference is created. 43 | pub fn vm(&self) -> VM { 44 | self.vm 45 | } 46 | 47 | /// Returns the raw JNI reference pointer. 48 | pub fn as_raw(&self) -> jobject { 49 | self.object 50 | } 51 | 52 | /// Leaks the `Global` and turns it into a raw pointer, preserving the ownership of 53 | /// one JNI global reference; prevents `DeleteGlobalRef` from being called on dropping. 54 | pub fn into_raw(self) -> jobject { 55 | let object = self.object; 56 | std::mem::forget(self); // Don't delete the object. 57 | object 58 | } 59 | 60 | /// Returns a new JNI local reference of the same Java object. 61 | pub fn as_local<'env>(&self, env: Env<'env>) -> Local<'env, T> { 62 | // Safety: this `Ref<'env, T>` isn't available outside, and it does nothing on dropping. 63 | let temp_ref = unsafe { Ref::from_raw(env, self.object) }; 64 | temp_ref.as_local() // creates a new `Local` 65 | } 66 | 67 | /// Returns a [Ref], with which Java methods from generated bindings can be used. 68 | /// The lifetime of the returned [Ref] can be the intersection of this `Global` 69 | /// and a supposed local reference under `env`. 70 | pub fn as_ref<'env>(&'env self, env: Env<'env>) -> Ref<'env, T> { 71 | unsafe { Ref::from_raw(env, self.object) } 72 | } 73 | } 74 | 75 | impl<'env, T: ReferenceType> From> for Global { 76 | fn from(x: Local<'env, T>) -> Self { 77 | x.as_global() 78 | } 79 | } 80 | 81 | impl<'env, T: ReferenceType> From> for Global { 82 | fn from(x: Ref<'env, T>) -> Self { 83 | x.as_global() 84 | } 85 | } 86 | 87 | impl<'env, T: ReferenceType> From<&Local<'env, T>> for Global { 88 | fn from(x: &Local<'env, T>) -> Self { 89 | x.as_global() 90 | } 91 | } 92 | 93 | impl<'env, T: ReferenceType> From<&Ref<'env, T>> for Global { 94 | fn from(x: &Ref<'env, T>) -> Self { 95 | x.as_global() 96 | } 97 | } 98 | 99 | impl Clone for Global { 100 | fn clone(&self) -> Self { 101 | self.vm.with_env(|env| { 102 | let env = env.as_raw(); 103 | let object = unsafe { ((**env).v1_2.NewGlobalRef)(env, self.object) }; 104 | assert!(!object.is_null()); 105 | Self { 106 | object, 107 | vm: self.vm, 108 | pd: PhantomData, 109 | } 110 | }) 111 | } 112 | } 113 | 114 | impl Drop for Global { 115 | fn drop(&mut self) { 116 | self.vm.with_env(|env| { 117 | let env = env.as_raw(); 118 | unsafe { ((**env).v1_2.DeleteGlobalRef)(env, self.object) } 119 | }); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /java-spaghetti/src/refs/local.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Debug, Display, Formatter}; 2 | use std::mem::transmute; 3 | use std::ops::Deref; 4 | 5 | use jni_sys::*; 6 | 7 | use crate::{AssignableTo, Env, Global, JavaDebug, JavaDisplay, Ref, ReferenceType, Return}; 8 | 9 | /// A [Local](https://www.ibm.com/docs/en/sdk-java-technology/8?topic=collector-overview-jni-object-references), 10 | /// non-null, reference to a Java object (+ [Env]) limited to the current thread/stack. 11 | /// 12 | /// Including the `env` allows for the convenient execution of methods without having to individually pass the `env` as 13 | /// an argument to each and every one. Since this is limited to the current thread/stack, these cannot be sanely stored 14 | /// in any kind of static storage, nor shared between threads - instead use a [Global] if you need to do either. 15 | /// 16 | /// Will `DeleteLocalRef` when dropped, invalidating the `jobject` but ensuring threads that rarely or never return to 17 | /// Java may run without being guaranteed to eventually exhaust their local reference limit. If this is not desired, 18 | /// convert to a plain [Ref] with: 19 | /// 20 | /// ```rust,no_run 21 | /// # use java_spaghetti::*; 22 | /// # fn example(local: Local) { 23 | /// let local = Local::leak(local); 24 | /// # } 25 | /// ``` 26 | /// 27 | /// **Not FFI Safe:** `#[repr(rust)]`, and exact layout is likely to change - depending on exact features used - in the 28 | /// future. Specifically, on Android, since we're guaranteed to only have a single ambient VM, we can likely store the 29 | /// `*const JNIEnv` in thread local storage instead of lugging it around in every [Local]. Of course, there's no 30 | /// guarantee that's actually an *optimization*... 31 | #[repr(C)] // this is NOT for FFI-safety, this is to ensure `cast` methods are sound. 32 | pub struct Local<'env, T: ReferenceType> { 33 | ref_: Ref<'env, T>, 34 | } 35 | 36 | impl<'env, T: ReferenceType> Local<'env, T> { 37 | /// Wraps an owned raw JNI local reference, taking the ownership. 38 | /// 39 | /// # Safety 40 | /// 41 | /// - `object` must be an owned non-null JNI local reference that belongs to `env`, 42 | /// not to be deleted by another wrapper. 43 | /// - `object` references an instance of type `T`. 44 | pub unsafe fn from_raw(env: Env<'env>, object: jobject) -> Self { 45 | Self { 46 | ref_: Ref::from_raw(env, object), 47 | } 48 | } 49 | 50 | /// Gets the [Env] under which the JNI reference is valid. 51 | pub fn env(&self) -> Env<'env> { 52 | self.ref_.env() 53 | } 54 | 55 | /// Returns the raw JNI reference pointer. 56 | pub fn as_raw(&self) -> jobject { 57 | self.ref_.as_raw() 58 | } 59 | 60 | /// Leaks the `Local` and turns it into a raw pointer, preserving the ownership of one JNI 61 | /// local reference; prevents `DeleteLocalRef` from being called on dropping. See [Local::leak]. 62 | pub fn into_raw(self) -> jobject { 63 | let object = self.ref_.as_raw(); 64 | std::mem::forget(self); // Don't allow `Local` to delete it 65 | object 66 | } 67 | 68 | /// Leaks the `Local`, prevents `DeleteLocalRef` from being called on dropping. 69 | /// 70 | /// If the current thread is a Java thread, it will be freed when the control flow returns 71 | /// to Java; otherwise it will be freed when the native thread exits. 72 | /// 73 | /// NOTE: some JVM implementations have a strict limitation of local reference capacity, 74 | /// an uncatchable error will be thrown if the capacity is full. 75 | pub fn leak(self) -> Ref<'env, T> { 76 | unsafe { Ref::from_raw(self.env(), self.into_raw()) } 77 | } 78 | 79 | /// Returns a new JNI global reference of the same Java object. 80 | pub fn as_global(&self) -> Global { 81 | self.as_ref().as_global() 82 | } 83 | 84 | /// Creates and leaks a new local reference to be returned from the JNI `extern` callback function. 85 | /// It will be freed as soon as the control flow returns to Java. 86 | pub fn as_return(&self) -> Return<'env, T> { 87 | self.clone().into_return() 88 | } 89 | 90 | /// Leaks the local reference to be returned from the JNI `extern` callback function. 91 | /// It will be freed as soon as the control flow returns to Java. 92 | pub fn into_return(self) -> Return<'env, T> { 93 | unsafe { Return::from_raw(self.into_raw()) } 94 | } 95 | 96 | /// Tries to cast itself to a JNI reference of type `U`. 97 | pub fn cast(self) -> Result, crate::CastError> { 98 | self.as_ref().check_assignable::()?; 99 | // Memory layout of the inner `Ref<'env, U>` is the same as `Ref<'env, T>`. 100 | Ok(unsafe { transmute::, Local<'_, U>>(self) }) 101 | } 102 | 103 | /// Casts itself towards a super class type, without the cost of runtime checking. 104 | pub fn upcast(self) -> Local<'env, U> 105 | where 106 | Self: AssignableTo, 107 | { 108 | // Memory layout of the inner `Ref<'env, U>` is the same as `Ref<'env, T>`. 109 | unsafe { transmute(self) } 110 | } 111 | } 112 | 113 | impl<'env, T: ReferenceType> From> for Local<'env, T> { 114 | fn from(x: Ref<'env, T>) -> Self { 115 | x.as_local() 116 | } 117 | } 118 | 119 | impl<'env, T: ReferenceType> From<&Local<'env, T>> for Local<'env, T> { 120 | fn from(x: &Local<'env, T>) -> Self { 121 | x.clone() 122 | } 123 | } 124 | 125 | impl<'env, T: ReferenceType> From<&Ref<'env, T>> for Local<'env, T> { 126 | fn from(x: &Ref<'env, T>) -> Self { 127 | x.as_local() 128 | } 129 | } 130 | 131 | // NOTE: `AsRef` would become **unsound** if `Ref` should implement `Copy` or `Clone`. 132 | // 133 | // It is possible to have a safe `pub fn as_ref(&'env self) -> Ref<'env, T>` outside of 134 | // `AsRef` trait, however a borrowed `Ref` is returned for the convenience of use. 135 | impl<'env, T: ReferenceType> AsRef> for Local<'env, T> { 136 | fn as_ref(&self) -> &Ref<'env, T> { 137 | &self.ref_ 138 | } 139 | } 140 | 141 | // NOTE: `Deref` would become **unsound** if `Ref` should implement `Copy` or `Clone`. 142 | impl<'env, T: ReferenceType> Deref for Local<'env, T> { 143 | type Target = Ref<'env, T>; 144 | fn deref(&self) -> &Self::Target { 145 | &self.ref_ 146 | } 147 | } 148 | 149 | impl<'env, T: ReferenceType> Clone for Local<'env, T> { 150 | fn clone(&self) -> Self { 151 | let env = self.env().as_raw(); 152 | let object = unsafe { ((**env).v1_2.NewLocalRef)(env, self.as_raw()) }; 153 | assert!(!object.is_null()); 154 | unsafe { Self::from_raw(self.env(), object) } 155 | } 156 | } 157 | 158 | impl<'env, T: ReferenceType> Drop for Local<'env, T> { 159 | fn drop(&mut self) { 160 | let env = self.env().as_raw(); 161 | unsafe { ((**env).v1_2.DeleteLocalRef)(env, self.as_raw()) } 162 | } 163 | } 164 | 165 | impl<'env, T: JavaDebug> Debug for Local<'env, T> { 166 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 167 | T::fmt(self, f) 168 | } 169 | } 170 | 171 | impl<'env, T: JavaDisplay> Display for Local<'env, T> { 172 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 173 | T::fmt(self, f) 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /java-spaghetti/src/refs/ref_.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Debug, Display, Formatter}; 2 | use std::marker::PhantomData; 3 | use std::mem::transmute; 4 | use std::ops::Deref; 5 | 6 | use jni_sys::jobject; 7 | 8 | use crate::{AssignableTo, Env, Global, JavaDebug, JavaDisplay, Local, ReferenceType}; 9 | 10 | /// A non-null, [reference](https://www.ibm.com/docs/en/sdk-java-technology/8?topic=collector-overview-jni-object-references) 11 | /// to a Java object (+ [Env]). This may refer to a [Local](crate::Local), [Global](crate::Global), local [Arg](crate::Arg), etc. 12 | /// 13 | /// `Ref` guarantees not to have a `Drop` implementation. It does not own the JNI reference. 14 | /// 15 | /// **Not FFI Safe:** `#[repr(rust)]`, and exact layout is likely to change - depending on exact features used - in the 16 | /// future. Specifically, on Android, since we're guaranteed to only have a single ambient VM, we can likely store the 17 | /// `*const JNIEnv` in thread local storage instead of lugging it around in every [Ref]. Of course, there's no 18 | /// guarantee that's actually an *optimization*... 19 | #[repr(C)] // this is NOT for FFI-safety, this is to ensure `cast` methods are sound. 20 | pub struct Ref<'env, T: ReferenceType> { 21 | object: jobject, 22 | env: Env<'env>, 23 | _class: PhantomData, 24 | } 25 | 26 | impl<'env, T: ReferenceType> std::ops::Receiver for Ref<'env, T> { 27 | type Target = T; 28 | } 29 | 30 | impl<'env, T: ReferenceType> Ref<'env, T> { 31 | /// Wraps an raw JNI reference. 32 | /// 33 | /// # Safety 34 | /// 35 | /// - `object` is a non-null JNI reference, and it must keep valid under `env` before the created `Ref` goes out of scope. 36 | /// This means it should not be a raw pointer managed by [Local] or any other wrapper that deletes it on dropping. 37 | /// - `object` references an instance of type `T`. 38 | pub unsafe fn from_raw(env: Env<'env>, object: jobject) -> Self { 39 | Self { 40 | object, 41 | env, 42 | _class: PhantomData, 43 | } 44 | } 45 | 46 | /// Gets the [Env] under which the JNI reference is valid. 47 | pub fn env(&self) -> Env<'env> { 48 | self.env 49 | } 50 | 51 | /// Returns the raw JNI reference pointer. 52 | pub fn as_raw(&self) -> jobject { 53 | self.object 54 | } 55 | 56 | /// Returns a new JNI global reference of the same Java object. 57 | pub fn as_global(&self) -> Global { 58 | let env = self.env(); 59 | let jnienv = env.as_raw(); 60 | let object = unsafe { ((**jnienv).v1_2.NewGlobalRef)(jnienv, self.as_raw()) }; 61 | assert!(!object.is_null()); 62 | unsafe { Global::from_raw(env.vm(), object) } 63 | } 64 | 65 | /// Returns a new JNI local reference of the same Java object. 66 | pub fn as_local(&self) -> Local<'env, T> { 67 | let env = self.env(); 68 | let jnienv = env.as_raw(); 69 | let object = unsafe { ((**jnienv).v1_2.NewLocalRef)(jnienv, self.as_raw()) }; 70 | assert!(!object.is_null()); 71 | unsafe { Local::from_raw(self.env(), object) } 72 | } 73 | 74 | /// Enters monitored mode or increments the JNI monitor counter in this thread for the referenced Java object. 75 | /// See [Monitor] for the limited locking functionality. 76 | pub fn as_monitor(&'env self) -> Monitor<'env, T> { 77 | Monitor::new(self) 78 | } 79 | 80 | /// Tests whether two JNI references refer to the same Java object. 81 | pub fn is_same_object(&self, other: &Ref<'_, O>) -> bool { 82 | let jnienv = self.env.as_raw(); 83 | unsafe { ((**jnienv).v1_2.IsSameObject)(jnienv, self.as_raw(), other.as_raw()) } 84 | } 85 | 86 | /// Checks if the Java object can be safely casted to type `U`. 87 | pub(crate) fn check_assignable(&self) -> Result<(), crate::CastError> { 88 | let env = self.env(); 89 | let jnienv = env.as_raw(); 90 | let class = U::static_with_jni_type(|t| unsafe { env.require_class(t) }); 91 | if !unsafe { ((**jnienv).v1_2.IsInstanceOf)(jnienv, self.as_raw(), class) } { 92 | return Err(crate::CastError); 93 | } 94 | Ok(()) 95 | } 96 | 97 | /// Casts itself to a JNI reference of type `U` forcefully, without the cost of runtime checking. 98 | /// 99 | /// # Safety 100 | /// 101 | /// - `self` references an instance of type `U`. 102 | pub unsafe fn cast_unchecked(self) -> Ref<'env, U> { 103 | transmute(self) 104 | } 105 | 106 | /// Tries to cast itself to a JNI reference of type `U`. 107 | pub fn cast(self) -> Result, crate::CastError> { 108 | self.check_assignable::()?; 109 | Ok(unsafe { self.cast_unchecked() }) 110 | } 111 | 112 | /// Casts itself towards a super class type, without the cost of runtime checking. 113 | pub fn upcast(self) -> Ref<'env, U> 114 | where 115 | Self: AssignableTo, 116 | { 117 | unsafe { self.cast_unchecked() } 118 | } 119 | 120 | /// Casts the borrowed `Ref` to a JNI reference of type `U` forcefully, without the cost of runtime checking. 121 | /// 122 | /// # Safety 123 | /// 124 | /// - `self` references an instance of type `U`. 125 | pub unsafe fn cast_ref_unchecked(&self) -> &Ref<'env, U> { 126 | transmute(self) 127 | } 128 | 129 | /// Tries to cast the borrowed `Ref` to a JNI reference of type `U`. 130 | pub fn cast_ref(&self) -> Result<&Ref<'env, U>, crate::CastError> { 131 | self.check_assignable::()?; 132 | Ok(unsafe { self.cast_ref_unchecked() }) 133 | } 134 | 135 | /// Casts the borrowed `Ref` towards a super class type, without the cost of runtime checking. 136 | pub fn upcast_ref(&self) -> &Ref<'env, U> 137 | where 138 | Self: AssignableTo, 139 | { 140 | unsafe { self.cast_ref_unchecked() } 141 | } 142 | } 143 | 144 | impl<'env, T: JavaDebug> Debug for Ref<'env, T> { 145 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 146 | T::fmt(self, f) 147 | } 148 | } 149 | 150 | impl<'env, T: JavaDisplay> Display for Ref<'env, T> { 151 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 152 | T::fmt(self, f) 153 | } 154 | } 155 | 156 | /// A borrowed [Ref] of a Java object locked with the JNI monitor mechanism, providing *limited* thread safety. 157 | /// 158 | /// **It is imposible to be FFI safe.** It is important to drop the monitor or call [Monitor::unlock()] when appropriate. 159 | /// 160 | /// Limitations: 161 | /// 162 | /// - It merely blocks other native functions from owning the JNI monitor of the same object before it drops. 163 | /// - It may not block other native functions from using the corresponding object without entering monitored mode. 164 | /// - It may not prevent any Java method or block from using this object, even if it is marked as `synchronized`. 165 | /// - While it is a reentrant lock for the current thread, dead lock is still possible under multi-thread conditions. 166 | pub struct Monitor<'env, T: ReferenceType> { 167 | inner: &'env Ref<'env, T>, 168 | } 169 | 170 | impl<'env, T: ReferenceType> Monitor<'env, T> { 171 | fn new(reference: &'env Ref<'env, T>) -> Self { 172 | let jnienv = reference.env.as_raw(); 173 | let result = unsafe { ((**jnienv).v1_2.MonitorEnter)(jnienv, reference.as_raw()) }; 174 | assert!(result == jni_sys::JNI_OK); 175 | Self { inner: reference } 176 | } 177 | 178 | /// Decrements the JNI monitor counter indicating the number of times it has entered this monitor. 179 | /// If the value of the counter becomes zero, the current thread releases the monitor. 180 | pub fn unlock(self) -> &'env Ref<'env, T> { 181 | let inner = self.inner; 182 | drop(self); // this looks clearer than dropping implicitly 183 | inner 184 | } 185 | } 186 | 187 | impl<'env, T: ReferenceType> Deref for Monitor<'env, T> { 188 | type Target = Ref<'env, T>; 189 | fn deref(&self) -> &Self::Target { 190 | self.inner 191 | } 192 | } 193 | 194 | impl<'env, T: ReferenceType> Drop for Monitor<'env, T> { 195 | fn drop(&mut self) { 196 | let env = self.inner.env; 197 | let jnienv = env.as_raw(); 198 | let result = unsafe { ((**jnienv).v1_2.MonitorExit)(jnienv, self.inner.as_raw()) }; 199 | assert!(result == jni_sys::JNI_OK); 200 | let exception = unsafe { ((**jnienv).v1_2.ExceptionOccurred)(jnienv) }; 201 | assert!( 202 | exception.is_null(), 203 | "exception happened calling JNI MonitorExit, the monitor is probably broken previously" 204 | ); 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /java-spaghetti/src/refs/return_.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | use std::ptr::null_mut; 3 | 4 | use jni_sys::jobject; 5 | 6 | use crate::ReferenceType; 7 | 8 | /// FFI: Use **Return\** instead of `jobject`. This represents a (null?) JNI function call return value. 9 | /// 10 | /// Unlike most Java reference types from this library, this *can* be null. Recommended constructors are 11 | /// [crate::Local::into_return] and [Return::null]. 12 | /// 13 | /// FFI safe where a jobject is safe, assuming you match your types correctly. 14 | #[repr(transparent)] 15 | pub struct Return<'env, T: ReferenceType> { 16 | object: jobject, 17 | _class: PhantomData<&'env T>, 18 | } 19 | 20 | impl<'env, T: ReferenceType> Return<'env, T> { 21 | /// Wraps a raw JNI reference. 22 | /// 23 | /// # Safety 24 | /// 25 | /// - If `object` is non-null, it must be a JNI local(?) reference to an instance of type `T`; 26 | /// - `object` must keep valid for `'env` lifetime; it is not owned by `Local` or any other wrapper 27 | /// that deletes the reference on `Drop` before the JNI native method call returns. 28 | pub unsafe fn from_raw(object: jobject) -> Self { 29 | Self { 30 | object, 31 | _class: PhantomData, 32 | } 33 | } 34 | 35 | /// Creates a null value to be returned from the JNI native method. 36 | pub fn null() -> Self { 37 | Self { 38 | object: null_mut(), 39 | _class: PhantomData, 40 | } 41 | } 42 | 43 | /// Returns the raw JNI reference pointer. Generally it should not be used. 44 | pub fn as_raw(&self) -> jobject { 45 | self.object 46 | } 47 | } 48 | 49 | impl<'env, T: ReferenceType> Default for Return<'env, T> { 50 | /// This is a null value. 51 | fn default() -> Self { 52 | Self::null() 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /java-spaghetti/src/string_chars.rs: -------------------------------------------------------------------------------- 1 | use std::{char, iter, slice}; 2 | 3 | use jni_sys::*; 4 | 5 | use crate::Env; 6 | 7 | /// Represents a JNI `GetStringChars` + `GetStringLength` query. 8 | /// It will call `ReleaseStringChars` automatically when dropped. 9 | pub struct StringChars<'env> { 10 | env: Env<'env>, 11 | string: jstring, 12 | chars: *const jchar, 13 | length: jsize, // in characters 14 | } 15 | 16 | impl<'env> StringChars<'env> { 17 | /// Construct a `StringChars` from an [Env] + [jstring]. 18 | /// 19 | /// # Safety 20 | /// 21 | /// The Java string object referenced by `string` must remain available before the created 22 | /// `StringChars` is dropped. This should be true if the JNI reference `string` is not deleted. 23 | /// 24 | /// This function is supposed to be used in generated bindings. 25 | pub unsafe fn from_env_jstring(env: Env<'env>, string: jstring) -> Self { 26 | debug_assert!(!string.is_null()); 27 | 28 | let chars = env.get_string_chars(string); 29 | let length = env.get_string_length(string); 30 | 31 | Self { 32 | env, 33 | string, 34 | chars, 35 | length, 36 | } 37 | } 38 | 39 | /// Get an array of [jchar]s. Generally UTF16, but not guaranteed to be valid UTF16. 40 | pub fn chars(&self) -> &[jchar] { 41 | unsafe { slice::from_raw_parts(self.chars, self.length as usize) } 42 | } 43 | 44 | /// [std::char::decode_utf16]\(...\)s these string characters. 45 | pub fn decode(&self) -> char::DecodeUtf16>> { 46 | char::decode_utf16(self.chars().iter().cloned()) 47 | } 48 | 49 | /// Returns a new [Ok]\([String]\), or an [Err]\([DecodeUtf16Error](char::DecodeUtf16Error)\) if if it contained any invalid UTF16. 50 | pub fn to_string(&self) -> Result { 51 | self.decode().collect() 52 | } 53 | 54 | /// Returns a new [String] with any invalid UTF16 characters replaced with [REPLACEMENT_CHARACTER](char::REPLACEMENT_CHARACTER)s (`'\u{FFFD}'`.) 55 | pub fn to_string_lossy(&self) -> String { 56 | self.decode() 57 | .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)) 58 | .collect() 59 | } 60 | } 61 | 62 | impl<'env> Drop for StringChars<'env> { 63 | fn drop(&mut self) { 64 | unsafe { self.env.release_string_chars(self.string, self.chars) }; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /java-spaghetti/src/vm.rs: -------------------------------------------------------------------------------- 1 | use std::cell::{Cell, OnceCell}; 2 | use std::ptr::null_mut; 3 | 4 | use jni_sys::*; 5 | 6 | use crate::Env; 7 | 8 | /// FFI: Use **&VM** instead of `*const JavaVM`. This represents a global, process-wide Java exection environment. 9 | /// 10 | /// On Android, there is only one VM per-process, although on desktop it's possible (if rare) to have multiple VMs 11 | /// within the same process. This library does not support having multiple VMs active simultaniously. 12 | /// 13 | /// This is a "safe" alternative to `jni_sys::JavaVM` raw pointers, with the following caveats: 14 | /// 15 | /// 1) A null vm will result in **undefined behavior**. Java should not be invoking your native functions with a null 16 | /// `*mut JavaVM`, however, so I don't believe this is a problem in practice unless you've bindgened the C header 17 | /// definitions elsewhere, calling them (requiring `unsafe`), and passing null pointers (generally UB for JNI 18 | /// functions anyways, so can be seen as a caller soundness issue.) 19 | /// 20 | /// 2) Allowing the underlying JavaVM to be modified is **undefined behavior**. I don't believe the JNI libraries 21 | /// modify the JavaVM, so as long as you're not accepting a `*mut JavaVM` elsewhere, using unsafe to dereference it, 22 | /// and mucking with the methods on it yourself, I believe this "should" be fine. 23 | #[repr(transparent)] 24 | #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 25 | pub struct VM(*mut JavaVM); 26 | 27 | impl VM { 28 | pub fn as_raw(&self) -> *mut JavaVM { 29 | self.0 30 | } 31 | 32 | /// Constructs `VM` with a valid `jni_sys::JavaVM` raw pointer. 33 | /// 34 | /// # Safety 35 | /// 36 | /// - Make sure the corresponding JVM will keep alive within the lifetime of current native library or application. 37 | /// - Do not use any class redefinition feature, which may break the validity of method/field IDs to be cached. 38 | pub unsafe fn from_raw(vm: *mut JavaVM) -> Self { 39 | Self(vm) 40 | } 41 | 42 | pub fn with_env(&self, callback: F) -> R 43 | where 44 | F: for<'env> FnOnce(Env<'env>) -> R, 45 | { 46 | let mut env = null_mut(); 47 | let just_attached = match unsafe { ((**self.0).v1_2.GetEnv)(self.0, &mut env, JNI_VERSION_1_2) } { 48 | JNI_OK => false, 49 | JNI_EDETACHED => { 50 | let ret = unsafe { ((**self.0).v1_2.AttachCurrentThread)(self.0, &mut env, null_mut()) }; 51 | if ret != JNI_OK { 52 | panic!("AttachCurrentThread returned unknown error: {}", ret) 53 | } 54 | if !get_thread_exit_flag() { 55 | set_thread_attach_flag(self.0); 56 | } 57 | true 58 | } 59 | JNI_EVERSION => panic!("GetEnv returned JNI_EVERSION"), 60 | unexpected => panic!("GetEnv returned unknown error: {}", unexpected), 61 | }; 62 | 63 | let result = callback(unsafe { Env::from_raw(env as _) }); 64 | 65 | if just_attached && get_thread_exit_flag() { 66 | // this is needed in case of `with_env` is used on dropping some thread-local instance. 67 | unsafe { ((**self.0).v1_2.DetachCurrentThread)(self.0) }; 68 | } 69 | 70 | result 71 | } 72 | } 73 | 74 | unsafe impl Send for VM {} 75 | unsafe impl Sync for VM {} 76 | 77 | thread_local! { 78 | static THREAD_ATTACH_FLAG: Cell> = const { Cell::new(None) }; 79 | static THREAD_EXIT_FLAG: OnceCell<()> = const { OnceCell::new() }; 80 | } 81 | 82 | struct AttachFlag { 83 | raw_vm: *mut JavaVM, 84 | } 85 | 86 | impl Drop for AttachFlag { 87 | fn drop(&mut self) { 88 | // avoids the fatal error "Native thread exiting without having called DetachCurrentThread" 89 | unsafe { ((**self.raw_vm).v1_2.DetachCurrentThread)(self.raw_vm) }; 90 | let _ = THREAD_EXIT_FLAG.try_with(|flag| flag.set(())); 91 | } 92 | } 93 | 94 | fn set_thread_attach_flag(raw_vm: *mut JavaVM) { 95 | THREAD_ATTACH_FLAG.replace(Some(AttachFlag { raw_vm })); 96 | } 97 | 98 | fn get_thread_exit_flag() -> bool { 99 | THREAD_EXIT_FLAG.try_with(|flag| flag.get().is_some()).unwrap_or(true) 100 | } 101 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | group_imports = "StdExternalCrate" 2 | imports_granularity = "Module" 3 | max_width = 120 4 | --------------------------------------------------------------------------------