diff --git a/.gitignore b/.gitignore index e403f14..9d9fd8d 100644 --- a/.gitignore +++ b/.gitignore @@ -162,4 +162,8 @@ bin/ # Simulation GUI and other tools window save file *-window.json -/src/main/java/org/frc5572/robotools/IOTypes.java \ No newline at end of file +/src/main/java/org/frc5572/robotools/IOTypes.java + +# Added by cargo + +/target diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c5f3f6b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "interactive" +} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1d37238 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,294 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "bytes" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "proc-macro2" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "robot-tools" +version = "0.1.0" +dependencies = [ + "jni", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "syn" +version = "2.0.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..5146a10 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "robot-tools" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib"] +path = "src/main/rust/lib.rs" + +[dependencies] +jni = "0.21" diff --git a/build.gradle b/build.gradle index e1b779c..047e0b3 100755 --- a/build.gradle +++ b/build.gradle @@ -17,15 +17,51 @@ tasks.withType(JavaCompile) { options.compilerArgs << '--add-exports' << 'jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED' } -// sourceCompatibility = JavaVersion.VERSION_17 -// targetCompatibility = JavaVersion.VERSION_17 +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} repositories { mavenCentral() } dependencies { - + implementation 'org.apache.commons:commons-lang3:3.15.0' +} + +task buildRustWindows(type: Exec) { + commandLine System.properties['user.home'] + '/.cargo/bin/cargo', 'build', '--target', 'x86_64-pc-windows-gnu', '--release' +} + +task buildRustLinux(type: Exec) { + commandLine System.properties['user.home'] + '/.cargo/bin/cargo', 'build', '--target', 'x86_64-unknown-linux-gnu' +} + +task buildRust { + dependsOn('buildRustWindows') + dependsOn('buildRustLinux') +} + +task copyRustWindows(type: Copy) { + dependsOn('buildRustWindows') + from 'target/x86_64-pc-windows-gnu/release/robot_tools.dll' + into 'src/main/resources' +} + +task copyRustLinux(type: Copy) { + dependsOn('buildRustLinux') + from 'target/x86_64-unknown-linux-gnu/debug/librobot_tools.so' + into 'src/main/resources' +} + +task copyRust { + dependsOn('copyRustWindows') + dependsOn('copyRustLinux') +} + +tasks.named('processResources') { + dependsOn('copyRust') } publishing { @@ -34,7 +70,7 @@ publishing { // Use jitpack format for publishing to mavenLocal groupId = 'com.github.Frc5572' artifactId = 'RobotTools' - version = 'main-SNAPSHOT' + version = 'test' from components.java } diff --git a/gen_io_types/.gitignore b/gen_io_types/.gitignore deleted file mode 100644 index 9c71cc9..0000000 --- a/gen_io_types/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/Cargo.lock -/target \ No newline at end of file diff --git a/gen_io_types/Cargo.toml b/gen_io_types/Cargo.toml deleted file mode 100644 index 6a12474..0000000 --- a/gen_io_types/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "gen_io_types" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -vendordeps = { git = "https://github.com/wilsonwatson/vendordeps.git" } -binrw = "0.13" -zip = "0.6" -tokio = { version = "1", features = ["full"] } -tempfile = "3.9" -serde_json = "1" \ No newline at end of file diff --git a/gen_io_types/src/java.rs b/gen_io_types/src/java.rs deleted file mode 100644 index 4866283..0000000 --- a/gen_io_types/src/java.rs +++ /dev/null @@ -1,192 +0,0 @@ -use binrw::BinRead; - -#[doc = "Enough of a Java Class to figure out its name, package and what it extends/implements"] -#[binrw::binread] -#[br(big, magic = b"\xca\xfe\xba\xbe")] -pub struct MinimalJavaClass { - #[br(temp)] - _minor_version: u16, - #[br(temp)] - _major_version: u16, - constant_pool: ConstantPool, - access_flags: u16, - this_class: u16, - super_class: u16, - #[br(temp)] - interfaces_count: u16, - #[br(count = interfaces_count)] - _interfaces: Vec, -} - -#[allow(unused)] -impl MinimalJavaClass { - pub fn this_class(&self) -> String { - match &self.constant_pool.0[self.this_class as usize - 1] { - ConstantPoolItem::Class { name_index } => { - match &self.constant_pool.0[*name_index as usize - 1] { - ConstantPoolItem::Utf8 { value } => { - return value.clone(); - } - x => panic!("cpool[this_class.name_index] is not a ConstantPoolItem::Utf8... Instead got {:?}", x) - } - }, - x => panic!("this_class is not a ConstantPoolItem::Class... Instead got {:?}", x) - } - } - - pub fn super_class(&self) -> String { - match &self.constant_pool.0[self.super_class as usize - 1] { - ConstantPoolItem::Class { name_index } => { - match &self.constant_pool.0[*name_index as usize - 1] { - ConstantPoolItem::Utf8 { value } => { - return value.clone(); - } - x => panic!("cpool[super_class.name_index] is not a ConstantPoolItem::Utf8... Instead got {:?}", x) - } - }, - x => panic!("super_class is not a ConstantPoolItem::Class... Instead got {:?}", x) - } - } - - pub fn is_public(&self) -> bool { - (self.access_flags & 0x0001) != 0 - } - - pub fn is_interface(&self) -> bool { - (self.access_flags & 0x0200) != 0 - } - - pub fn is_synthetic(&self) -> bool { - (self.access_flags & 0x1000) != 0 - } - - pub fn is_annotation(&self) -> bool { - (self.access_flags & 0x2000) != 0 - } - - pub fn is_enum(&self) -> bool { - (self.access_flags & 0x4000) != 0 - } -} - -struct ConstantPool(Vec); - -impl BinRead for ConstantPool { - type Args<'a> = (); - - fn read_options( - reader: &mut R, - _endian: binrw::Endian, - _args: Self::Args<'_>, - ) -> binrw::prelude::BinResult { - let cpool_count = u16::read_be(reader)?; - let mut cpool = Vec::new(); - let mut i = 1; - loop { - if i >= cpool_count { - break - } - let pos = reader.stream_position()?; - let item = ConstantPoolItem::read_be(reader)?; - let bump = match &item { - ConstantPoolItem::Long { .. } | ConstantPoolItem::Double { .. } => 2, - ConstantPoolItem::Skip => return Err(binrw::Error::AssertFail { pos, message: format!("Invalid Constant Pool Item.") }), - _ => 1 - }; - cpool.push(item); - for _ in 1..bump { - cpool.push(ConstantPoolItem::Skip); - } - - i += bump; - } - Ok(Self(cpool)) - } -} - -#[doc = "Constant Pool Item enum. Defined in SE Spec sec 4.4"] -#[binrw::binread] -#[derive(Debug)] -enum ConstantPoolItem { - #[br(magic = 7u8)] - Class { - name_index: u16, - }, - #[br(magic = 9u8)] - Fieldref { - _class_index: u16, - _name_and_type_index: u16, - }, - #[br(magic = 10u8)] - Methodref { - _class_index: u16, - _name_and_type_index: u16, - }, - #[br(magic = 11u8)] - InterfaceMethodref { - _class_index: u16, - _name_and_type_index: u16, - }, - #[br(magic = 8u8)] - String { - _string_index: u16, - }, - #[br(magic = 3u8)] - Integer { - _bytes: u32, - }, - #[br(magic = 4u8)] - Float { - _bytes: u32, - }, - #[br(magic = 5u8)] - Long { - _bytes: u64, - }, - #[br(magic = 6u8)] - Double { - _bytes: u64, - }, - #[br(magic = 12u8)] - NameAndType { - _name_index: u16, - _descriptor_index: u16, - }, - #[br(magic = 1u8)] - Utf8 { - #[br(temp)] - length: u16, - // Technically, Java supports CESU-8, not UTF-8, but this is close enough for now. - #[br(count = length, try_map = |x: Vec| String::from_utf8(x))] - value: String, - }, - #[br(magic = 15u8)] - MethodHandle { - _reference_kind: u8, - _reference_index: u16, - }, - #[br(magic = 16u8)] - MethodType { - _descriptor_index: u16, - }, - #[br(magic = 17u8)] - Dynamic { - _bootstrap_method_attr_index: u16, - _name_and_type_index: u16, - }, - #[br(magic = 18u8)] - InvokeDynamic { - _bootstrap_method_attr_index: u16, - _name_and_type_index: u16, - }, - #[br(magic = 19u8)] - Module { - _name_index: u16, - }, - #[br(magic = 20u8)] - Package { - _name_index: u16, - }, - - Skip, -} diff --git a/gen_io_types/src/main.rs b/gen_io_types/src/main.rs deleted file mode 100644 index 8ba970d..0000000 --- a/gen_io_types/src/main.rs +++ /dev/null @@ -1,103 +0,0 @@ -use std::{collections::HashMap, io::{Read, Write}}; - -use binrw::BinRead; -use tempfile::tempdir; - - -mod java; - -#[tokio::main] -async fn main() { - let source_dir = std::path::Path::new(file!()).canonicalize().unwrap(); - let source_dir = source_dir.parent().unwrap().parent().unwrap().parent().unwrap(); - - let temp_dir = tempdir().unwrap(); - - let mut interfaces = String::from("{"); - let mut classes = String::from("{"); - - let wpi = std::fs::read(source_dir.join("config.json")).unwrap(); - let wpi: HashMap> = serde_json::from_slice(&wpi).unwrap(); - for interface in &wpi["interfaces"] { - interfaces.push_str(&format!("\n {:?},", interface)); - } - for class in &wpi["classes"] { - classes.push_str(&format!("\n {:?},", class)); - } - - let skip = wpi["skip"].clone(); - - let vendor_deps_dir = source_dir.join("vendordeps"); - for item in std::fs::read_dir(vendor_deps_dir).unwrap() { - let item = item.unwrap(); - match item.path().extension().and_then(|x| x.to_str()) { - Some("json") => { - let vendordep: vendordeps::VendorDep = match serde_json::from_reader(std::fs::File::open(item.path()).unwrap()) { - Ok(x) => x, - Err(x) => { - eprintln!("Invalid format for vendordep at {}", item.path().display()); - eprintln!("{}", x); - continue - }, - }; - vendordep.download_all_java_deps_to_folder(temp_dir.path()).await.unwrap(); - } - _ => {} - } - } - - for item in std::fs::read_dir(temp_dir.path()).unwrap() { - let item = item.unwrap(); - if item.file_type().unwrap().is_dir() { - continue - } - let f = std::fs::File::open(item.path()).unwrap(); - let mut z = zip::ZipArchive::new(f).unwrap(); - for i in 0..z.len() { - let mut f = z.by_index(i).unwrap(); - if !f.name().ends_with(".class") { - continue - } - // ZipFile can't seek, so we need to fill it into a buffer first. - let mut res = Vec::new(); - f.read_to_end(&mut res).unwrap(); - - let mut res = std::io::Cursor::new(res); - let class = java::MinimalJavaClass::read_be(&mut res).unwrap(); - - if !class.is_public() { - continue - } - if class.is_annotation() { - continue - } - if class.is_enum() { - continue - } - - let name = class.this_class().replace('/', ".").replace('$', "."); - - if skip.contains(&name) { - continue - } - - if class.is_interface() { - interfaces.push_str(&format!("\n {:?},", name)); - } else { - classes.push_str(&format!("\n {:?},", name)); - } - } - } - - let mut outf = std::fs::File::create(source_dir.join("src/main/java/org/frc5572/robotools/IOTypes.java")).unwrap(); - writeln!(&mut outf, "package org.frc5572.robotools;\n").unwrap(); - writeln!(&mut outf, "/** Auto-generated list of IO interfaces and classes. */").unwrap(); - writeln!(&mut outf, "public class IOTypes {{\n").unwrap(); - writeln!(&mut outf, " /** List of interfaces disallowed a direct path to Robot.java. */").unwrap(); - writeln!(&mut outf, " public static String[] ioInterfaces = {}", interfaces).unwrap(); - writeln!(&mut outf, " }};").unwrap(); - writeln!(&mut outf, " /** List of classes disallowed a direct path to Robot.java. */").unwrap(); - writeln!(&mut outf, " public static String[] ioClasses = {}", classes).unwrap(); - writeln!(&mut outf, " }};").unwrap(); - writeln!(&mut outf, "}}\n").unwrap(); -} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 249e583..7f93135 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index c23a1b3..3fa8f86 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME -distributionPath=permwrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME -zipStorePath=permwrapper/dists +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index a69d9cb..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -55,7 +55,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +80,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,22 +131,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index f127cfd..6689b85 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,91 +1,92 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/install_toolchains.sh b/install_toolchains.sh new file mode 100644 index 0000000..b96fc12 --- /dev/null +++ b/install_toolchains.sh @@ -0,0 +1,4 @@ +apt-get update +apt-get install -y build-essential curl g++-mingw-w64-x86-64 +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | bash -s -- -y +$HOME/.cargo/bin/rustup target add x86_64-pc-windows-gnu diff --git a/jitpack.yml b/jitpack.yml index 83c8146..c974ccf 100644 --- a/jitpack.yml +++ b/jitpack.yml @@ -2,4 +2,5 @@ jdk: - openjdk17 before_install: - sdk install java 17.0.1-open - - sdk use java 17.0.1-open \ No newline at end of file + - sdk use java 17.0.1-open + - ./install_toolchains.sh \ No newline at end of file diff --git a/src/main/java/org/frc5572/robotools/Checks.java b/src/main/java/org/frc5572/robotools/Checks.java deleted file mode 100644 index 1971cc8..0000000 --- a/src/main/java/org/frc5572/robotools/Checks.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.frc5572.robotools; - -import org.frc5572.robotools.checks.Check; -import org.frc5572.robotools.checks.IOCheck; - -/** All checks to run. */ -public class Checks { - - private static final Check[] CHECKS = new Check[] {new IOCheck()}; - - /** Run through all checks */ - public static boolean process(CompilationData data) { - boolean fatal = false; - for (Check c : CHECKS) { - fatal = fatal || c.check(data); - } - return fatal; - } - -} diff --git a/src/main/java/org/frc5572/robotools/CompilationData.java b/src/main/java/org/frc5572/robotools/CompilationData.java deleted file mode 100755 index c7866ce..0000000 --- a/src/main/java/org/frc5572/robotools/CompilationData.java +++ /dev/null @@ -1,137 +0,0 @@ -package org.frc5572.robotools; - -import javax.annotation.processing.Messager; -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.Element; -import javax.lang.model.element.TypeElement; -import javax.lang.model.util.Types; -import javax.tools.Diagnostic; -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.tree.LineMap; -import com.sun.source.tree.Tree; -import com.sun.source.util.JavacTask; -import com.sun.source.util.SourcePositions; -import com.sun.source.util.TaskEvent; -import com.sun.source.util.Trees; - -/** - * Wrapper around a TypeElement. Includes helpers for printing errors, warnings etc. - */ -public class CompilationData { - - /** Type Information for entire classpath. */ - public Types types; - private Trees trees; - private SourcePositions positions; - private CompilationUnitTree compilationUnitTree; - /** Element being processed */ - public TypeElement element; - private Messager messager; - - /** Basic constructor. */ - public CompilationData(Types types, Trees trees, SourcePositions positions, - CompilationUnitTree compilationUnitTree, TypeElement element, Messager messager) { - this.types = types; - this.trees = trees; - this.positions = positions; - this.compilationUnitTree = compilationUnitTree; - this.element = element; - this.messager = messager; - } - - /** Constructor from Javac Plugin context. */ - public CompilationData(JavacTask task, TaskEvent event) { - this(task.getTypes(), Trees.instance(task), Trees.instance(task).getSourcePositions(), - event.getCompilationUnit(), event.getTypeElement(), null); - } - - /** Constructor from Annotation Processor context. */ - public CompilationData(ProcessingEnvironment processingEnv, TypeElement element) { - this(processingEnv.getTypeUtils(), null, null, null, element, processingEnv.getMessager()); - } - - /** Show error */ - public void error(Element element, Object object) { - echo(element, object.toString(), Diagnostic.Kind.ERROR, "error", "Error"); - } - - /** Show warning */ - public void warn(Element element, Object object) { - echo(element, object.toString(), Diagnostic.Kind.MANDATORY_WARNING, "warning", "Warning"); - } - - /** Show note (this doesn't work in VS Code yet) */ - public void note(Element element, Object object) { - echo(element, object.toString(), Diagnostic.Kind.NOTE, "notice", "Note"); - } - - private void echo(Element element, String errString, Diagnostic.Kind kind, String ghString, - String humanString) { - if (compilationUnitTree == null) { - messager.printMessage(kind, errString, element); - } else { - Tree tree = trees.getTree(element); - LineMap linemap = compilationUnitTree.getLineMap(); - long pos = positions.getStartPosition(compilationUnitTree, tree); - long row = linemap.getLineNumber(pos); - String name = compilationUnitTree.getSourceFile().toUri().toString().split("/src/")[1]; - System.out - .println("::" + ghString + " file=src/" + name + ",line=" + row + "::" + errString); - } - } - - private boolean _implements(String qualifiedName, TypeElement elem) { - if (elem.getQualifiedName().toString().equals(qualifiedName)) { - return true; - } - Element superClass = types.asElement(elem.getSuperclass()); - if (superClass instanceof TypeElement) { - if (_implements(qualifiedName, (TypeElement) superClass)) { - return true; - } - } - for (var iface : elem.getInterfaces()) { - Element interface_ = types.asElement(iface); - if (interface_ instanceof TypeElement) { - if (_implements(qualifiedName, (TypeElement) interface_)) { - return true; - } - } - } - return false; - } - - private boolean _extends(String qualifiedName, TypeElement elem) { - if (elem.getQualifiedName().toString().equals(qualifiedName)) { - return true; - } - Element superClass = types.asElement(elem.getSuperclass()); - if (superClass instanceof TypeElement) { - if (_extends(qualifiedName, (TypeElement) superClass)) { - return true; - } - } - return false; - } - - /** Get if this type implements an interface by name. */ - public boolean implementsInterface(String qualifiedName) { - return _implements(qualifiedName, this.element); - } - - /** Get if the specified type implements an interface by name. */ - public boolean implementsInterface(TypeElement e, String qualifiedName) { - return _implements(qualifiedName, e); - } - - /** Get if this type extends a class by name. */ - public boolean extendsClass(String qualifiedName) { - return _extends(qualifiedName, this.element); - } - - /** Get if the specified type extends a class by name. */ - public boolean extendsClass(TypeElement e, String qualifiedName) { - return _extends(qualifiedName, e); - } - -} diff --git a/src/main/java/org/frc5572/robotools/IOTypes.java b/src/main/java/org/frc5572/robotools/IOTypes.java deleted file mode 100644 index cc11c01..0000000 --- a/src/main/java/org/frc5572/robotools/IOTypes.java +++ /dev/null @@ -1,223 +0,0 @@ -package org.frc5572.robotools; - -/** Auto-generated list of IO interfaces and classes. */ -public class IOTypes { - - /** List of interfaces disallowed a direct path to Robot.java. */ - public static String[] ioInterfaces = { - "edu.wpi.first.wpilibj.interfaces.Gyro", - "edu.wpi.first.wpilibj.interfaces.Accelerometer", - "edu.wpi.first.wpilibj.motorcontrol.MotorController", - "com.revrobotics.SparkMaxPIDController", - "com.revrobotics.CANSensor", - "com.revrobotics.CANEncoder", - "com.revrobotics.CANAnalog", - "com.revrobotics.RelativeEncoder", - "com.revrobotics.SparkMaxAbsoluteEncoder", - "com.revrobotics.AbsoluteEncoder", - "com.revrobotics.MotorFeedbackSensor", - "com.revrobotics.CANPIDController", - "com.revrobotics.SparkMaxLimitSwitch", - "com.revrobotics.SparkMaxRelativeEncoder", - "com.revrobotics.CANDigitalInput", - "com.revrobotics.AnalogInput", - "com.revrobotics.SparkMaxAnalogSensor", - "com.ctre.phoenix6.ISerializable", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest", - "com.ctre.phoenix6.hardware.ParentDevice.MapGenerator", - "com.ctre.phoenix6.configs.ParentConfiguration", - "com.kauailabs.navx.frc.ITimestampedDataSubscriber", - }; - /** List of classes disallowed a direct path to Robot.java. */ - public static String[] ioClasses = { - "edu.wpi.first.wpilibj.AnalogEncoder", - "edu.wpi.first.wpilibj.AnalogGyro", - "edu.wpi.first.wpilibj.AnalogInput", - "edu.wpi.first.wpilibj.AnalogOutput", - "edu.wpi.first.wpilibj.AnalogPotentiometer", - "edu.wpi.first.wpilibj.AnalogTrigger", - "edu.wpi.first.wpilibj.AnalogTriggerOutput", - "edu.wpi.first.wpilibj.DMA", - "edu.wpi.first.wpilibj.DigitalSource", - "edu.wpi.first.wpilibj.DoubleSolenoid", - "edu.wpi.first.wpilibj.Encoder", - "edu.wpi.first.wpilibj.I2C", - "edu.wpi.first.wpilibj.PWM", - "edu.wpi.first.wpilibj.PneumaticsBase", - "edu.wpi.first.wpilibj.PowerDistribution", - "edu.wpi.first.wpilibj.Relay", - "edu.wpi.first.wpilibj.SPI", - "edu.wpi.first.wpilibj.SerialPort", - "edu.wpi.first.wpilibj.Solenoid", - "com.revrobotics.CANSparkBase.ExternalFollower", - "com.revrobotics.ColorSensorV3", - "com.revrobotics.jni.CANSparkMaxJNI", - "com.revrobotics.jni.RevJNIWrapper", - "com.revrobotics.jni.CANSWDLJNI", - "com.revrobotics.SparkAbsoluteEncoder", - "com.revrobotics.SparkFlexExternalEncoder", - "com.revrobotics.ColorSensorV3.RawColor", - "com.revrobotics.CANSparkMaxLowLevel.PeriodicStatus2", - "com.revrobotics.SparkAnalogSensor", - "com.revrobotics.CANSparkMaxLowLevel", - "com.revrobotics.CIEColor", - "com.revrobotics.SparkRelativeEncoder", - "com.revrobotics.CANSparkLowLevel", - "com.revrobotics.CANSparkFlex", - "com.revrobotics.ColorMatchResult", - "com.revrobotics.CANSparkMax", - "com.revrobotics.SparkMaxAlternateEncoder", - "com.revrobotics.CANSparkLowLevel.PeriodicStatus1", - "com.revrobotics.CANSparkLowLevel.PeriodicStatus2", - "com.revrobotics.CANSparkLowLevel.FollowConfig", - "com.revrobotics.SparkLimitSwitch", - "com.revrobotics.CANSparkMaxLowLevel.PeriodicStatus0", - "com.revrobotics.ColorMatch", - "com.revrobotics.SparkPIDController", - "com.revrobotics.CANSparkLowLevel.FollowConfig.Config", - "com.revrobotics.CANSparkLowLevel.PeriodicStatus0", - "com.revrobotics.REVPhysicsSim", - "com.revrobotics.CANSparkBase", - "com.revrobotics.CANSparkMaxLowLevel.PeriodicStatus1", - "com.revrobotics.DataPortConfigUtil", - "com.ctre.phoenix6.Orchestra", - "com.ctre.phoenix6.sim.TalonFXSimState", - "com.ctre.phoenix6.sim.CANcoderSimState", - "com.ctre.phoenix6.sim.Pigeon2SimState", - "com.ctre.phoenix6.jni.ErrorReportingJNI", - "com.ctre.phoenix6.jni.StatusSignalJNI", - "com.ctre.phoenix6.jni.OrchestraJNI", - "com.ctre.phoenix6.jni.CANBusJNI", - "com.ctre.phoenix6.jni.SignalLoggerJNI", - "com.ctre.phoenix6.jni.PlatformJNI", - "com.ctre.phoenix6.jni.CtreJniWrapper", - "com.ctre.phoenix6.wpiutils.AutoFeedEnable", - "com.ctre.phoenix6.wpiutils.MotorSafetyImplem", - "com.ctre.phoenix6.wpiutils.CallbackHelper", - "com.ctre.phoenix6.SignalLogger", - "com.ctre.phoenix6.Utils", - "com.ctre.phoenix6.BaseStatusSignal", - "com.ctre.phoenix6.controls.jni.ControlJNI", - "com.ctre.phoenix6.controls.jni.ControlConfigJNI", - "com.ctre.phoenix6.controls.compound.Diff_VelocityDutyCycle_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_MotionMagicTorqueCurrentFOC_Position", - "com.ctre.phoenix6.controls.compound.Diff_VelocityDutyCycle_Position", - "com.ctre.phoenix6.controls.compound.Diff_VelocityTorqueCurrentFOC_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_VelocityVoltage_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_PositionTorqueCurrentFOC_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_MotionMagicDutyCycle_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_DutyCycleOut_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_TorqueCurrentFOC_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_VoltageOut_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_PositionVoltage_Position", - "com.ctre.phoenix6.controls.compound.Diff_PositionTorqueCurrentFOC_Position", - "com.ctre.phoenix6.controls.compound.Diff_MotionMagicVoltage_Position", - "com.ctre.phoenix6.controls.compound.Diff_PositionVoltage_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_VoltageOut_Position", - "com.ctre.phoenix6.controls.compound.Diff_PositionDutyCycle_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_MotionMagicTorqueCurrentFOC_Velocity", - "com.ctre.phoenix6.controls.compound.Diff_PositionDutyCycle_Position", - "com.ctre.phoenix6.controls.compound.Diff_VelocityTorqueCurrentFOC_Position", - "com.ctre.phoenix6.controls.compound.Diff_MotionMagicDutyCycle_Position", - "com.ctre.phoenix6.controls.compound.Diff_VelocityVoltage_Position", - "com.ctre.phoenix6.controls.compound.Diff_DutyCycleOut_Position", - "com.ctre.phoenix6.controls.compound.Diff_TorqueCurrentFOC_Position", - "com.ctre.phoenix6.controls.compound.Diff_MotionMagicVoltage_Velocity", - "com.ctre.phoenix6.CANBus", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.SwerveControlRequestParameters", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.RobotCentric", - "com.ctre.phoenix6.mechanisms.swerve.SwerveDrivetrain.OdometryThread", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.SwerveDriveBrake", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.ApplyChassisSpeeds", - "com.ctre.phoenix6.mechanisms.swerve.SwerveDrivetrainConstants", - "com.ctre.phoenix6.mechanisms.swerve.SwerveModuleConstants", - "com.ctre.phoenix6.mechanisms.swerve.utility.PhoenixPIDController", - "com.ctre.phoenix6.mechanisms.swerve.SwerveDrivetrain", - "com.ctre.phoenix6.mechanisms.swerve.SwerveModule", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.PointWheelsAt", - "com.ctre.phoenix6.mechanisms.swerve.SimSwerveDrivetrain.SimSwerveModule", - "com.ctre.phoenix6.mechanisms.swerve.SwerveModuleConstantsFactory", - "com.ctre.phoenix6.mechanisms.swerve.SimSwerveDrivetrain", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.FieldCentricFacingAngle", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.FieldCentric", - "com.ctre.phoenix6.mechanisms.swerve.SwerveDrivetrain.SwerveDriveState", - "com.ctre.phoenix6.mechanisms.swerve.SwerveRequest.Idle", - "com.ctre.phoenix6.mechanisms.DifferentialMechanism", - "com.ctre.phoenix6.mechanisms.SimpleDifferentialMechanism", - "com.ctre.phoenix6.StatusSignal.SignalMeasurement", - "com.ctre.phoenix6.unmanaged.jni.UnmanagedJNI", - "com.ctre.phoenix6.unmanaged.Unmanaged", - "com.ctre.phoenix6.AllTimestamps", - "com.ctre.phoenix6.StatusSignal", - "com.ctre.phoenix6.hardware.CANcoder", - "com.ctre.phoenix6.hardware.Pigeon2", - "com.ctre.phoenix6.hardware.jni.HardwareJNI", - "com.ctre.phoenix6.hardware.ParentDevice", - "com.ctre.phoenix6.hardware.DeviceIdentifier", - "com.ctre.phoenix6.hardware.core.CorePigeon2", - "com.ctre.phoenix6.hardware.core.CoreTalonFX", - "com.ctre.phoenix6.hardware.core.CoreCANcoder", - "com.ctre.phoenix6.hardware.TalonFX", - "com.ctre.phoenix6.CANBus.CANBusStatus", - "com.ctre.phoenix6.Timestamp", - "com.ctre.phoenix6.configs.CurrentLimitsConfigs", - "com.ctre.phoenix6.configs.ClosedLoopGeneralConfigs", - "com.ctre.phoenix6.configs.TalonFXConfiguration", - "com.ctre.phoenix6.configs.DifferentialConstantsConfigs", - "com.ctre.phoenix6.configs.AudioConfigs", - "com.ctre.phoenix6.configs.VoltageConfigs", - "com.ctre.phoenix6.configs.jni.ConfigJNI", - "com.ctre.phoenix6.configs.SoftwareLimitSwitchConfigs", - "com.ctre.phoenix6.configs.ParentConfigurator", - "com.ctre.phoenix6.configs.MagnetSensorConfigs", - "com.ctre.phoenix6.configs.CANcoderConfiguration", - "com.ctre.phoenix6.configs.MotionMagicConfigs", - "com.ctre.phoenix6.configs.SlotConfigs", - "com.ctre.phoenix6.configs.ClosedLoopRampsConfigs", - "com.ctre.phoenix6.configs.MountPoseConfigs", - "com.ctre.phoenix6.configs.Pigeon2Configuration", - "com.ctre.phoenix6.configs.MotorOutputConfigs", - "com.ctre.phoenix6.configs.OpenLoopRampsConfigs", - "com.ctre.phoenix6.configs.DifferentialSensorsConfigs", - "com.ctre.phoenix6.configs.GyroTrimConfigs", - "com.ctre.phoenix6.configs.Pigeon2FeaturesConfigs", - "com.ctre.phoenix6.configs.TorqueCurrentConfigs", - "com.ctre.phoenix6.configs.TalonFXConfigurator", - "com.ctre.phoenix6.configs.Pigeon2Configurator", - "com.ctre.phoenix6.configs.FeedbackConfigs", - "com.ctre.phoenix6.configs.CANcoderConfigurator", - "com.ctre.phoenix6.configs.Slot0Configs", - "com.ctre.phoenix6.configs.CustomParamsConfigs", - "com.ctre.phoenix6.configs.HardwareLimitSwitchConfigs", - "com.ctre.phoenix6.configs.Slot1Configs", - "com.ctre.phoenix6.configs.Slot2Configs", - "com.kauailabs.vmx.AHRSJNI", - "com.kauailabs.navx.AHRSProtocol.AHRSUpdate", - "com.kauailabs.navx.IMUProtocol.YPRUpdate", - "com.kauailabs.navx.AHRSProtocol.AHRSPosTSRawUpdate", - "com.kauailabs.navx.IMUProtocol.GyroUpdate", - "com.kauailabs.navx.frc.Tracer", - "com.kauailabs.navx.frc.AHRS.BoardYawAxis", - "com.kauailabs.navx.frc.IIOCompleteNotification.BoardState", - "com.kauailabs.navx.frc.AHRS", - "com.kauailabs.navx.frc.Quaternion", - "com.kauailabs.navx.IMUProtocol.QuaternionUpdate", - "com.kauailabs.navx.AHRSProtocol.AHRS_TUNING_VAR_ID", - "com.kauailabs.navx.IMUProtocol.StreamCommand", - "com.kauailabs.navx.AHRSProtocol.AHRSPosUpdate", - "com.kauailabs.navx.AHRSProtocol.AHRS_DATA_TYPE", - "com.kauailabs.navx.IMUProtocol", - "com.kauailabs.navx.AHRSProtocol.AHRSPosTSUpdate", - "com.kauailabs.navx.AHRSProtocol", - "com.kauailabs.navx.AHRSProtocol.AHRS_DATA_ACTION", - "com.kauailabs.navx.AHRSProtocol.MagCalData", - "com.kauailabs.navx.AHRSProtocol.AHRSUpdateBase", - "com.kauailabs.navx.AHRSProtocol.DataSetResponse", - "com.kauailabs.navx.AHRSProtocol.IntegrationControl", - "com.kauailabs.navx.IMURegisters", - "com.kauailabs.navx.IMUProtocol.StreamResponse", - "com.kauailabs.navx.AHRSProtocol.BoardID", - "com.kauailabs.navx.AHRSProtocol.TuningVar", - }; -} - diff --git a/src/main/java/org/frc5572/robotools/RobotPlugin.java b/src/main/java/org/frc5572/robotools/RobotPlugin.java deleted file mode 100644 index 6b8a624..0000000 --- a/src/main/java/org/frc5572/robotools/RobotPlugin.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.frc5572.robotools; - -import javax.lang.model.util.Types; -import com.sun.source.util.JavacTask; -import com.sun.source.util.Plugin; -import com.sun.source.util.SourcePositions; -import com.sun.source.util.TaskEvent; -import com.sun.source.util.TaskListener; -import com.sun.source.util.Trees; - -/** - * Javac plugin has source info, so it's used for Github Action annotations. - */ -public class RobotPlugin implements Plugin { - - /** - * Name used in build.gradle - */ - @Override - public String getName() { - return "rchk"; - } - - /** - * Function run when loaded - */ - @Override - public void init(JavacTask task, String... arg1) { - Types types = task.getTypes(); - Trees trees = Trees.instance(task); - SourcePositions positions = trees.getSourcePositions(); - task.addTaskListener(new TaskListener() { - @Override - public void finished(TaskEvent event) { - if (event.getKind() == TaskEvent.Kind.ANALYZE) { - CompilationData data = new CompilationData(types, trees, positions, - event.getCompilationUnit(), event.getTypeElement(), null); - Checks.process(data); - } - } - }); - } - -} diff --git a/src/main/java/org/frc5572/robotools/RobotProcessor.java b/src/main/java/org/frc5572/robotools/RobotProcessor.java index 7eee768..d3ab5a0 100644 --- a/src/main/java/org/frc5572/robotools/RobotProcessor.java +++ b/src/main/java/org/frc5572/robotools/RobotProcessor.java @@ -1,11 +1,16 @@ package org.frc5572.robotools; +import java.nio.file.Path; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedOptions; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; @@ -13,24 +18,17 @@ import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; +import org.apache.commons.lang3.SystemUtils; + +import com.sun.source.util.Trees; + /** * Annotation processor for checks. Used by VS Code. */ @SupportedAnnotationTypes("*") @SupportedSourceVersion(SourceVersion.RELEASE_11) -@SupportedOptions("frc_check.skip") public class RobotProcessor extends AbstractProcessor { - private boolean processTypeElement(TypeElement typeElement) { - for (Element e3 : typeElement.getEnclosedElements()) { - if (e3 instanceof TypeElement) { - processTypeElement((TypeElement) e3); - } - } - CompilationData data = new CompilationData(processingEnv, typeElement); - return Checks.process(data); - } - private boolean hasProcessed; /** Initialization function */ @@ -40,6 +38,8 @@ public synchronized void init(ProcessingEnvironment processingEnv) { hasProcessed = false; } + public native String run(String name); + /** Process all elements. */ @Override public boolean process(Set arg0, RoundEnvironment roundEnv) { @@ -47,7 +47,8 @@ public boolean process(Set arg0, RoundEnvironment roundEn return false; } hasProcessed = true; - boolean fatal = false; + Trees trees = Trees.instance(processingEnv); + outer: for (ModuleElement mod : processingEnv.getElementUtils().getAllModuleElements()) { if (!mod.isUnnamed()) { continue; @@ -55,21 +56,72 @@ public boolean process(Set arg0, RoundEnvironment roundEn for (Element element : mod.getEnclosedElements()) { if (element instanceof PackageElement) { PackageElement packageElement = (PackageElement) element; - if (packageElement.getQualifiedName().toString().startsWith("frc.")) { - for (Element element2 : packageElement.getEnclosedElements()) { - if (element2 instanceof TypeElement) { - TypeElement typeElement = (TypeElement) element2; - fatal = fatal || processTypeElement(typeElement); + for (Element element2 : packageElement.getEnclosedElements()) { + if (element2 instanceof TypeElement) { + TypeElement typeElement = (TypeElement) element2; + var treePath = trees.getPath(typeElement); + if (treePath == null) { + continue; + } + long num_parents = typeElement.getQualifiedName().chars().filter((x) -> { + return x == ((int) '.'); + }).count(); + Path p = Path.of(treePath.getCompilationUnit().getSourceFile().getName()); + for(int i = 0; i < num_parents; i++) { + p = p.getParent(); } + p = p.getParent().getParent().getParent().getParent(); + String generated = run(p.toString()); + try { + var file = processingEnv.getFiler().createSourceFile("org.frc5572.Generated"); + try(var writer = file.openWriter()) { + writer.write(generated); + } + } catch(IOException e) { + e.printStackTrace(); + } + + break outer; } } } } } - if (fatal) { - throw new RuntimeException("Checks failed!"); - } return false; } + static { + try { + loadLib("robot_tools"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void loadLib(String name) throws IOException { + String filename; + if(SystemUtils.IS_OS_LINUX) { + filename = "lib" + name + ".so"; + } else if (SystemUtils.IS_OS_WINDOWS) { + filename = name + ".dll"; + } else { + throw new RuntimeException("Unsupported OS"); + } + Path temp = Files.createTempDirectory(""); + File file = new File(temp.toFile(), filename); + System.out.println(file.getAbsolutePath()); + InputStream in = RobotProcessor.class.getClassLoader().getResourceAsStream(filename); + byte[] buf = new byte[4096]; + try(FileOutputStream outStream = new FileOutputStream(file)) { + while(true) { + int count = in.read(buf); + if(count <= 0) { + break; + } + outStream.write(buf, 0, count); + } + } + System.load(file.getAbsolutePath()); + } + } diff --git a/src/main/java/org/frc5572/robotools/checks/Check.java b/src/main/java/org/frc5572/robotools/checks/Check.java deleted file mode 100755 index 03a76dc..0000000 --- a/src/main/java/org/frc5572/robotools/checks/Check.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.frc5572.robotools.checks; - -import org.frc5572.robotools.CompilationData; - -/** A code checker */ -@FunctionalInterface -public interface Check { - - /** Check if code is fine. Returns true if error is fatal. */ - public boolean check(CompilationData data); - -} diff --git a/src/main/java/org/frc5572/robotools/checks/IOCheck.java b/src/main/java/org/frc5572/robotools/checks/IOCheck.java deleted file mode 100755 index 001b780..0000000 --- a/src/main/java/org/frc5572/robotools/checks/IOCheck.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.frc5572.robotools.checks; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.AnnotationValue; -import javax.lang.model.element.Element; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.type.ArrayType; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.SimpleAnnotationValueVisitor9; -import org.frc5572.robotools.CompilationData; -import org.frc5572.robotools.IOTypes; - -/** Performs checks to see that Subsystems do not contain raw IO types. */ -public class IOCheck implements Check { - - private void checkType(CompilationData data, Element[] warnPos, String path, TypeElement elem, - Set skip, String post) { - for (String iface : IOTypes.ioInterfaces) { - if (data.implementsInterface(elem, iface)) { - String[] parts = iface.split("\\."); - for (Element warnElem : warnPos) { - - data.error(warnElem, path + " is a " + parts[parts.length - 1] - + " which performs IO. It should be in an IO class!"); - - } - return; - } - } - for (String class_ : IOTypes.ioClasses) { - if (data.extendsClass(elem, class_)) { - String[] parts = class_.split("\\."); - for (Element warnElem : warnPos) { - - data.error(warnElem, path + " is a " + parts[parts.length - 1] - + " which performs IO. It should be in an IO class!"); - - } - return; - } - } - if (skip.contains(elem.getQualifiedName().toString())) { - return; - } - skip.add(elem.getQualifiedName().toString()); - outer: for (var item : elem.getEnclosedElements()) { - if (item instanceof VariableElement) { - VariableElement variable = (VariableElement) item; - for (AnnotationMirror mirror : item.getAnnotationMirrors()) { - Element annotationElement = mirror.getAnnotationType().asElement(); - if (annotationElement instanceof TypeElement) { - TypeElement annotationType = (TypeElement) annotationElement; - if (annotationType.getQualifiedName().toString() - .equals("java.lang.SuppressWarnings")) { - for (var entry : mirror.getElementValues().entrySet()) { - if (entry.getValue() - .accept(new SimpleAnnotationValueVisitor9() { - - @Override - public Boolean visitArray( - List vals, Void p) { - for (AnnotationValue v : vals) { - if (v.accept(this, null)) { - return true; - } - } - return false; - } - - @Override - public Boolean visitString(String s, Void p) { - if (s.equals("IOCheck")) { - return true; - } - return false; - } - }, null)) { - continue outer; - } - } - } - } - } - String post2 = ""; - TypeMirror typeMirror = variable.asType(); - while (typeMirror instanceof ArrayType) { - typeMirror = ((ArrayType) typeMirror).getComponentType(); - post2 += "[*]"; - } - Element element = data.types.asElement(typeMirror); - Element[] newElements = new Element[warnPos.length + 1]; - for (int i = 0; i < warnPos.length; i++) { - newElements[i] = warnPos[i]; - } - newElements[warnPos.length] = variable; - if (element instanceof TypeElement) { - TypeElement type = (TypeElement) element; - checkType(data, newElements, - path + post + "." + variable.getSimpleName().toString(), type, skip, post2); - } - } - } - } - - /** Perform check. */ - @Override - public boolean check(CompilationData data) { - if (data.implementsInterface("edu.wpi.first.wpilibj.RobotBase")) { - for (var item : data.element.getEnclosedElements()) { - if (item instanceof VariableElement) { - VariableElement variable = (VariableElement) item; - String path = - data.element.getQualifiedName() + "." + variable.getSimpleName().toString(); - String post = ""; - TypeMirror typeMirror = variable.asType(); - while (typeMirror instanceof ArrayType) { - typeMirror = ((ArrayType) typeMirror).getComponentType(); - post += "[*]"; - } - Element element = data.types.asElement(typeMirror); - if (element instanceof TypeElement) { - TypeElement type = (TypeElement) element; - Set skip = new HashSet<>(); - checkType(data, new Element[] {variable}, path, type, skip, post); - } - } - } - } - return false; - } - -} diff --git a/src/main/resources/META-INF/services/com.sun.source.util.Plugin b/src/main/resources/META-INF/services/com.sun.source.util.Plugin deleted file mode 100644 index 2057c50..0000000 --- a/src/main/resources/META-INF/services/com.sun.source.util.Plugin +++ /dev/null @@ -1 +0,0 @@ -org.frc5572.robotools.RobotPlugin \ No newline at end of file diff --git a/src/main/rust/lib.rs b/src/main/rust/lib.rs new file mode 100644 index 0000000..5849c16 --- /dev/null +++ b/src/main/rust/lib.rs @@ -0,0 +1,11 @@ +use jni::{objects::{JClass, JString}, sys::jstring, JNIEnv}; + + +#[no_mangle] +pub extern "system" fn Java_org_frc5572_robotools_RobotProcessor_run<'local>(mut env: JNIEnv<'local>, class: JClass<'local>, input: JString<'local>) -> jstring { + + + + let output = env.new_string("package org.frc5572;\n\npublic class Generated {}").unwrap(); + output.into_raw() +}