From f53e566d23a7209da2143ddc556d543b10bc56c0 Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 07:43:03 +0100 Subject: [PATCH 01/12] chore: update rust edition to 2024 --- Cargo.toml | 2 +- crates/bevy_api_gen/Cargo.bootstrap.toml | 2 +- crates/bevy_api_gen/Cargo.toml | 2 +- crates/bevy_mod_scripting_core/Cargo.toml | 2 +- .../src/bindings/allocator.rs | 8 ++-- .../src/bindings/reference.rs | 46 +++++++++---------- .../src/bindings/script_system.rs | 32 +++++++------ .../bevy_mod_scripting_core/src/extractors.rs | 44 +++++++++++------- crates/bevy_mod_scripting_derive/Cargo.toml | 2 +- .../bevy_mod_scripting_functions/Cargo.toml | 2 +- .../mdbook_lad_preprocessor/Cargo.toml | 2 +- .../mdbook_lad_preprocessor/src/lib.rs | 2 +- .../tests/book_integration_tests.rs | 10 ++-- crates/ladfile/Cargo.toml | 2 +- crates/ladfile_builder/Cargo.toml | 2 +- .../bevy_mod_scripting_lua/Cargo.toml | 2 +- .../bevy_mod_scripting_rhai/Cargo.toml | 2 +- .../bevy_mod_scripting_rune/Cargo.toml | 2 +- .../Cargo.toml | 2 +- .../src/lib.rs | 28 +++++------ crates/testing_crates/test_utils/Cargo.toml | 2 +- xtask/Cargo.toml | 2 +- xtask/src/main.rs | 24 ++++++---- 23 files changed, 120 insertions(+), 104 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 01f23b1475..b861179cb3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "bevy_mod_scripting" version = "0.15.1" authors = ["Maksymilian Mozolewski "] -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" description = "Multi language scripting in Bevy" repository = "https://github.com/makspll/bevy_mod_scripting" diff --git a/crates/bevy_api_gen/Cargo.bootstrap.toml b/crates/bevy_api_gen/Cargo.bootstrap.toml index 04b6cf4532..6885d4c344 100644 --- a/crates/bevy_api_gen/Cargo.bootstrap.toml +++ b/crates/bevy_api_gen/Cargo.bootstrap.toml @@ -2,7 +2,7 @@ [package] name = "bevy_analyzer_deps_bootstrap" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] bevy_mod_scripting_core = { path = "{{BMS_CORE_PATH}}" } diff --git a/crates/bevy_api_gen/Cargo.toml b/crates/bevy_api_gen/Cargo.toml index 33ab58b9ae..54556d4fd6 100644 --- a/crates/bevy_api_gen/Cargo.toml +++ b/crates/bevy_api_gen/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bevy_api_gen" version = "0.6.0" -edition = "2021" +edition = "2024" description = "Code generator tool for bevy" license = "MIT OR Apache-2.0" repository = "https://github.com/makspll/bevy_mod_scripting" diff --git a/crates/bevy_mod_scripting_core/Cargo.toml b/crates/bevy_mod_scripting_core/Cargo.toml index e44b310d03..3aaf153f6b 100644 --- a/crates/bevy_mod_scripting_core/Cargo.toml +++ b/crates/bevy_mod_scripting_core/Cargo.toml @@ -2,7 +2,7 @@ name = "bevy_mod_scripting_core" version = "0.15.1" authors = ["Maksymilian Mozolewski "] -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" description = "Core traits and structures required for other parts of bevy_mod_scripting" repository = "https://github.com/makspll/bevy_mod_scripting" diff --git a/crates/bevy_mod_scripting_core/src/bindings/allocator.rs b/crates/bevy_mod_scripting_core/src/bindings/allocator.rs index 7914b0694b..62faf05405 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/allocator.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/allocator.rs @@ -4,8 +4,8 @@ use bevy::prelude::Resource; use bevy::{ app::{App, Plugin, PostUpdate}, diagnostic::{Diagnostic, DiagnosticPath, Diagnostics, RegisterDiagnostic}, - ecs::system::Res, - platform::collections::HashMap, + ecs::system::Res, + platform::collections::HashMap, prelude::ResMut, reflect::PartialReflect, }; @@ -15,7 +15,7 @@ use std::{ cmp::Ordering, fmt::{Display, Formatter}, hash::Hasher, - sync::{atomic::AtomicU64, Arc}, + sync::{Arc, atomic::AtomicU64}, }; /// The path used for the total number of allocations diagnostic @@ -121,7 +121,7 @@ impl ReflectAllocation { /// # Safety /// - Must only be done if no other references to this allocation exist at the same time pub unsafe fn take(self) -> Box { - std::mem::transmute(self.0) + unsafe { std::mem::transmute(self.0) } } } diff --git a/crates/bevy_mod_scripting_core/src/bindings/reference.rs b/crates/bevy_mod_scripting_core/src/bindings/reference.rs index 60c4efc3d2..72a33daf92 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/reference.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/reference.rs @@ -4,12 +4,12 @@ //! reflection gives us access to `dyn PartialReflect` objects via their type name, //! Scripting languages only really support `Clone` objects so if we want to support references, //! we need wrapper types which have owned and ref variants. -use super::{access_map::ReflectAccessId, WorldGuard}; +use super::{WorldGuard, access_map::ReflectAccessId}; use crate::{ - bindings::{with_access_read, with_access_write, ReflectAllocationId}, + ReflectAllocator, + bindings::{ReflectAllocationId, with_access_read, with_access_write}, error::InteropError, reflection_extensions::{PartialReflectExt, TypeIdExtensions}, - ReflectAllocator, }; use bevy::{ ecs::{ @@ -315,12 +315,13 @@ impl ReflectReference { .get_type_data(self.base.type_id) .ok_or_else(|| InteropError::unregistered_base(self.base.clone()))?; - let ptr = self - .base - .base_id - .clone() - .into_ptr(world.as_unsafe_world_cell()?) - .ok_or_else(|| InteropError::unregistered_base(self.base.clone()))?; + let ptr = unsafe { + self.base + .base_id + .clone() + .into_ptr(world.as_unsafe_world_cell()?) + } + .ok_or_else(|| InteropError::unregistered_base(self.base.clone()))?; // (Ptr) Safety: we use the same type_id to both // 1) retrieve the ptr @@ -369,12 +370,13 @@ impl ReflectReference { .get_type_data(self.base.type_id) .ok_or_else(|| InteropError::unregistered_base(self.base.clone()))?; - let ptr = self - .base - .base_id - .clone() - .into_ptr_mut(world.as_unsafe_world_cell()?) - .ok_or_else(|| InteropError::unregistered_base(self.base.clone()))?; + let ptr = unsafe { + self.base + .base_id + .clone() + .into_ptr_mut(world.as_unsafe_world_cell()?) + } + .ok_or_else(|| InteropError::unregistered_base(self.base.clone()))?; // (Ptr) Safety: we use the same type_id to both // 1) retrieve the ptr @@ -503,11 +505,11 @@ impl ReflectBase { match self { ReflectBase::Component(entity, component_id) => { // Safety: the caller ensures invariants hold - world.get_entity(entity).ok()?.get_by_id(component_id) + unsafe { world.get_entity(entity).ok()?.get_by_id(component_id) } } ReflectBase::Resource(component_id) => { // Safety: the caller ensures invariants hold - world.get_resource_by_id(component_id) + unsafe { world.get_resource_by_id(component_id) } } _ => None, } @@ -522,15 +524,11 @@ impl ReflectBase { match self { ReflectBase::Component(entity, component_id) => { // Safety: the caller ensures invariants hold - world - .get_entity(entity) - .ok()? - .get_mut_by_id(component_id) - .ok() + unsafe { world.get_entity(entity).ok()?.get_mut_by_id(component_id) }.ok() } ReflectBase::Resource(component_id) => { // Safety: the caller ensures invariants hold - world.get_resource_mut_by_id(component_id) + unsafe { world.get_resource_mut_by_id(component_id) } } _ => None, } @@ -645,7 +643,7 @@ mod test { use bevy::prelude::{AppTypeRegistry, World}; use crate::bindings::{ - function::script_function::AppScriptFunctionRegistry, AppReflectAllocator, + AppReflectAllocator, function::script_function::AppScriptFunctionRegistry, }; use super::*; diff --git a/crates/bevy_mod_scripting_core/src/bindings/script_system.rs b/crates/bevy_mod_scripting_core/src/bindings/script_system.rs index f1a5b3bbf0..d3a48acd98 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/script_system.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/script_system.rs @@ -1,15 +1,16 @@ //! everything to do with dynamically added script systems use super::{ + AppReflectAllocator, AppScriptComponentRegistry, ReflectBaseType, ReflectReference, + ScriptQueryBuilder, ScriptQueryResult, ScriptResourceRegistration, WorldAccessGuard, + WorldGuard, access_map::ReflectAccessId, function::{from::Val, into::IntoScript, script_function::AppScriptFunctionRegistry}, schedule::AppScheduleRegistry, script_value::ScriptValue, - AppReflectAllocator, AppScriptComponentRegistry, ReflectBaseType, ReflectReference, - ScriptQueryBuilder, ScriptQueryResult, ScriptResourceRegistration, WorldAccessGuard, - WorldGuard, }; use crate::{ + IntoScriptPluginParams, bindings::pretty_print::DisplayWithWorld, context::ContextLoadingSettings, error::{InteropError, ScriptError}, @@ -18,7 +19,6 @@ use crate::{ handler::ScriptingHandler, runtime::RuntimeContainer, script::{ScriptAttachment, ScriptContext}, - IntoScriptPluginParams, }; use bevy::{ ecs::{ @@ -29,7 +29,7 @@ use bevy::{ reflect::AppTypeRegistry, schedule::SystemSet, system::{IntoSystem, System, SystemParamValidationError}, - world::{unsafe_world_cell::UnsafeWorldCell, World}, + world::{World, unsafe_world_cell::UnsafeWorldCell}, }, platform::collections::HashSet, prelude::IntoScheduleConfigs, @@ -417,15 +417,17 @@ impl System for DynamicScriptSystem

{ let world = unsafe { world.world_mut() }; WorldAccessGuard::new_exclusive(world) } else { - WorldAccessGuard::new_non_exclusive( - world, - state.subset.clone(), - state.type_registry.clone(), - state.allocator.clone(), - state.function_registry.clone(), - state.schedule_registry.clone(), - state.component_registry.clone(), - ) + unsafe { + WorldAccessGuard::new_non_exclusive( + world, + state.subset.clone(), + state.type_registry.clone(), + state.allocator.clone(), + state.function_registry.clone(), + state.schedule_registry.clone(), + state.component_registry.clone(), + ) + } }; // TODO: cache references which don't change once we have benchmarks @@ -446,7 +448,7 @@ impl System for DynamicScriptSystem

{ } ScriptSystemParam::EntityQuery { query, components } => { // TODO: is this the right way to use this world cell for queries? - let entities = query.iter_unchecked(world).collect::>(); + let entities = unsafe { query.iter_unchecked(world) }.collect::>(); let results = entities .into_iter() .map(|entity| { diff --git a/crates/bevy_mod_scripting_core/src/extractors.rs b/crates/bevy_mod_scripting_core/src/extractors.rs index ca4abd3417..307bdddc45 100644 --- a/crates/bevy_mod_scripting_core/src/extractors.rs +++ b/crates/bevy_mod_scripting_core/src/extractors.rs @@ -5,15 +5,15 @@ use crate::bindings::pretty_print::DisplayWithWorld; use crate::handler::ScriptingHandler; use crate::{ + IntoScriptPluginParams, bindings::{ - access_map::ReflectAccessId, script_value::ScriptValue, WorldAccessGuard, WorldGuard, + WorldAccessGuard, WorldGuard, access_map::ReflectAccessId, script_value::ScriptValue, }, context::ContextLoadingSettings, error::{InteropError, ScriptError}, event::{CallbackLabel, IntoCallbackLabel}, runtime::RuntimeContainer, script::{ScriptAttachment, ScriptContext, StaticScripts}, - IntoScriptPluginParams, }; use bevy::ecs::resource::Resource; use bevy::ecs::{ @@ -102,7 +102,7 @@ unsafe impl SystemParam for ResScope<'_, T> { _change_tick: bevy::ecs::component::Tick, ) -> Self::Item<'world, 'state> { state.1 = true; - if let Some(mut r) = world.get_resource_mut::() { + if let Some(mut r) = unsafe { world.get_resource_mut::() } { std::mem::swap(&mut state.0, &mut r); } ResScope(&mut state.0) @@ -309,7 +309,7 @@ unsafe impl SystemParam for WithWorldGuard<'_, '_, T> { change_tick: bevy::ecs::component::Tick, ) -> Self::Item<'world, 'state> { // create a guard which can only access the resources/components specified by the system. - let guard = WorldAccessGuard::new_exclusive(world.world_mut()); + let guard = WorldAccessGuard::new_exclusive(unsafe { world.world_mut() }); #[allow( clippy::panic, @@ -318,16 +318,22 @@ unsafe impl SystemParam for WithWorldGuard<'_, '_, T> { for (raid, is_write) in &state.1 { if *is_write { if !guard.claim_write_access(*raid) { - panic!("System tried to access set of system params which break rust aliasing rules. Aliasing access: {}", (*raid).display_with_world(guard.clone())); + panic!( + "System tried to access set of system params which break rust aliasing rules. Aliasing access: {}", + (*raid).display_with_world(guard.clone()) + ); } } else if !guard.claim_read_access(*raid) { - panic!("System tried to access set of system params which break rust aliasing rules. Aliasing access: {}", (*raid).display_with_world(guard.clone())); + panic!( + "System tried to access set of system params which break rust aliasing rules. Aliasing access: {}", + (*raid).display_with_world(guard.clone()) + ); } } WithWorldGuard { world_guard: guard, - param: T::get_param(&mut state.0, system_meta, world, change_tick), + param: unsafe { T::get_param(&mut state.0, system_meta, world, change_tick) }, } } @@ -336,7 +342,7 @@ unsafe impl SystemParam for WithWorldGuard<'_, '_, T> { archetype: &bevy::ecs::archetype::Archetype, system_meta: &mut bevy::ecs::system::SystemMeta, ) { - T::new_archetype(&mut state.0, archetype, system_meta) + unsafe { T::new_archetype(&mut state.0, archetype, system_meta) } } fn apply( @@ -360,7 +366,7 @@ unsafe impl SystemParam for WithWorldGuard<'_, '_, T> { system_meta: &bevy::ecs::system::SystemMeta, world: bevy::ecs::world::unsafe_world_cell::UnsafeWorldCell, ) -> Result<(), SystemParamValidationError> { - T::validate_param(&state.0, system_meta, world) + unsafe { T::validate_param(&state.0, system_meta, world) } } } @@ -433,14 +439,18 @@ mod test { let system_fn = |mut guard: WithWorldGuard<(ResMut, Query<&'static Comp>)>| { let (guard, (_res, _entity)) = guard.get_mut(); assert_eq!(guard.list_accesses().len(), 2, "Expected 2 accesses"); - assert!(!guard.claim_read_access( - ReflectAccessId::for_resource::(&guard.as_unsafe_world_cell().unwrap()) - .unwrap() - )); - assert!(!guard.claim_write_access( - ReflectAccessId::for_resource::(&guard.as_unsafe_world_cell().unwrap()) - .unwrap() - )); + assert!( + !guard.claim_read_access( + ReflectAccessId::for_resource::(&guard.as_unsafe_world_cell().unwrap()) + .unwrap() + ) + ); + assert!( + !guard.claim_write_access( + ReflectAccessId::for_resource::(&guard.as_unsafe_world_cell().unwrap()) + .unwrap() + ) + ); }; let mut app = bevy::app::App::new(); diff --git a/crates/bevy_mod_scripting_derive/Cargo.toml b/crates/bevy_mod_scripting_derive/Cargo.toml index 31b06cc6c5..e39b2ff0b7 100644 --- a/crates/bevy_mod_scripting_derive/Cargo.toml +++ b/crates/bevy_mod_scripting_derive/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bevy_mod_scripting_derive" version = "0.15.1" -edition = "2021" +edition = "2024" authors = ["Maksymilian Mozolewski "] license = "MIT OR Apache-2.0" description = "Necessary functionality for Lua support with bevy_mod_scripting" diff --git a/crates/bevy_mod_scripting_functions/Cargo.toml b/crates/bevy_mod_scripting_functions/Cargo.toml index 00becce090..a99d656012 100644 --- a/crates/bevy_mod_scripting_functions/Cargo.toml +++ b/crates/bevy_mod_scripting_functions/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bevy_mod_scripting_functions" version = "0.15.1" -edition = "2021" +edition = "2024" authors = ["Maksymilian Mozolewski "] license = "MIT OR Apache-2.0" description = "Necessary functionality for Lua support with bevy_mod_scripting" diff --git a/crates/lad_backends/mdbook_lad_preprocessor/Cargo.toml b/crates/lad_backends/mdbook_lad_preprocessor/Cargo.toml index 84890d0297..9b6c1c1594 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/Cargo.toml +++ b/crates/lad_backends/mdbook_lad_preprocessor/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "mdbook_lad_preprocessor" version = "0.2.0" -edition = "2021" +edition = "2024" authors = ["Maksymilian Mozolewski "] license = "MIT OR Apache-2.0" description = "Language Agnostic Declaration (LAD) file format for the bevy_mod_scripting crate" diff --git a/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs b/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs index 481087fab5..c8d78737ca 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs @@ -168,7 +168,7 @@ impl Preprocessor for LADPreprocessor { if !errors.is_empty() { // return on first error - for error in errors { + if let Some(error) = errors.into_iter().next() { log::error!("{error}"); Err(error)?; } diff --git a/crates/lad_backends/mdbook_lad_preprocessor/tests/book_integration_tests.rs b/crates/lad_backends/mdbook_lad_preprocessor/tests/book_integration_tests.rs index c7f2406731..5ec59ac757 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/tests/book_integration_tests.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/tests/book_integration_tests.rs @@ -14,10 +14,12 @@ fn add_executable_dir_to_path() { let mut paths = std::env::split_paths(&std::env::var("PATH").expect("failed to get PATH")) .collect::>(); paths.insert(0, dir.to_owned()); - std::env::set_var( - "PATH", - std::env::join_paths(paths).expect("failed to join paths"), - ); + unsafe { + std::env::set_var( + "PATH", + std::env::join_paths(paths).expect("failed to join paths"), + ) + }; } // use cargo manifest dir diff --git a/crates/ladfile/Cargo.toml b/crates/ladfile/Cargo.toml index 1a6a488df0..bc2fa1442e 100644 --- a/crates/ladfile/Cargo.toml +++ b/crates/ladfile/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "ladfile" version = "0.5.0" -edition = "2021" +edition = "2024" authors = ["Maksymilian Mozolewski "] license = "MIT OR Apache-2.0" description = "Language Agnostic Declaration (LAD) file format for the bevy_mod_scripting crate" diff --git a/crates/ladfile_builder/Cargo.toml b/crates/ladfile_builder/Cargo.toml index 87648afc01..47e0ad56b9 100644 --- a/crates/ladfile_builder/Cargo.toml +++ b/crates/ladfile_builder/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "ladfile_builder" version = "0.5.1" -edition = "2021" +edition = "2024" authors = ["Maksymilian Mozolewski "] license = "MIT OR Apache-2.0" description = "Language Agnostic Declaration (LAD) file format for the bevy_mod_scripting crate" diff --git a/crates/languages/bevy_mod_scripting_lua/Cargo.toml b/crates/languages/bevy_mod_scripting_lua/Cargo.toml index 74bcd20c95..87cf7a56cc 100644 --- a/crates/languages/bevy_mod_scripting_lua/Cargo.toml +++ b/crates/languages/bevy_mod_scripting_lua/Cargo.toml @@ -2,7 +2,7 @@ name = "bevy_mod_scripting_lua" version = "0.15.1" authors = ["Maksymilian Mozolewski "] -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" description = "Necessary functionality for Lua support with bevy_mod_scripting" repository = "https://github.com/makspll/bevy_mod_scripting" diff --git a/crates/languages/bevy_mod_scripting_rhai/Cargo.toml b/crates/languages/bevy_mod_scripting_rhai/Cargo.toml index 7d9aa81719..3fd4aab11c 100644 --- a/crates/languages/bevy_mod_scripting_rhai/Cargo.toml +++ b/crates/languages/bevy_mod_scripting_rhai/Cargo.toml @@ -2,7 +2,7 @@ name = "bevy_mod_scripting_rhai" version = "0.15.1" authors = ["Maksymilian Mozolewski "] -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" description = "Necessary functionality for Rhai support with bevy_mod_scripting" repository = "https://github.com/makspll/bevy_mod_scripting" diff --git a/crates/languages/bevy_mod_scripting_rune/Cargo.toml b/crates/languages/bevy_mod_scripting_rune/Cargo.toml index 9b8494803a..03ed5f2778 100644 --- a/crates/languages/bevy_mod_scripting_rune/Cargo.toml +++ b/crates/languages/bevy_mod_scripting_rune/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "bevy_mod_scripting_rune" version = "0.9.0-alpha.2" -edition = "2021" +edition = "2024" license = "MIT OR Apache-2.0" description = "Necessary functionality for Rune support with bevy_mod_scripting" repository = "https://github.com/makspll/bevy_mod_scripting" diff --git a/crates/testing_crates/script_integration_test_harness/Cargo.toml b/crates/testing_crates/script_integration_test_harness/Cargo.toml index 6891665daf..feeecc9212 100644 --- a/crates/testing_crates/script_integration_test_harness/Cargo.toml +++ b/crates/testing_crates/script_integration_test_harness/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "script_integration_test_harness" version = "0.1.0" -edition = "2021" +edition = "2024" publish = false [features] diff --git a/crates/testing_crates/script_integration_test_harness/src/lib.rs b/crates/testing_crates/script_integration_test_harness/src/lib.rs index f3f8733709..aa422e8415 100644 --- a/crates/testing_crates/script_integration_test_harness/src/lib.rs +++ b/crates/testing_crates/script_integration_test_harness/src/lib.rs @@ -15,26 +15,26 @@ use bevy::{ world::FromWorld, }, log::{ - tracing::{self, event}, Level, + tracing::{self, event}, }, reflect::Reflect, }; use bevy_mod_scripting_core::{ + BMSScriptingInfrastructurePlugin, IntoScriptPluginParams, bindings::{ - pretty_print::DisplayWithWorld, CoreScriptGlobalsPlugin, ReflectAccessId, WorldAccessGuard, - WorldGuard, + CoreScriptGlobalsPlugin, ReflectAccessId, WorldAccessGuard, WorldGuard, + pretty_print::DisplayWithWorld, }, commands::CreateOrUpdateScript, error::ScriptError, extractors::HandlerContext, script::{DisplayProxy, ScriptAttachment, ScriptComponent, ScriptId}, - BMSScriptingInfrastructurePlugin, IntoScriptPluginParams, }; use bevy_mod_scripting_functions::ScriptFunctionsPlugin; -use criterion::{measurement::Measurement, BatchSize}; +use criterion::{BatchSize, measurement::Measurement}; use rand::{Rng, SeedableRng}; -use test_functions::{register_test_functions, RNG}; +use test_functions::{RNG, register_test_functions}; use test_utils::test_data::setup_integration_test; use crate::scenario::Scenario; @@ -65,8 +65,8 @@ pub fn install_test_plugin(app: &mut bevy::app::App, include_test_functions: boo #[cfg(feature = "lua")] pub fn make_test_lua_plugin() -> bevy_mod_scripting_lua::LuaScriptingPlugin { - use bevy_mod_scripting_core::{bindings::WorldContainer, ConfigureScriptPlugin}; - use bevy_mod_scripting_lua::{mlua, LuaScriptingPlugin}; + use bevy_mod_scripting_core::{ConfigureScriptPlugin, bindings::WorldContainer}; + use bevy_mod_scripting_lua::{LuaScriptingPlugin, mlua}; LuaScriptingPlugin::default().add_context_initializer( |_, ctxt: &mut bevy_mod_scripting_lua::mlua::Lua| { @@ -81,7 +81,7 @@ pub fn make_test_lua_plugin() -> bevy_mod_scripting_lua::LuaScriptingPlugin { Ok(_) => { return Err(mlua::Error::external( "Expected function to throw error, but it did not.", - )) + )); } Err(e) => ScriptError::from_mlua_error(e).display_with_world(world), }; @@ -106,12 +106,12 @@ pub fn make_test_lua_plugin() -> bevy_mod_scripting_lua::LuaScriptingPlugin { #[cfg(feature = "rhai")] pub fn make_test_rhai_plugin() -> bevy_mod_scripting_rhai::RhaiScriptingPlugin { use bevy_mod_scripting_core::{ - bindings::{ThreadWorldContainer, WorldContainer}, ConfigureScriptPlugin, + bindings::{ThreadWorldContainer, WorldContainer}, }; use bevy_mod_scripting_rhai::{ - rhai::{Dynamic, EvalAltResult, FnPtr, NativeCallContext}, RhaiScriptingPlugin, + rhai::{Dynamic, EvalAltResult, FnPtr, NativeCallContext}, }; RhaiScriptingPlugin::default().add_runtime_initializer(|runtime| { @@ -175,7 +175,7 @@ pub fn execute_integration_test(scenario: Scenario) -> Result<(), String> { manifest_dir.pop(); } - std::env::set_var("BEVY_ASSET_ROOT", manifest_dir.clone()); + unsafe { std::env::set_var("BEVY_ASSET_ROOT", manifest_dir.clone()) }; match scenario.execute(App::default()) { Ok(_) => Ok(()), @@ -205,7 +205,7 @@ pub fn run_lua_benchmark( pre_bencher.call::<()>(()).unwrap(); } c.iter(|| { - use bevy::log::{tracing, Level}; + use bevy::log::{Level, tracing}; tracing::event!(Level::TRACE, "profiling_iter {}", label); bencher.call::<()>(()).unwrap(); @@ -243,7 +243,7 @@ pub fn run_rhai_benchmark( } c.iter(|| { - use bevy::log::{tracing, Level}; + use bevy::log::{Level, tracing}; tracing::event!(Level::TRACE, "profiling_iter {}", label); let _ = runtime diff --git a/crates/testing_crates/test_utils/Cargo.toml b/crates/testing_crates/test_utils/Cargo.toml index 7adc1968dd..dbb4e24c35 100644 --- a/crates/testing_crates/test_utils/Cargo.toml +++ b/crates/testing_crates/test_utils/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "test_utils" version = "0.1.0" -edition = "2021" +edition = "2024" publish = false [dependencies] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index f3d635091e..72933d5134 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "xtask" version = "0.1.0" -edition = "2021" +edition = "2024" publish = false diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 9a43771d62..ca26acdb8c 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -851,7 +851,7 @@ impl Xtasks { let mut flags = rustflags.split(' ').collect::>(); flags.push(flag); let flags = flags.join(" "); - std::env::set_var("RUSTFLAGS", flags); + unsafe { std::env::set_var("RUSTFLAGS", flags) }; } fn run_system_command>>( @@ -1222,7 +1222,9 @@ impl Xtasks { fn check(app_settings: GlobalArgs, ide_mode: bool, kind: CheckKind) -> Result<()> { if ide_mode && kind == CheckKind::All { - bail!("Ide mode should not be used with 'all' check kind, each workspace needs to have each own individual check, for toolchains to be properly supported"); + bail!( + "Ide mode should not be used with 'all' check kind, each workspace needs to have each own individual check, for toolchains to be properly supported" + ); } match kind { @@ -1341,11 +1343,11 @@ impl Xtasks { let mut features = Features::default(); if profile { - std::env::set_var("ENABLE_PROFILING", "1"); + unsafe { std::env::set_var("ENABLE_PROFILING", "1") }; // features.push(Feature::BevyTracy); features.0.insert(Feature::ProfileWithTracy); } else { - std::env::set_var("RUST_LOG", "bevy_mod_scripting=error"); + unsafe { std::env::set_var("RUST_LOG", "bevy_mod_scripting=error") }; } let args = if let Some(name) = name { @@ -1424,7 +1426,7 @@ impl Xtasks { // .args(["--build-time"]) .args(["--threshold-measure", "latency"]) .args(["--threshold-test", "t_test"]) - .args(["--threshold-max-sample-size", "64"]) + .args(["--threshold-max-sample-size", "10"]) .args(["--threshold-upper-boundary", "0.99"]) .args(["--thresholds-reset"]); @@ -1615,7 +1617,7 @@ impl Xtasks { let coverage_dir = std::path::PathBuf::from(target_dir).join("coverage"); let coverage_file = coverage_dir.join("cargo-test-%p-%m.profraw"); - std::env::set_var("LLVM_PROFILE_FILE", coverage_file); + unsafe { std::env::set_var("LLVM_PROFILE_FILE", coverage_file) }; } fn test(app_settings: GlobalArgs, package: Option, name: Option) -> Result<()> { @@ -1812,7 +1814,9 @@ impl Xtasks { // install alsa et al if cfg!(target_os = "linux") { let sudo = if !is_root::is_root() { "sudo" } else { "" }; - let install_cmd = format!("{sudo} apt-get update && {sudo} apt-get install --no-install-recommends -y libasound2-dev libudev-dev"); + let install_cmd = format!( + "{sudo} apt-get update && {sudo} apt-get install --no-install-recommends -y libasound2-dev libudev-dev" + ); Self::run_system_command( &app_settings, "sh", @@ -2010,8 +2014,8 @@ fn pop_cargo_env() -> Result<()> { for (key, value) in env.iter() { if key.starts_with("CARGO_") && !exclude_list.contains(&(key.as_str())) { let new_key = format!("MAIN_{key}"); - std::env::set_var(new_key, value); - std::env::remove_var(key); + unsafe { std::env::set_var(new_key, value) }; + unsafe { std::env::remove_var(key) }; } } @@ -2021,7 +2025,7 @@ fn pop_cargo_env() -> Result<()> { if exclude_list.contains(var) { continue; } - std::env::remove_var(var); + unsafe { std::env::remove_var(var) }; } Ok(()) From e5e3124dd16cc4fcf771cbd156814e237114d493 Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 07:54:14 +0100 Subject: [PATCH 02/12] fix more warnings --- crates/bevy_api_gen/src/args.rs | 6 +++--- crates/bevy_api_gen/src/bin/driver.rs | 2 +- crates/bevy_api_gen/src/bin/main.rs | 26 ++++++++++++++------------ 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/crates/bevy_api_gen/src/args.rs b/crates/bevy_api_gen/src/args.rs index 2316b18b94..bc22a9221d 100644 --- a/crates/bevy_api_gen/src/args.rs +++ b/crates/bevy_api_gen/src/args.rs @@ -249,10 +249,10 @@ impl WorkspaceMeta { } pub fn set_env(&self) { - std::env::set_var(Self::CRATES_ENV_NAME, self.crates.join(",")); - std::env::set_var(Self::PLUGIN_DIR_NAME, &self.plugin_target_dir); + unsafe { std::env::set_var(Self::CRATES_ENV_NAME, self.crates.join(",")) }; + unsafe { std::env::set_var(Self::PLUGIN_DIR_NAME, &self.plugin_target_dir) }; if let Some(include_crates) = &self.include_crates { - std::env::set_var(Self::INCLUDE_CRATES_ENV_NAME, include_crates.join(",")); + unsafe { std::env::set_var(Self::INCLUDE_CRATES_ENV_NAME, include_crates.join(",")) }; } } } diff --git a/crates/bevy_api_gen/src/bin/driver.rs b/crates/bevy_api_gen/src/bin/driver.rs index a8cdbc17a8..2b5759a216 100644 --- a/crates/bevy_api_gen/src/bin/driver.rs +++ b/crates/bevy_api_gen/src/bin/driver.rs @@ -3,7 +3,7 @@ use bevy_api_gen::*; fn main() { // initially set it to high so no logs are missed, but later when we parse the args we will set it to the correct level - std::env::set_var("RUST_LOG", "trace"); + unsafe { std::env::set_var("RUST_LOG", "trace") }; env_logger::init(); rustc_plugin::driver_main(BevyAnalyzer); } diff --git a/crates/bevy_api_gen/src/bin/main.rs b/crates/bevy_api_gen/src/bin/main.rs index 202102ad10..35ef2bb528 100644 --- a/crates/bevy_api_gen/src/bin/main.rs +++ b/crates/bevy_api_gen/src/bin/main.rs @@ -2,7 +2,7 @@ use std::{ collections::HashMap, env, - fs::{create_dir_all, File}, + fs::{File, create_dir_all}, io::{BufRead, Write}, path::{Path, PathBuf}, process::{Command, Stdio}, @@ -22,7 +22,7 @@ fn main() { let args = Args::parse_from(env::args().skip(1)); if env::var("RUST_LOG").is_err() { - env::set_var("RUST_LOG", args.verbose.get_rustlog_value()); + unsafe { env::set_var("RUST_LOG", args.verbose.get_rustlog_value()) }; } env_logger::init(); @@ -175,15 +175,17 @@ fn main() { .join(" "); debug!("bootstrap paths: {bootstrap_rlibs:?}"); - env::set_var( - "RUSTFLAGS", - format!( - "{} {} -L dependency={}", - env::var("RUSTFLAGS").unwrap_or("".to_owned()), - extern_args, - bootstrap_rlibs.iter().next().unwrap().1.parent().unwrap() - ), - ); + unsafe { + env::set_var( + "RUSTFLAGS", + format!( + "{} {} -L dependency={}", + env::var("RUSTFLAGS").unwrap_or("".to_owned()), + extern_args, + bootstrap_rlibs.iter().next().unwrap().1.parent().unwrap() + ), + ) + }; } else { panic!("Could not find 'libmlua' artifact among bootstrap crate artifacts, stopping."); } @@ -193,7 +195,7 @@ fn main() { debug!("RUSTFLAGS={}", env::var("RUSTFLAGS").unwrap_or_default()); // disable incremental compilation - env::set_var("CARGO_INCREMENTAL", "0"); + unsafe { env::set_var("CARGO_INCREMENTAL", "0") }; rustc_plugin::cli_main(BevyAnalyzer); From 8e10773317cd418f299b339b706cc9184da6e453 Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 22:49:30 +0100 Subject: [PATCH 03/12] clippy lints --- .../src/derive/mod.rs | 22 +++++++-------- .../src/derive/script_bindings.rs | 28 +++++++++---------- .../src/derive/script_globals.rs | 28 +++++++++---------- 3 files changed, 36 insertions(+), 42 deletions(-) diff --git a/crates/bevy_mod_scripting_derive/src/derive/mod.rs b/crates/bevy_mod_scripting_derive/src/derive/mod.rs index b0363a2455..30835ff68a 100644 --- a/crates/bevy_mod_scripting_derive/src/derive/mod.rs +++ b/crates/bevy_mod_scripting_derive/src/derive/mod.rs @@ -5,7 +5,7 @@ mod script_globals; mod typed_through; use proc_macro2::{Span, TokenStream}; -use quote::{quote_spanned, ToTokens}; +use quote::{ToTokens, quote_spanned}; use syn::{Ident, ImplItemFn, ItemImpl}; pub use self::{ @@ -112,17 +112,15 @@ pub(crate) fn parse_docstring<'a>( attrs: impl Iterator, ) -> Option { let docs = attrs.filter_map(|attr| { - if attr.path().is_ident("doc") { - if let syn::Meta::NameValue(meta_name_value) = &attr.meta { - if let syn::Expr::Lit(expr_lit) = &meta_name_value.value { - if let syn::Lit::Str(lit_str) = &expr_lit.lit { - if lit_str.value().len() > 1 { - return Some(lit_str.value()[1..].to_string()); - } else { - return Some(lit_str.value()); - } - } - } + if attr.path().is_ident("doc") + && let syn::Meta::NameValue(meta_name_value) = &attr.meta + && let syn::Expr::Lit(expr_lit) = &meta_name_value.value + && let syn::Lit::Str(lit_str) = &expr_lit.lit + { + if lit_str.value().len() > 1 { + return Some(lit_str.value()[1..].to_string()); + } else { + return Some(lit_str.value()); } }; diff --git a/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs b/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs index df4d9b957b..72b13b8841 100644 --- a/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs +++ b/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs @@ -1,6 +1,6 @@ use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote_spanned}; -use syn::{spanned::Spanned, ItemImpl}; +use syn::{ItemImpl, spanned::Spanned}; use super::{impl_fn_to_namespace_builder_registration, is_public_impl}; @@ -155,20 +155,18 @@ impl syn::parse::Parse for Args { } } syn::Meta::NameValue(name_value) => { - if name_value.path.is_ident("bms_core_path") { - if let syn::Expr::Lit(path) = &name_value.value { - if let syn::Lit::Str(lit_str) = &path.lit { - bms_core_path = syn::parse_str(&lit_str.value())?; - continue; - } - } - } else if name_value.path.is_ident("name") { - if let syn::Expr::Lit(path) = &name_value.value { - if let syn::Lit::Str(lit_str) = &path.lit { - name = syn::parse_str(&lit_str.value())?; - continue; - } - } + if name_value.path.is_ident("bms_core_path") + && let syn::Expr::Lit(path) = &name_value.value + && let syn::Lit::Str(lit_str) = &path.lit + { + bms_core_path = syn::parse_str(&lit_str.value())?; + continue; + } else if name_value.path.is_ident("name") + && let syn::Expr::Lit(path) = &name_value.value + && let syn::Lit::Str(lit_str) = &path.lit + { + name = syn::parse_str(&lit_str.value())?; + continue; } } _ => { diff --git a/crates/bevy_mod_scripting_derive/src/derive/script_globals.rs b/crates/bevy_mod_scripting_derive/src/derive/script_globals.rs index 8ada9ee4f0..d64d851c23 100644 --- a/crates/bevy_mod_scripting_derive/src/derive/script_globals.rs +++ b/crates/bevy_mod_scripting_derive/src/derive/script_globals.rs @@ -1,6 +1,6 @@ use proc_macro2::Span; use quote::{format_ident, quote_spanned}; -use syn::{spanned::Spanned, ItemImpl}; +use syn::{ItemImpl, spanned::Spanned}; use super::{impl_fn_to_global_registry_registration, is_public_impl}; @@ -74,20 +74,18 @@ impl syn::parse::Parse for Args { for pair in pairs { match &pair { syn::Meta::NameValue(name_value) => { - if name_value.path.is_ident("bms_core_path") { - if let syn::Expr::Lit(path) = &name_value.value { - if let syn::Lit::Str(lit_str) = &path.lit { - bms_core_path = syn::parse_str(&lit_str.value())?; - continue; - } - } - } else if name_value.path.is_ident("name") { - if let syn::Expr::Lit(path) = &name_value.value { - if let syn::Lit::Str(lit_str) = &path.lit { - name = syn::parse_str(&lit_str.value())?; - continue; - } - } + if name_value.path.is_ident("bms_core_path") + && let syn::Expr::Lit(path) = &name_value.value + && let syn::Lit::Str(lit_str) = &path.lit + { + bms_core_path = syn::parse_str(&lit_str.value())?; + continue; + } else if name_value.path.is_ident("name") + && let syn::Expr::Lit(path) = &name_value.value + && let syn::Lit::Str(lit_str) = &path.lit + { + name = syn::parse_str(&lit_str.value())?; + continue; } } _ => { From 4bd6c53130915d9048b8e2cb9c1c9e90293d425e Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 22:51:23 +0100 Subject: [PATCH 04/12] cargo fmt --- benches/benchmarks.rs | 10 ++-- crates/bevy_mod_scripting_core/src/asset.rs | 18 ++++--- .../bevy_mod_scripting_core/src/commands.rs | 15 +++--- crates/bevy_mod_scripting_core/src/context.rs | 2 +- crates/bevy_mod_scripting_core/src/error.rs | 6 +-- crates/bevy_mod_scripting_core/src/event.rs | 2 +- crates/bevy_mod_scripting_core/src/handler.rs | 6 +-- crates/bevy_mod_scripting_core/src/lib.rs | 12 ++--- crates/bevy_mod_scripting_core/src/runtime.rs | 2 +- .../src/script/script_context.rs | 8 +-- .../src/derive/get_type_dependencies.rs | 4 +- .../bevy_mod_scripting_functions/src/core.rs | 6 +-- .../mdbook_lad_preprocessor/src/markdown.rs | 6 +-- .../mdbook_lad_preprocessor/src/sections.rs | 11 ++-- crates/ladfile_builder/src/lib.rs | 6 +-- crates/ladfile_builder/src/plugin.rs | 4 +- .../src/bindings/reference.rs | 6 +-- .../src/bindings/script_value.rs | 2 +- .../bevy_mod_scripting_lua/src/lib.rs | 6 +-- .../src/bindings/reference.rs | 5 +- .../src/bindings/script_value.rs | 2 +- .../bevy_mod_scripting_rhai/src/lib.rs | 8 +-- .../src/parse.rs | 7 ++- .../src/scenario.rs | 51 ++++++++++--------- .../src/test_functions.rs | 6 +-- examples/docgen.rs | 8 +-- examples/game_of_life.rs | 2 +- src/lib.rs | 2 +- src/prelude.rs | 4 +- tests/script_tests.rs | 2 +- 30 files changed, 123 insertions(+), 106 deletions(-) diff --git a/benches/benchmarks.rs b/benches/benchmarks.rs index 356441381c..427bea3e63 100644 --- a/benches/benchmarks.rs +++ b/benches/benchmarks.rs @@ -5,7 +5,7 @@ use std::{collections::HashMap, path::PathBuf, sync::LazyLock, time::Duration}; use bevy::{ log::{ - tracing, tracing::span, tracing_subscriber, tracing_subscriber::layer::SubscriberExt, Level, + Level, tracing, tracing::span, tracing_subscriber, tracing_subscriber::layer::SubscriberExt, }, reflect::Reflect, }; @@ -13,7 +13,7 @@ use bevy_mod_scripting_core::bindings::{ FromScript, IntoScript, Mut, Ref, ReflectReference, ScriptValue, Val, }; use criterion::{ - criterion_main, measurement::Measurement, BatchSize, BenchmarkFilter, BenchmarkGroup, Criterion, + BatchSize, BenchmarkFilter, BenchmarkGroup, Criterion, criterion_main, measurement::Measurement, }; use regex::Regex; use script_integration_test_harness::{ @@ -21,7 +21,7 @@ use script_integration_test_harness::{ run_lua_benchmark, run_plugin_script_load_benchmark, run_rhai_benchmark, test_functions::rand::Rng, }; -use test_utils::{discover_all_tests, Test}; +use test_utils::{Test, discover_all_tests}; static ENABLE_PROFILING: LazyLock = LazyLock::new(|| std::env::var("ENABLE_PROFILING").is_ok()); @@ -147,7 +147,9 @@ fn script_benchmarks(criterion: &mut Criterion, filter: Option) { fn maybe_with_profiler(f: impl Fn(bool)) { if *ENABLE_PROFILING { - println!("profiling enabled, make sure to run tracy. If using it across windows/WSL you can use something like `tracy-capture.exe -o output.tracy -a localhost` on windows"); + println!( + "profiling enabled, make sure to run tracy. If using it across windows/WSL you can use something like `tracy-capture.exe -o output.tracy -a localhost` on windows" + ); // set global tracing subscriber so bevy doesn't set it itself first let subscriber = tracing_subscriber::Registry::default(); let tracy_layer = tracing_tracy::TracyLayer::default(); diff --git a/crates/bevy_mod_scripting_core/src/asset.rs b/crates/bevy_mod_scripting_core/src/asset.rs index 5c09fec0cf..021851a7e0 100644 --- a/crates/bevy_mod_scripting_core/src/asset.rs +++ b/crates/bevy_mod_scripting_core/src/asset.rs @@ -3,12 +3,12 @@ use std::borrow::Cow; use crate::{ + IntoScriptPluginParams, LanguageExtensions, ScriptComponent, ScriptingSystemSet, StaticScripts, commands::{CreateOrUpdateScript, DeleteScript}, context::ContextLoadingSettings, error::ScriptError, event::ScriptEvent, script::{ContextKey, DisplayProxy, ScriptAttachment}, - IntoScriptPluginParams, LanguageExtensions, ScriptComponent, ScriptingSystemSet, StaticScripts, }; use bevy::{ app::{App, Last}, @@ -155,12 +155,18 @@ impl AssetLoader for ScriptAssetLoader { }) }); if language == Language::Lua && cfg!(not(feature = "mlua")) { - warn_once!("Script {:?} is a Lua script but the {:?} feature is not enabled; the script will not be evaluated.", - load_context.path().display(), "mlua"); + warn_once!( + "Script {:?} is a Lua script but the {:?} feature is not enabled; the script will not be evaluated.", + load_context.path().display(), + "mlua" + ); } if language == Language::Rhai && cfg!(not(feature = "rhai")) { - warn_once!("Script {:?} is a Rhai script but the {:?} feature is not enabled; the script will not be evaluated.", - load_context.path().display(), "rhai"); + warn_once!( + "Script {:?} is a Rhai script but the {:?} feature is not enabled; the script will not be evaluated.", + load_context.path().display(), + "rhai" + ); } let asset = ScriptAsset { content: content.into_boxed_slice(), @@ -348,9 +354,9 @@ mod tests { use std::path::PathBuf; use bevy::{ + MinimalPlugins, app::App, asset::{AssetApp, AssetPath, AssetPlugin, AssetServer, Assets, Handle, LoadState}, - MinimalPlugins, }; use super::*; diff --git a/crates/bevy_mod_scripting_core/src/commands.rs b/crates/bevy_mod_scripting_core/src/commands.rs index 59a63e1010..07b894a7e4 100644 --- a/crates/bevy_mod_scripting_core/src/commands.rs +++ b/crates/bevy_mod_scripting_core/src/commands.rs @@ -1,6 +1,7 @@ //! Commands for creating, updating and deleting scripts use crate::{ + IntoScriptPluginParams, ScriptContext, asset::ScriptAsset, bindings::{ScriptValue, WorldGuard}, context::ScriptingLoader, @@ -9,10 +10,9 @@ use crate::{ CallbackLabel, IntoCallbackLabel, OnScriptLoaded, OnScriptReloaded, OnScriptUnloaded, ScriptCallbackResponseEvent, ScriptEvent, }, - extractors::{with_handler_system_state, HandlerContext}, + extractors::{HandlerContext, with_handler_system_state}, handler::{handle_script_errors, send_callback_response}, script::{DisplayProxy, ScriptAttachment, StaticScripts}, - IntoScriptPluginParams, ScriptContext, }; use bevy::{ asset::{Assets, Handle}, @@ -334,11 +334,12 @@ impl CreateOrUpdateScript

{ Err(err) => { handle_script_errors( guard, - vec![err - .clone() - .with_script(script_id.display()) - .with_context(P::LANGUAGE) - .with_context(phrase)] + vec![ + err.clone() + .with_script(script_id.display()) + .with_context(P::LANGUAGE) + .with_context(phrase), + ] .into_iter(), ); Err(err) diff --git a/crates/bevy_mod_scripting_core/src/context.rs b/crates/bevy_mod_scripting_core/src/context.rs index 61166335f2..c4f6a4010c 100644 --- a/crates/bevy_mod_scripting_core/src/context.rs +++ b/crates/bevy_mod_scripting_core/src/context.rs @@ -1,10 +1,10 @@ //! Traits and types for managing script contexts. use crate::{ + IntoScriptPluginParams, bindings::{ThreadWorldContainer, WorldContainer, WorldGuard}, error::ScriptError, script::ScriptAttachment, - IntoScriptPluginParams, }; use bevy::prelude::Resource; diff --git a/crates/bevy_mod_scripting_core/src/error.rs b/crates/bevy_mod_scripting_core/src/error.rs index a5548654b0..8cf43c38c2 100644 --- a/crates/bevy_mod_scripting_core/src/error.rs +++ b/crates/bevy_mod_scripting_core/src/error.rs @@ -2,15 +2,15 @@ use crate::script::DisplayProxy; use crate::{ + ScriptAsset, bindings::{ + ReflectBaseType, ReflectReference, access_map::{DisplayCodeLocation, ReflectAccessId}, function::namespace::Namespace, pretty_print::DisplayWithWorld, script_value::ScriptValue, - ReflectBaseType, ReflectReference, }, script::ContextKey, - ScriptAsset, }; use bevy::{ asset::{AssetPath, Handle}, @@ -1624,7 +1624,7 @@ mod test { use bevy::prelude::{AppTypeRegistry, World}; use crate::bindings::{ - function::script_function::AppScriptFunctionRegistry, AppReflectAllocator, WorldGuard, + AppReflectAllocator, WorldGuard, function::script_function::AppScriptFunctionRegistry, }; use super::*; diff --git a/crates/bevy_mod_scripting_core/src/event.rs b/crates/bevy_mod_scripting_core/src/event.rs index c4f7ee10e0..62ca10d8af 100644 --- a/crates/bevy_mod_scripting_core/src/event.rs +++ b/crates/bevy_mod_scripting_core/src/event.rs @@ -3,11 +3,11 @@ use std::sync::Arc; use crate::{ + IntoScriptPluginParams, asset::Language, bindings::script_value::ScriptValue, error::ScriptError, script::{ScriptAttachment, ScriptContext, ScriptId}, - IntoScriptPluginParams, }; use bevy::{asset::Handle, ecs::entity::Entity, prelude::Event, reflect::Reflect}; use parking_lot::Mutex; diff --git a/crates/bevy_mod_scripting_core/src/handler.rs b/crates/bevy_mod_scripting_core/src/handler.rs index 6408a508b9..6fd387b767 100644 --- a/crates/bevy_mod_scripting_core/src/handler.rs +++ b/crates/bevy_mod_scripting_core/src/handler.rs @@ -1,8 +1,9 @@ //! Contains the logic for handling script callback events use crate::{ + IntoScriptPluginParams, Language, bindings::{ - pretty_print::DisplayWithWorld, script_value::ScriptValue, ThreadWorldContainer, - WorldAccessGuard, WorldContainer, WorldGuard, + ThreadWorldContainer, WorldAccessGuard, WorldContainer, WorldGuard, + pretty_print::DisplayWithWorld, script_value::ScriptValue, }, context::ContextPreHandlingInitializer, error::ScriptError, @@ -12,7 +13,6 @@ use crate::{ }, extractors::{HandlerContext, WithWorldGuard}, script::ScriptAttachment, - IntoScriptPluginParams, Language, }; use bevy::{ ecs::{ diff --git a/crates/bevy_mod_scripting_core/src/lib.rs b/crates/bevy_mod_scripting_core/src/lib.rs index f87320ffde..5899e691a6 100644 --- a/crates/bevy_mod_scripting_core/src/lib.rs +++ b/crates/bevy_mod_scripting_core/src/lib.rs @@ -8,21 +8,21 @@ use crate::{ event::ScriptErrorEvent, }; use asset::{ - configure_asset_systems, configure_asset_systems_for_plugin, Language, ScriptAsset, - ScriptAssetLoader, + Language, ScriptAsset, ScriptAssetLoader, configure_asset_systems, + configure_asset_systems_for_plugin, }; use bevy::{platform::collections::HashMap, prelude::*}; use bindings::{ - function::script_function::AppScriptFunctionRegistry, garbage_collector, - schedule::AppScheduleRegistry, script_value::ScriptValue, AppReflectAllocator, - DynamicScriptComponentPlugin, ReflectAllocator, ReflectReference, ScriptTypeRegistration, + AppReflectAllocator, DynamicScriptComponentPlugin, ReflectAllocator, ReflectReference, + ScriptTypeRegistration, function::script_function::AppScriptFunctionRegistry, + garbage_collector, schedule::AppScheduleRegistry, script_value::ScriptValue, }; use commands::{AddStaticScript, RemoveStaticScript}; use context::{Context, ContextInitializer, ContextLoadingSettings, ContextPreHandlingInitializer}; use error::ScriptError; use event::{ScriptCallbackEvent, ScriptCallbackResponseEvent, ScriptEvent}; use handler::HandlerFn; -use runtime::{initialize_runtime, Runtime, RuntimeContainer, RuntimeInitializer, RuntimeSettings}; +use runtime::{Runtime, RuntimeContainer, RuntimeInitializer, RuntimeSettings, initialize_runtime}; use script::{ContextPolicy, ScriptComponent, ScriptContext, StaticScripts}; pub mod asset; diff --git a/crates/bevy_mod_scripting_core/src/runtime.rs b/crates/bevy_mod_scripting_core/src/runtime.rs index a4d925fbd7..6f747e150b 100644 --- a/crates/bevy_mod_scripting_core/src/runtime.rs +++ b/crates/bevy_mod_scripting_core/src/runtime.rs @@ -1,7 +1,7 @@ //! "Runtime" here refers to the execution evironment of scripts. This might be the VM executing bytecode or the interpreter executing source code. //! The important thing is that there is only one runtime which is used to execute all scripts of a particular type or `context`. -use crate::{error::ScriptError, IntoScriptPluginParams}; +use crate::{IntoScriptPluginParams, error::ScriptError}; use bevy::{ ecs::system::ResMut, prelude::{Res, Resource}, diff --git a/crates/bevy_mod_scripting_core/src/script/script_context.rs b/crates/bevy_mod_scripting_core/src/script/script_context.rs index ccaa578bf7..934a09dc54 100644 --- a/crates/bevy_mod_scripting_core/src/script/script_context.rs +++ b/crates/bevy_mod_scripting_core/src/script/script_context.rs @@ -377,9 +377,11 @@ mod tests { assert!(script_context.get(&context_key).is_some()); // insert another into the same context - assert!(script_context - .insert_resident(context_key2.clone()) - .unwrap()); + assert!( + script_context + .insert_resident(context_key2.clone()) + .unwrap() + ); assert!(script_context.contains(&context_key2)); let mut residents = script_context.residents(&context_key2).collect::>(); diff --git a/crates/bevy_mod_scripting_derive/src/derive/get_type_dependencies.rs b/crates/bevy_mod_scripting_derive/src/derive/get_type_dependencies.rs index cb4ace9389..bc1d0734c5 100644 --- a/crates/bevy_mod_scripting_derive/src/derive/get_type_dependencies.rs +++ b/crates/bevy_mod_scripting_derive/src/derive/get_type_dependencies.rs @@ -1,6 +1,6 @@ use proc_macro2::TokenStream; -use quote::{quote_spanned, ToTokens}; -use syn::{parse_quote, parse_quote_spanned, DeriveInput, WhereClause}; +use quote::{ToTokens, quote_spanned}; +use syn::{DeriveInput, WhereClause, parse_quote, parse_quote_spanned}; /// Generate a GetTypeDependencies impl like below: /// For type: diff --git a/crates/bevy_mod_scripting_functions/src/core.rs b/crates/bevy_mod_scripting_functions/src/core.rs index 3904897bb6..3eefea720a 100644 --- a/crates/bevy_mod_scripting_functions/src/core.rs +++ b/crates/bevy_mod_scripting_functions/src/core.rs @@ -18,6 +18,8 @@ use bevy_mod_scripting_core::{ use bevy_mod_scripting_derive::script_bindings; use bevy_system_reflection::{ReflectSchedule, ReflectSystem}; use bindings::{ + ReflectReference, ScriptComponentRegistration, ScriptQueryBuilder, ScriptQueryResult, + ScriptResourceRegistration, ScriptTypeRegistration, ThreadWorldContainer, WorldContainer, function::{ from::{Ref, Val}, from_ref::FromScriptRef, @@ -26,8 +28,6 @@ use bindings::{ }, pretty_print::DisplayWithWorld, script_value::ScriptValue, - ReflectReference, ScriptComponentRegistration, ScriptQueryBuilder, ScriptQueryResult, - ScriptResourceRegistration, ScriptTypeRegistration, ThreadWorldContainer, WorldContainer, }; use error::InteropError; use reflection_extensions::{PartialReflectExt, TypeIdExtensions}; @@ -441,7 +441,7 @@ impl World { "creating a system in {} scripting language", ctxt.language() ), - )) + )); } }; #[allow(unreachable_code)] diff --git a/crates/lad_backends/mdbook_lad_preprocessor/src/markdown.rs b/crates/lad_backends/mdbook_lad_preprocessor/src/markdown.rs index c577cdacbc..5ae984fec3 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/src/markdown.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/src/markdown.rs @@ -404,11 +404,7 @@ impl MarkdownBuilder { fn separator(&self) -> &'static str { if self.inline { - if self.tight_inline { - "" - } else { - " " - } + if self.tight_inline { "" } else { " " } } else { "\n\n" } diff --git a/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs b/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs index 412a59a130..ddd4e8a8d9 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs @@ -1,6 +1,6 @@ use crate::{ argument_visitor::MarkdownArgumentVisitor, - markdown::{markdown_substring, IntoMarkdown, Markdown, MarkdownBuilder, TableBuilder}, + markdown::{IntoMarkdown, Markdown, MarkdownBuilder, TableBuilder, markdown_substring}, markdown_vec, }; use ladfile::{ @@ -267,8 +267,9 @@ impl<'a> Section<'a> { builder.row(markdown_vec![ Markdown::new_paragraph("Global Functions").code(), Markdown::Link { - text: - Box::new("Documents all the global functions present in the bindings"), + text: Box::new( + "Documents all the global functions present in the bindings" + ), url: format!( "./{}/functions.md", linkify_filename(title.clone()) @@ -279,7 +280,9 @@ impl<'a> Section<'a> { builder.row(markdown_vec![ Markdown::new_paragraph("Globals").code(), Markdown::Link { - text: Box::new("Documents all global variables present in the bindings"), + text: Box::new( + "Documents all global variables present in the bindings" + ), url: format!( "./{}/globals.md", linkify_filename(title.clone()) diff --git a/crates/ladfile_builder/src/lib.rs b/crates/ladfile_builder/src/lib.rs index 75e71b979f..52686c9b63 100644 --- a/crates/ladfile_builder/src/lib.rs +++ b/crates/ladfile_builder/src/lib.rs @@ -4,18 +4,18 @@ pub mod plugin; use bevy::{ecs::world::World, log, platform::collections::HashSet}; use bevy_mod_scripting_core::{ bindings::{ + MarkAsCore, MarkAsGenerated, MarkAsSignificant, ReflectReference, function::{ namespace::Namespace, script_function::{ DynamicScriptFunction, DynamicScriptFunctionMut, FunctionCallContext, }, }, - MarkAsCore, MarkAsGenerated, MarkAsSignificant, ReflectReference, }, docgen::{ + TypedThrough, info::FunctionInfo, typed_through::{ThroughTypeInfo, TypedWrapperKind, UntypedWrapperKind}, - TypedThrough, }, match_by_type, }; @@ -855,11 +855,11 @@ mod test { use bevy_mod_scripting_core::{ bindings::{ + Union, Val, function::{ from::Ref, namespace::{GlobalNamespace, IntoNamespace}, }, - Union, Val, }, docgen::info::GetFunctionInfo, }; diff --git a/crates/ladfile_builder/src/plugin.rs b/crates/ladfile_builder/src/plugin.rs index 7a1c2f4619..984a47542c 100644 --- a/crates/ladfile_builder/src/plugin.rs +++ b/crates/ladfile_builder/src/plugin.rs @@ -7,11 +7,11 @@ use bevy::{ ecs::{prelude::Resource, reflect::AppTypeRegistry, system::Res, world::World}, }; use bevy_mod_scripting_core::bindings::{ + IntoNamespace, function::{namespace::Namespace, script_function::AppScriptFunctionRegistry}, globals::AppScriptGlobalsRegistry, - IntoNamespace, }; -use ladfile::{default_importance, LadTypeKind}; +use ladfile::{LadTypeKind, default_importance}; use crate::LadFileBuilder; diff --git a/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs b/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs index 3308647d50..e84c6b8cfd 100644 --- a/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs +++ b/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs @@ -1,8 +1,8 @@ -use super::script_value::{LuaScriptValue, LUA_CALLER_CONTEXT}; +use super::script_value::{LUA_CALLER_CONTEXT, LuaScriptValue}; use bevy_mod_scripting_core::{ bindings::{ - pretty_print::DisplayWithWorld, script_value::ScriptValue, ReflectReference, - ThreadWorldContainer, WorldContainer, + ReflectReference, ThreadWorldContainer, WorldContainer, pretty_print::DisplayWithWorld, + script_value::ScriptValue, }, error::InteropError, reflection_extensions::TypeIdExtensions, diff --git a/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs b/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs index 238e56cd92..88f238cb9a 100644 --- a/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs +++ b/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs @@ -112,7 +112,7 @@ impl FromLua for LuaScriptValue { from: value.type_name(), to: "ScriptValue".to_owned(), message: Some("unsupported value type".to_owned()), - }) + }); } } .into()) diff --git a/crates/languages/bevy_mod_scripting_lua/src/lib.rs b/crates/languages/bevy_mod_scripting_lua/src/lib.rs index a2f0487f46..60c38478b5 100644 --- a/crates/languages/bevy_mod_scripting_lua/src/lib.rs +++ b/crates/languages/bevy_mod_scripting_lua/src/lib.rs @@ -5,10 +5,11 @@ use bevy::{ ecs::{entity::Entity, world::World}, }; use bevy_mod_scripting_core::{ + IntoScriptPluginParams, ScriptingPlugin, asset::{Language, ScriptAsset}, bindings::{ - function::namespace::Namespace, globals::AppScriptGlobalsRegistry, - script_value::ScriptValue, ThreadWorldContainer, WorldContainer, + ThreadWorldContainer, WorldContainer, function::namespace::Namespace, + globals::AppScriptGlobalsRegistry, script_value::ScriptValue, }, context::{ContextInitializer, ContextPreHandlingInitializer}, error::ScriptError, @@ -16,7 +17,6 @@ use bevy_mod_scripting_core::{ reflection_extensions::PartialReflectExt, runtime::RuntimeSettings, script::{ContextPolicy, ScriptAttachment}, - IntoScriptPluginParams, ScriptingPlugin, }; use bindings::{ reference::{LuaReflectReference, LuaStaticReflectReference}, diff --git a/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs b/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs index 8e8d288ef8..a7cf399b91 100644 --- a/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs +++ b/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs @@ -1,8 +1,9 @@ use super::script_value::{FromDynamic, FunctionWithReceiver, IntoDynamic, RHAI_CALLER_CONTEXT}; use bevy_mod_scripting_core::{ bindings::{ + ReflectReference, ThreadWorldContainer, WorldContainer, function::script_function::DynamicScriptFunctionMut, pretty_print::DisplayWithWorld, - script_value::ScriptValue, ReflectReference, ThreadWorldContainer, WorldContainer, + script_value::ScriptValue, }, error::InteropError, reflection_extensions::TypeIdExtensions, @@ -304,7 +305,7 @@ impl CustomType for RhaiReflectReference { { Ok(func) => { return FunctionWithReceiver::curry(func, self_.clone().into()) - .into_dynamic() + .into_dynamic(); } Err(string) => ScriptValue::String(string), } diff --git a/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs b/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs index d2e793ea0c..f5448bffc6 100644 --- a/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs +++ b/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs @@ -124,7 +124,7 @@ impl IntoDynamic for ScriptValue { "Interop error in rhai script".to_string(), interop_error.into(), ) - .into()) + .into()); } }) } diff --git a/crates/languages/bevy_mod_scripting_rhai/src/lib.rs b/crates/languages/bevy_mod_scripting_rhai/src/lib.rs index 0d92298cbc..3100849ae7 100644 --- a/crates/languages/bevy_mod_scripting_rhai/src/lib.rs +++ b/crates/languages/bevy_mod_scripting_rhai/src/lib.rs @@ -8,10 +8,11 @@ use bevy::{ ecs::{entity::Entity, world::World}, }; use bevy_mod_scripting_core::{ + IntoScriptPluginParams, ScriptingPlugin, asset::{Language, ScriptAsset}, bindings::{ - function::namespace::Namespace, globals::AppScriptGlobalsRegistry, - script_value::ScriptValue, ThreadWorldContainer, WorldContainer, + ThreadWorldContainer, WorldContainer, function::namespace::Namespace, + globals::AppScriptGlobalsRegistry, script_value::ScriptValue, }, context::{ContextInitializer, ContextPreHandlingInitializer}, error::ScriptError, @@ -19,7 +20,6 @@ use bevy_mod_scripting_core::{ reflection_extensions::PartialReflectExt, runtime::RuntimeSettings, script::{ContextPolicy, DisplayProxy, ScriptAttachment}, - IntoScriptPluginParams, ScriptingPlugin, }; use bindings::{ reference::{ReservedKeyword, RhaiReflectReference, RhaiStaticReflectReference}, @@ -27,7 +27,7 @@ use bindings::{ }; use parking_lot::RwLock; pub use rhai; -use rhai::{CallFnOptions, Dynamic, Engine, EvalAltResult, Scope, AST}; +use rhai::{AST, CallFnOptions, Dynamic, Engine, EvalAltResult, Scope}; /// Bindings for rhai. pub mod bindings; diff --git a/crates/testing_crates/script_integration_test_harness/src/parse.rs b/crates/testing_crates/script_integration_test_harness/src/parse.rs index 1b6142e274..d68946ec09 100644 --- a/crates/testing_crates/script_integration_test_harness/src/parse.rs +++ b/crates/testing_crates/script_integration_test_harness/src/parse.rs @@ -12,7 +12,7 @@ use bevy_mod_scripting_core::{ script::{ContextPolicy, ScriptAttachment}, }; -use crate::scenario::{ScenarioContext, ScenarioStep, SCENARIO_SELF_LANGUAGE_NAME}; +use crate::scenario::{SCENARIO_SELF_LANGUAGE_NAME, ScenarioContext, ScenarioStep}; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, PartialEq, Eq)] pub enum ScenarioSchedule { @@ -438,7 +438,10 @@ mod tests { language: None, }; let flat_string = step.to_flat_string().unwrap(); - assert_eq!(flat_string, "AssertCallbackSuccess attachment=\"EntityScript\", entity=\"entity1\", expect_string_value=\"null\", label=\"OnTest\", language=\"null\", script=\"script1\""); + assert_eq!( + flat_string, + "AssertCallbackSuccess attachment=\"EntityScript\", entity=\"entity1\", expect_string_value=\"null\", label=\"OnTest\", language=\"null\", script=\"script1\"" + ); } #[test] diff --git a/crates/testing_crates/script_integration_test_harness/src/scenario.rs b/crates/testing_crates/script_integration_test_harness/src/scenario.rs index c24a4e2b8e..4567a7bcd0 100644 --- a/crates/testing_crates/script_integration_test_harness/src/scenario.rs +++ b/crates/testing_crates/script_integration_test_harness/src/scenario.rs @@ -1,5 +1,5 @@ use crate::{install_test_plugin, parse::*}; -use anyhow::{anyhow, Context, Error}; +use anyhow::{Context, Error, anyhow}; use bevy::ecs::entity::Entity; use bevy::ecs::system::Command; use bevy::prelude::IntoSystem; @@ -18,13 +18,13 @@ use bevy_mod_scripting_core::commands::{AddStaticScript, RemoveStaticScript}; use bevy_mod_scripting_core::event::ScriptEvent; use bevy_mod_scripting_core::script::ContextPolicy; use bevy_mod_scripting_core::script::ScriptContext; +use bevy_mod_scripting_core::{ConfigureScriptPlugin, LanguageExtensions}; use bevy_mod_scripting_core::{ asset::ScriptAsset, event::{CallbackLabel, IntoCallbackLabel, ScriptCallbackEvent, ScriptCallbackResponseEvent}, handler::event_handler, script::{ScriptAttachment, ScriptComponent}, }; -use bevy_mod_scripting_core::{ConfigureScriptPlugin, LanguageExtensions}; use std::borrow::Cow; use std::collections::VecDeque; use std::{ @@ -512,12 +512,13 @@ impl ScenarioStep { } _ => { return Err(anyhow!( - "Scenario step InstallPlugin is not supported for the current plugin type: '{}'", - context.current_script_language - .as_ref() - .map(|l| l.to_string()) - .unwrap_or_else(|| "None".to_string()) - )); + "Scenario step InstallPlugin is not supported for the current plugin type: '{}'", + context + .current_script_language + .as_ref() + .map(|l| l.to_string()) + .unwrap_or_else(|| "None".to_string()) + )); } } return Ok(()); @@ -584,9 +585,9 @@ impl ScenarioStep { .add_handler::(context.current_script_language.clone(), app), _ => { return Err(anyhow!( - "callback label: {} is not allowed, you can only use one of a set of labels", - label - )) + "callback label: {} is not allowed, you can only use one of a set of labels", + label + )); } } } @@ -637,12 +638,14 @@ impl ScenarioStep { if ScriptValue::String(Cow::Owned(expected_string.clone())) != *val { return Err(anyhow!( - "Callback '{}' for attachment: '{}' expected: {}, but got: {}", - label, - script.to_string(), - expected_string, - val.display_with_world(WorldGuard::new_exclusive(app.world_mut())) - )); + "Callback '{}' for attachment: '{}' expected: {}, but got: {}", + label, + script.to_string(), + expected_string, + val.display_with_world(WorldGuard::new_exclusive( + app.world_mut() + )) + )); } } } @@ -704,10 +707,10 @@ impl ScenarioStep { }; } else { return Err(anyhow!( - "Script asset with id '{}' not found in context. Tried reloading from path: {}", - script.id(), - path.display() - )); + "Script asset with id '{}' not found in context. Tried reloading from path: {}", + script.id(), + path.display() + )); } } ScenarioStep::AssertNoCallbackResponsesEmitted => { @@ -756,9 +759,9 @@ impl ScenarioStep { .residents_len(&script), _ => { return Err(anyhow!( - "Scenario step AssertContextRemoved is not supported for the current plugin type: '{:?}'", - context.current_script_language - )); + "Scenario step AssertContextRemoved is not supported for the current plugin type: '{:?}'", + context.current_script_language + )); } }; diff --git a/crates/testing_crates/script_integration_test_harness/src/test_functions.rs b/crates/testing_crates/script_integration_test_harness/src/test_functions.rs index 138a46373f..a73aa6e39b 100644 --- a/crates/testing_crates/script_integration_test_harness/src/test_functions.rs +++ b/crates/testing_crates/script_integration_test_harness/src/test_functions.rs @@ -12,13 +12,13 @@ use bevy::{ use bevy_mod_scripting_core::{ asset::Language, bindings::{ + DynamicScriptFunction, ReflectReference, ScriptComponentRegistration, + ScriptResourceRegistration, ScriptTypeRegistration, ScriptValue, function::{ namespace::{GlobalNamespace, NamespaceBuilder}, script_function::{DynamicScriptFunctionMut, FunctionCallContext}, }, pretty_print::DisplayWithWorld, - DynamicScriptFunction, ReflectReference, ScriptComponentRegistration, - ScriptResourceRegistration, ScriptTypeRegistration, ScriptValue, }, error::InteropError, }; @@ -98,7 +98,7 @@ pub fn register_test_functions(world: &mut App) { Ok(_) => { return Err(InteropError::external_error( "Expected function to throw error, but it did not.".into(), - )) + )); } Err(e) => e.display_with_world(world.clone()), }; diff --git a/examples/docgen.rs b/examples/docgen.rs index 27a1932e13..2294fa5d1e 100644 --- a/examples/docgen.rs +++ b/examples/docgen.rs @@ -1,11 +1,11 @@ use bevy::ecs::reflect::AppTypeRegistry; -use bevy::{app::App, DefaultPlugins}; +use bevy::{DefaultPlugins, app::App}; use bevy_mod_scripting::ScriptFunctionsPlugin; +use bevy_mod_scripting_core::BMSScriptingInfrastructurePlugin; use bevy_mod_scripting_core::bindings::function::script_function::AppScriptFunctionRegistry; -use bevy_mod_scripting_core::bindings::globals::core::CoreScriptGlobalsPlugin; use bevy_mod_scripting_core::bindings::globals::AppScriptGlobalsRegistry; -use bevy_mod_scripting_core::BMSScriptingInfrastructurePlugin; -use ladfile_builder::plugin::{generate_lad_file, LadFileSettings, ScriptingDocgenPlugin}; +use bevy_mod_scripting_core::bindings::globals::core::CoreScriptGlobalsPlugin; +use ladfile_builder::plugin::{LadFileSettings, ScriptingDocgenPlugin, generate_lad_file}; fn main() -> std::io::Result<()> { let mut app = App::new(); diff --git a/examples/game_of_life.rs b/examples/game_of_life.rs index 0f87bae6ae..3acb6af3b6 100644 --- a/examples/game_of_life.rs +++ b/examples/game_of_life.rs @@ -14,7 +14,7 @@ use bevy::{ }, window::{PrimaryWindow, WindowResized}, }; -use bevy_console::{make_layer, AddConsoleCommand, ConsoleCommand, ConsoleOpen, ConsolePlugin}; +use bevy_console::{AddConsoleCommand, ConsoleCommand, ConsoleOpen, ConsolePlugin, make_layer}; use bevy_mod_scripting::{core::bindings::AllocatorDiagnosticPlugin, prelude::*}; use clap::Parser; diff --git a/src/lib.rs b/src/lib.rs index 421a3bdb81..6f6e83fd94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,7 +23,7 @@ pub mod rhai { use bevy::app::plugin_group; use bevy_mod_scripting_core::{ - bindings::CoreScriptGlobalsPlugin, BMSScriptingInfrastructurePlugin, + BMSScriptingInfrastructurePlugin, bindings::CoreScriptGlobalsPlugin, }; pub use bevy_mod_scripting_derive::*; pub use bevy_mod_scripting_functions::*; diff --git a/src/prelude.rs b/src/prelude.rs index a9eb6990c3..bfb525cf08 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,17 +1,17 @@ pub use crate::{BMSPlugin, ScriptFunctionsPlugin}; pub use bevy_mod_scripting_core::{ + ConfigureScriptAssetSettings, ConfigureScriptPlugin, IntoScriptPluginParams, asset::{Language, ScriptAsset}, bindings::{ + CoreScriptGlobalsPlugin, function::namespace::{GlobalNamespace, NamespaceBuilder}, script_value::ScriptValue, - CoreScriptGlobalsPlugin, }, callback_labels, commands::{AddStaticScript, DeleteScript}, event::ScriptCallbackEvent, handler::event_handler, script::{ScriptComponent, ScriptId}, - ConfigureScriptAssetSettings, ConfigureScriptPlugin, IntoScriptPluginParams, }; #[cfg(feature = "lua")] diff --git a/tests/script_tests.rs b/tests/script_tests.rs index 039a965dee..e3a58d383a 100644 --- a/tests/script_tests.rs +++ b/tests/script_tests.rs @@ -5,7 +5,7 @@ use std::path::PathBuf; use libtest_mimic::{Arguments, Failed, Trial}; use script_integration_test_harness::{execute_integration_test, scenario::Scenario}; -use test_utils::{discover_all_tests, Test}; +use test_utils::{Test, discover_all_tests}; trait TestExecutor { fn execute(self) -> Result<(), Failed>; From 74c84872f443f08dd55ad726019908040f1f5268 Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 23:08:36 +0100 Subject: [PATCH 05/12] more clippy --- .../src/bindings/function/from_ref.rs | 52 +++++++++---------- .../src/bindings/reference.rs | 39 +++++++------- .../src/bindings/script_value.rs | 22 ++++---- .../bevy_mod_scripting_core/src/commands.rs | 9 ++-- .../src/reflection_extensions.rs | 14 ++--- .../src/script/context_key.rs | 9 ++-- .../src/derive/script_bindings.rs | 13 ++--- 7 files changed, 80 insertions(+), 78 deletions(-) diff --git a/crates/bevy_mod_scripting_core/src/bindings/function/from_ref.rs b/crates/bevy_mod_scripting_core/src/bindings/function/from_ref.rs index 3308392750..e5fcbea798 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/function/from_ref.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/function/from_ref.rs @@ -1,10 +1,10 @@ //! Contains the [`FromScriptRef`] trait and its implementations. use crate::{ - bindings::{match_by_type, FromScript, WorldGuard}, + ScriptValue, + bindings::{FromScript, WorldGuard, match_by_type}, error::InteropError, reflection_extensions::TypeInfoExtensions, - ScriptValue, }; use bevy::reflect::{ DynamicEnum, DynamicList, DynamicMap, DynamicTuple, DynamicVariant, Map, PartialReflect, @@ -87,34 +87,34 @@ impl FromScriptRef for Box { return Ok(Box::new(dynamic_enum)); } - if let Some(inner_list_type) = type_info.list_inner_type() { - if let ScriptValue::List(vec) = value { - let mut dynamic_list = DynamicList::default(); - for item in vec { - let inner = Self::from_script_ref(inner_list_type, item, world.clone())?; - dynamic_list.push_box(inner); - } - - dynamic_list.set_represented_type(Some(type_info)); - return Ok(Box::new(dynamic_list)); + if let Some(inner_list_type) = type_info.list_inner_type() + && let ScriptValue::List(vec) = value + { + let mut dynamic_list = DynamicList::default(); + for item in vec { + let inner = Self::from_script_ref(inner_list_type, item, world.clone())?; + dynamic_list.push_box(inner); } + + dynamic_list.set_represented_type(Some(type_info)); + return Ok(Box::new(dynamic_list)); } - if let Some((key_type, val_type)) = type_info.map_inner_types() { - if let ScriptValue::Map(map) = value { - let mut dynamic_map = DynamicMap::default(); - for (key, val) in map { - let key = Self::from_script_ref( - key_type, - ScriptValue::String(key.into()), - world.clone(), - )?; - let val = Self::from_script_ref(val_type, val, world.clone())?; - dynamic_map.insert_boxed(key, val); - } - dynamic_map.set_represented_type(Some(type_info)); - return Ok(Box::new(dynamic_map)); + if let Some((key_type, val_type)) = type_info.map_inner_types() + && let ScriptValue::Map(map) = value + { + let mut dynamic_map = DynamicMap::default(); + for (key, val) in map { + let key = Self::from_script_ref( + key_type, + ScriptValue::String(key.into()), + world.clone(), + )?; + let val = Self::from_script_ref(val_type, val, world.clone())?; + dynamic_map.insert_boxed(key, val); } + dynamic_map.set_represented_type(Some(type_info)); + return Ok(Box::new(dynamic_map)); } match value { diff --git a/crates/bevy_mod_scripting_core/src/bindings/reference.rs b/crates/bevy_mod_scripting_core/src/bindings/reference.rs index 72a33daf92..2e9a02f833 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/reference.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/reference.rs @@ -189,27 +189,28 @@ impl ReflectReference { &self, world: WorldGuard, ) -> Result, InteropError> { - if let ReflectBase::Owned(id) = &self.base.base_id { - if self.reflect_path.is_empty() && id.strong_count() == 0 { - let allocator = world.allocator(); - let mut allocator = allocator.write(); - let arc = allocator - .remove(id) - .ok_or_else(|| InteropError::garbage_collected_allocation(self.clone()))?; - - let access_id = ReflectAccessId::for_allocation(id.clone()); - if world.claim_write_access(access_id) { - // Safety: we claim write access, nobody else is accessing this - if unsafe { &*arc.get_ptr() }.try_as_reflect().is_some() { - // Safety: the only accesses exist in this function - unsafe { world.release_access(access_id) }; - return Ok(unsafe { arc.take() }); - } else { - unsafe { world.release_access(access_id) }; - } + if let ReflectBase::Owned(id) = &self.base.base_id + && self.reflect_path.is_empty() + && id.strong_count() == 0 + { + let allocator = world.allocator(); + let mut allocator = allocator.write(); + let arc = allocator + .remove(id) + .ok_or_else(|| InteropError::garbage_collected_allocation(self.clone()))?; + + let access_id = ReflectAccessId::for_allocation(id.clone()); + if world.claim_write_access(access_id) { + // Safety: we claim write access, nobody else is accessing this + if unsafe { &*arc.get_ptr() }.try_as_reflect().is_some() { + // Safety: the only accesses exist in this function + unsafe { world.release_access(access_id) }; + return Ok(unsafe { arc.take() }); + } else { + unsafe { world.release_access(access_id) }; } - allocator.insert(id.clone(), arc); } + allocator.insert(id.clone(), arc); } self.with_reflect(world.clone(), |r| { diff --git a/crates/bevy_mod_scripting_core/src/bindings/script_value.rs b/crates/bevy_mod_scripting_core/src/bindings/script_value.rs index 7c15721940..8ffd24cb57 100644 --- a/crates/bevy_mod_scripting_core/src/bindings/script_value.rs +++ b/crates/bevy_mod_scripting_core/src/bindings/script_value.rs @@ -7,8 +7,8 @@ use bevy::reflect::{OffsetAccess, ParsedPath, Reflect}; use crate::error::InteropError; use super::{ - function::script_function::{DynamicScriptFunction, DynamicScriptFunctionMut}, ReflectReference, + function::script_function::{DynamicScriptFunction, DynamicScriptFunctionMut}, }; /// An abstraction of values that can be passed to and from scripts. @@ -178,17 +178,17 @@ impl TryFrom for ParsedPath { value, "Floating point numbers cannot be used to index into reflected values" .to_owned(), - )) + )); } ScriptValue::String(cow) => { - if let Some(tuple_struct_index) = cow.strip_prefix("_") { - if let Ok(index) = tuple_struct_index.parse::() { - let parsed_path = ParsedPath::from(vec![OffsetAccess { - access: bevy::reflect::Access::TupleIndex(index), - offset: Some(1), - }]); - return Ok(parsed_path); - } + if let Some(tuple_struct_index) = cow.strip_prefix("_") + && let Ok(index) = tuple_struct_index.parse::() + { + let parsed_path = ParsedPath::from(vec![OffsetAccess { + access: bevy::reflect::Access::TupleIndex(index), + offset: Some(1), + }]); + return Ok(parsed_path); } match cow { @@ -202,7 +202,7 @@ impl TryFrom for ParsedPath { return Err(InteropError::invalid_index( ScriptValue::Reference(reflect_reference), "References cannot be used to index into reflected values".to_owned(), - )) + )); } _ => ParsedPath(vec![]), }) diff --git a/crates/bevy_mod_scripting_core/src/commands.rs b/crates/bevy_mod_scripting_core/src/commands.rs index 07b894a7e4..d9018dab0f 100644 --- a/crates/bevy_mod_scripting_core/src/commands.rs +++ b/crates/bevy_mod_scripting_core/src/commands.rs @@ -293,14 +293,13 @@ impl CreateOrUpdateScript

{ match result_context_to_insert { Ok(maybe_context) => { - if let Some(context) = maybe_context { - if handler_ctxt + if let Some(context) = maybe_context + && handler_ctxt .script_context .insert(&attachment, context) .is_err() - { - warn!("Unable to insert script context for {}.", attachment); - } + { + warn!("Unable to insert script context for {}.", attachment); } // mark as resident in the context diff --git a/crates/bevy_mod_scripting_core/src/reflection_extensions.rs b/crates/bevy_mod_scripting_core/src/reflection_extensions.rs index b1b661b766..947c948d96 100644 --- a/crates/bevy_mod_scripting_core/src/reflection_extensions.rs +++ b/crates/bevy_mod_scripting_core/src/reflection_extensions.rs @@ -138,13 +138,13 @@ impl PartialReflectExt for T { } fn as_option(&self) -> Result, InteropError> { - if let bevy::reflect::ReflectRef::Enum(e) = self.reflect_ref() { - if e.is_type(Some("core"), "Option") { - if let Some(field) = e.field_at(0) { - return Ok(Some(field)); - } else { - return Ok(None); - } + if let bevy::reflect::ReflectRef::Enum(e) = self.reflect_ref() + && e.is_type(Some("core"), "Option") + { + if let Some(field) = e.field_at(0) { + return Ok(Some(field)); + } else { + return Ok(None); } } diff --git a/crates/bevy_mod_scripting_core/src/script/context_key.rs b/crates/bevy_mod_scripting_core/src/script/context_key.rs index 688ed7e900..3e12544948 100644 --- a/crates/bevy_mod_scripting_core/src/script/context_key.rs +++ b/crates/bevy_mod_scripting_core/src/script/context_key.rs @@ -137,11 +137,12 @@ impl ContextKey { /// If a script handle is present and is strong, convert it to a weak /// handle. pub fn into_weak(mut self) -> Self { - if let Some(script) = &self.script { - if script.is_strong() { - self.script = Some(script.clone_weak()); - } + if let Some(script) = &self.script + && script.is_strong() + { + self.script = Some(script.clone_weak()); } + self } } diff --git a/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs b/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs index 72b13b8841..104e726244 100644 --- a/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs +++ b/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs @@ -155,12 +155,13 @@ impl syn::parse::Parse for Args { } } syn::Meta::NameValue(name_value) => { - if name_value.path.is_ident("bms_core_path") - && let syn::Expr::Lit(path) = &name_value.value - && let syn::Lit::Str(lit_str) = &path.lit - { - bms_core_path = syn::parse_str(&lit_str.value())?; - continue; + if name_value.path.is_ident("bms_core_path") { + if let syn::Expr::Lit(path) = &name_value.value { + if let syn::Lit::Str(lit_str) = &path.lit { + bms_core_path = syn::parse_str(&lit_str.value())?; + continue; + } + } } else if name_value.path.is_ident("name") && let syn::Expr::Lit(path) = &name_value.value && let syn::Lit::Str(lit_str) = &path.lit From 44c78cd1b8595d4a3b39e2e2eba4aae93a498565 Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 23:21:31 +0100 Subject: [PATCH 06/12] disable toolchain override --- .github/workflows/bevy_mod_scripting.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/bevy_mod_scripting.yml b/.github/workflows/bevy_mod_scripting.yml index d5c2ffd51c..8f9a16a2ea 100644 --- a/.github/workflows/bevy_mod_scripting.yml +++ b/.github/workflows/bevy_mod_scripting.yml @@ -124,7 +124,14 @@ jobs: if: ${{ needs.check-needs-run.outputs.any-changes == 'true' && (matrix.run_args.run_on_forks || needs.check-is-fork.outputs.is_fork != 'true') }} with: toolchain: stable - override: true + override: false + - name: Print versions + if: ${{ needs.check-needs-run.outputs.any-changes == 'true' && (matrix.run_args.run_on_forks || needs.check-is-fork.outputs.is_fork != 'true') }} + run: | + echo "Rust version: $(rustc --version)" + echo "Clippy version: $(cargo clippy --version)" + echo "Active toolchain: $(rustup show active-toolchain)" + continue-on-error: true - name: Rust Cache if: ${{ needs.check-needs-run.outputs.any-changes == 'true' && (matrix.run_args.run_on_forks || needs.check-is-fork.outputs.is_fork != 'true') }} uses: Swatinem/rust-cache@v2.7.7 From 8e8f4f7d69ca5cfb144ec60262448df10e9e544c Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 23:23:15 +0100 Subject: [PATCH 07/12] another clippy --- .../src/derive/script_bindings.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs b/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs index 104e726244..72b13b8841 100644 --- a/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs +++ b/crates/bevy_mod_scripting_derive/src/derive/script_bindings.rs @@ -155,13 +155,12 @@ impl syn::parse::Parse for Args { } } syn::Meta::NameValue(name_value) => { - if name_value.path.is_ident("bms_core_path") { - if let syn::Expr::Lit(path) = &name_value.value { - if let syn::Lit::Str(lit_str) = &path.lit { - bms_core_path = syn::parse_str(&lit_str.value())?; - continue; - } - } + if name_value.path.is_ident("bms_core_path") + && let syn::Expr::Lit(path) = &name_value.value + && let syn::Lit::Str(lit_str) = &path.lit + { + bms_core_path = syn::parse_str(&lit_str.value())?; + continue; } else if name_value.path.is_ident("name") && let syn::Expr::Lit(path) = &name_value.value && let syn::Lit::Str(lit_str) = &path.lit From ab5a247ffc1d586bd8996493956a111bef122db1 Mon Sep 17 00:00:00 2001 From: makspll Date: Tue, 19 Aug 2025 23:37:52 +0100 Subject: [PATCH 08/12] add rustfmt component --- xtask/src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ca26acdb8c..5b8da93ebf 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1880,6 +1880,7 @@ impl Xtasks { "rustc-dev", "clippy", "llvm-tools-preview", + "rustfmt", ]; // install components for the stable and nightly toolchains From 3842c5c24dbb4901b81ea16b35b9f6a15c6b36e1 Mon Sep 17 00:00:00 2001 From: makspll Date: Thu, 21 Aug 2025 21:33:15 +0100 Subject: [PATCH 09/12] bump nightly, ditch rustc_plugin --- build_scripts.sh | 16 -- crates/bevy_api_gen/Cargo.toml | 1 - crates/bevy_api_gen/rust-toolchain.toml | 2 +- crates/bevy_api_gen/src/bin/driver.rs | 4 +- crates/bevy_api_gen/src/bin/main.rs | 19 +- crates/bevy_api_gen/src/callback.rs | 10 +- crates/bevy_api_gen/src/driver/license | 21 ++ crates/bevy_api_gen/src/driver/mod.rs | 236 ++++++++++++++++++ crates/bevy_api_gen/src/driver/plugin.rs | 55 ++++ crates/bevy_api_gen/src/feature_graph.rs | 8 +- crates/bevy_api_gen/src/import_path.rs | 10 +- crates/bevy_api_gen/src/lib.rs | 14 +- crates/bevy_api_gen/src/meta.rs | 20 +- .../bevy_api_gen/src/passes/cache_traits.rs | 2 +- crates/bevy_api_gen/src/passes/codegen.rs | 17 +- .../src/passes/find_methods_and_fields.rs | 145 +++++++---- .../src/passes/find_trait_impls.rs | 2 +- .../src/passes/populate_template_data.rs | 10 +- crates/bevy_api_gen/src/plugin.rs | 32 ++- crates/bevy_api_gen/src/template.rs | 6 +- .../mdbook_lad_preprocessor/src/lib.rs | 29 +-- xtask/templates/settings.json.tera | 5 +- 22 files changed, 504 insertions(+), 160 deletions(-) delete mode 100755 build_scripts.sh create mode 100644 crates/bevy_api_gen/src/driver/license create mode 100644 crates/bevy_api_gen/src/driver/mod.rs create mode 100644 crates/bevy_api_gen/src/driver/plugin.rs diff --git a/build_scripts.sh b/build_scripts.sh deleted file mode 100755 index ca664cab67..0000000000 --- a/build_scripts.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -WORKSPACE_DIR="$PWD" - -cd "$(dirname "$0")" -# if the path is in /bevy_api_gen then we run the codegen check - -if [[ "$WORKSPACE_DIR" == *"/bevy_api_gen"* ]]; then - # save output to file as well as stdout and stderr - cargo check --quiet --workspace --message-format=json --all-targets --keep-going -elif [[ "$WORKSPACE_DIR" == *"/xtask"* ]]; then - cd "$WORKSPACE_DIR" - cargo check --quiet --workspace --message-format=json --all-targets --keep-going -else - cd "$WORKSPACE_DIR" - cargo check --quiet --workspace --message-format=json --all-targets --keep-going -fi \ No newline at end of file diff --git a/crates/bevy_api_gen/Cargo.toml b/crates/bevy_api_gen/Cargo.toml index 54556d4fd6..fef474bd65 100644 --- a/crates/bevy_api_gen/Cargo.toml +++ b/crates/bevy_api_gen/Cargo.toml @@ -37,7 +37,6 @@ rustc_private = true [dependencies] log = "0.4" env_logger = "0.11" -rustc_plugin = "0.12.0-nightly-2024-12-15" indexmap = "2" cargo_metadata = "0.18" serde_json = "1" diff --git a/crates/bevy_api_gen/rust-toolchain.toml b/crates/bevy_api_gen/rust-toolchain.toml index 6b75379add..d03a332d52 100644 --- a/crates/bevy_api_gen/rust-toolchain.toml +++ b/crates/bevy_api_gen/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] components = ["clippy", "rust-src", "rustc-dev", "llvm-tools"] -channel = "nightly-2024-12-15" +channel = "nightly-2025-06-27" diff --git a/crates/bevy_api_gen/src/bin/driver.rs b/crates/bevy_api_gen/src/bin/driver.rs index 2b5759a216..3539a91a63 100644 --- a/crates/bevy_api_gen/src/bin/driver.rs +++ b/crates/bevy_api_gen/src/bin/driver.rs @@ -1,9 +1,9 @@ #![feature(rustc_private)] -use bevy_api_gen::*; +use bevy_api_gen::{driver::driver_main, *}; fn main() { // initially set it to high so no logs are missed, but later when we parse the args we will set it to the correct level unsafe { std::env::set_var("RUST_LOG", "trace") }; env_logger::init(); - rustc_plugin::driver_main(BevyAnalyzer); + driver_main(BevyAnalyzer); } diff --git a/crates/bevy_api_gen/src/bin/main.rs b/crates/bevy_api_gen/src/bin/main.rs index 35ef2bb528..7725a3f27e 100644 --- a/crates/bevy_api_gen/src/bin/main.rs +++ b/crates/bevy_api_gen/src/bin/main.rs @@ -99,7 +99,7 @@ fn main() { } bevy_api_gen::Command::ListTemplates => { for template in TemplateKind::VARIANTS { - println!("{}", template); + println!("{template}"); } return; } @@ -109,7 +109,7 @@ fn main() { api_name, } => { let tera = configure_tera("no_crate", &templates); - info!("Collecting from: {}", output); + info!("Collecting from: {output}"); if !output.is_dir() { panic!("Output is not a directory"); } @@ -197,7 +197,7 @@ fn main() { // disable incremental compilation unsafe { env::set_var("CARGO_INCREMENTAL", "0") }; - rustc_plugin::cli_main(BevyAnalyzer); + driver::cli_main(BevyAnalyzer); // just making sure the temp dir lives until everything is done drop(temp_dir); @@ -292,7 +292,7 @@ fn build_bootstrap( } } Err(e) => { - panic!("Failed to wait on cargo build process: {}", e); + panic!("Failed to wait on cargo build process: {e}"); } } @@ -307,12 +307,11 @@ fn process_artifact( let file_name = artifact.file_name().unwrap_or_default(); let lib_name = file_name.split('-').next().unwrap().strip_prefix("lib"); - if let Some(lib_name) = lib_name { - if BOOTSTRAP_DEPS.contains(&lib_name) - && artifact.extension().is_some_and(|ext| ext == "rlib") - { - bootstrap_rlibs.insert(lib_name.to_owned(), artifact); - } + if let Some(lib_name) = lib_name + && BOOTSTRAP_DEPS.contains(&lib_name) + && artifact.extension().is_some_and(|ext| ext == "rlib") + { + bootstrap_rlibs.insert(lib_name.to_owned(), artifact); } } diff --git a/crates/bevy_api_gen/src/callback.rs b/crates/bevy_api_gen/src/callback.rs index 8be9e21fa3..fd2f645f82 100644 --- a/crates/bevy_api_gen/src/callback.rs +++ b/crates/bevy_api_gen/src/callback.rs @@ -2,7 +2,9 @@ use log::{info, trace}; use rustc_hir::def_id::LOCAL_CRATE; use tera::Context; -use crate::{Args, TemplateKind, WorkspaceMeta, ALL_PASSES}; +use crate::{ + ALL_PASSES, Args, TemplateKind, WorkspaceMeta, modifying_file_loader::ModifyingFileLoader, +}; pub(crate) struct BevyAnalyzerCallbacks { args: Args, @@ -59,7 +61,7 @@ impl rustc_driver::Callbacks for BevyAnalyzerCallbacks { // tera environment for import processor let tera = crate::configure_tera(tcx.crate_name(LOCAL_CRATE).as_str(), &templates_dir); - info!("Using meta directories: {:?}", meta_dirs); + info!("Using meta directories: {meta_dirs:?}"); let mut ctxt = crate::BevyCtxt::new( tcx, &meta_dirs, @@ -89,4 +91,8 @@ impl rustc_driver::Callbacks for BevyAnalyzerCallbacks { rustc_driver::Compilation::Continue } + + fn config(&mut self, config: &mut rustc_interface::interface::Config) { + config.file_loader = Some(Box::new(ModifyingFileLoader)); + } } diff --git a/crates/bevy_api_gen/src/driver/license b/crates/bevy_api_gen/src/driver/license new file mode 100644 index 0000000000..9adf82f055 --- /dev/null +++ b/crates/bevy_api_gen/src/driver/license @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Cognitive Engineering Lab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/crates/bevy_api_gen/src/driver/mod.rs b/crates/bevy_api_gen/src/driver/mod.rs new file mode 100644 index 0000000000..f9069efe80 --- /dev/null +++ b/crates/bevy_api_gen/src/driver/mod.rs @@ -0,0 +1,236 @@ +//! The module dealing with how the CLI interacts with each instantiation of the +//! plugin across the workspace. + +mod plugin; + +use std::{ + env, + ops::Deref, + path::{Path, PathBuf}, + process::{Command, Stdio, exit}, +}; + +pub use plugin::*; +use rustc_session::{EarlyDiagCtxt, config::ErrorOutputType}; + +pub const RUN_ON_ALL_CRATES: &str = "RUSTC_PLUGIN_ALL_TARGETS"; +pub const CARGO_VERBOSE: &str = "CARGO_VERBOSE"; + +/// The top-level function that should be called in your user-facing binary. +pub fn cli_main(plugin: T) { + if env::args().any(|arg| arg == "-V") { + println!("{}", plugin.version()); + return; + } + + let metadata = cargo_metadata::MetadataCommand::new() + .no_deps() + .other_options(["--all-features".to_string(), "--offline".to_string()]) + .exec() + .unwrap(); + let plugin_subdir = format!("plugin-{}", env!("RUSTC_CHANNEL")); + let target_dir = metadata.target_directory.join(plugin_subdir); + + let args = plugin.args(&target_dir); + + let mut cmd = Command::new("cargo"); + cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit()); + + let mut path = env::current_exe() + .expect("current executable path invalid") + .with_file_name(plugin.driver_name().as_ref()); + + if cfg!(windows) { + path.set_extension("exe"); + } + + cmd.env("RUSTC_WORKSPACE_WRAPPER", path) + .args(["check", "--target-dir"]) + .arg(&target_dir); + + if env::var(CARGO_VERBOSE).is_ok() { + cmd.arg("-vv"); + } else { + cmd.arg("-q"); + } + + match args.filter { + CrateFilter::AllCrates | CrateFilter::OnlyWorkspace => { + cmd.arg("--all"); + match args.filter { + CrateFilter::AllCrates => { + cmd.env(RUN_ON_ALL_CRATES, ""); + } + CrateFilter::OnlyWorkspace => {} + } + } + } + + let args_str = serde_json::to_string(&args.args).unwrap(); + log::debug!("{PLUGIN_ARGS}={args_str}"); + cmd.env(PLUGIN_ARGS, args_str); + + plugin.modify_cargo(&mut cmd, &args.args); + + let exit_status = cmd.status().expect("failed to wait for cargo?"); + + exit(exit_status.code().unwrap_or(-1)); +} + +// use std::{ +// env, +// ops::Deref, +// path::{Path, PathBuf}, +// process::{Command, exit}, +// }; + +// use rustc_session::{EarlyDiagCtxt, config::ErrorOutputType}; +// use rustc_tools_util::VersionInfo; + +// use super::plugin::{PLUGIN_ARGS, RustcPlugin}; + +/// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If +/// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`. +fn arg_value<'a, T: Deref>( + args: &'a [T], + find_arg: &str, + pred: impl Fn(&str) -> bool, +) -> Option<&'a str> { + let mut args = args.iter().map(Deref::deref); + while let Some(arg) = args.next() { + let mut arg = arg.splitn(2, '='); + if arg.next() != Some(find_arg) { + continue; + } + + match arg.next().or_else(|| args.next()) { + Some(v) if pred(v) => return Some(v), + _ => {} + } + } + None +} + +fn toolchain_path(home: Option, toolchain: Option) -> Option { + home.and_then(|home| { + toolchain.map(|toolchain| { + let mut path = PathBuf::from(home); + path.push("toolchains"); + path.push(toolchain); + path + }) + }) +} + +fn get_sysroot(orig_args: &[String]) -> (bool, String) { + // Get the sysroot, looking from most specific to this invocation to the least: + // - command line + // - runtime environment + // - SYSROOT + // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN + // - sysroot from rustc in the path + // - compile-time environment + // - SYSROOT + // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN + let sys_root_arg = arg_value(orig_args, "--sysroot", |_| true); + let have_sys_root_arg = sys_root_arg.is_some(); + let sys_root = sys_root_arg + .map(PathBuf::from) + .or_else(|| std::env::var("MIRI_SYSROOT").ok().map(PathBuf::from)) + .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from)) + .or_else(|| { + let home = std::env::var("RUSTUP_HOME") + .or_else(|_| std::env::var("MULTIRUST_HOME")) + .ok(); + let toolchain = std::env::var("RUSTUP_TOOLCHAIN") + .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN")) + .ok(); + toolchain_path(home, toolchain) + }) + .or_else(|| { + Command::new("rustc") + .arg("--print") + .arg("sysroot") + .output() + .ok() + .and_then(|out| String::from_utf8(out.stdout).ok()) + .map(|s| PathBuf::from(s.trim())) + }) + .or_else(|| option_env!("SYSROOT").map(PathBuf::from)) + .or_else(|| { + let home = option_env!("RUSTUP_HOME") + .or(option_env!("MULTIRUST_HOME")) + .map(ToString::to_string); + let toolchain = option_env!("RUSTUP_TOOLCHAIN") + .or(option_env!("MULTIRUST_TOOLCHAIN")) + .map(ToString::to_string); + toolchain_path(home, toolchain) + }) + .map(|pb| pb.to_string_lossy().to_string()) + .expect( + "need to specify SYSROOT env var during clippy compilation, or use rustup or multirust", + ); + (have_sys_root_arg, sys_root) +} + +struct DefaultCallbacks; +impl rustc_driver::Callbacks for DefaultCallbacks {} + +/// The top-level function that should be called by your internal driver binary. +pub fn driver_main(plugin: T) { + let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default()); + rustc_driver::init_rustc_env_logger(&early_dcx); + + exit(rustc_driver::catch_with_exit_code(move || { + let mut orig_args: Vec = env::args().collect(); + + let (have_sys_root_arg, sys_root) = get_sysroot(&orig_args); + + if orig_args.iter().any(|a| a == "--version" || a == "-V") { + println!("{}", plugin.version()); + exit(0); + } + + // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument. + // We're invoking the compiler programmatically, so we ignore this + let wrapper_mode = + orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref()); + + if wrapper_mode { + // we still want to be able to invoke it normally though + orig_args.remove(1); + } + + // this conditional check for the --sysroot flag is there so users can call + // the driver directly without having to pass --sysroot or anything + let mut args: Vec = orig_args.clone(); + if !have_sys_root_arg { + args.extend(["--sysroot".into(), sys_root]); + }; + + // On a given invocation of rustc, we have to decide whether to act as rustc, + // or actually execute the plugin. There are two conditions for executing the plugin: + // 1. Either we're supposed to run on all crates, or CARGO_PRIMARY_PACKAGE is set. + // 2. --print is NOT passed, since Cargo does that to get info about rustc. + let primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok(); + let run_on_all_crates = env::var(RUN_ON_ALL_CRATES).is_ok(); + let normal_rustc = arg_value(&args, "--print", |_| true).is_some(); + + let run_plugin = !normal_rustc && (run_on_all_crates || primary_package); + + if run_plugin { + log::debug!("Running plugin..."); + let plugin_args: T::Args = + serde_json::from_str(&env::var(PLUGIN_ARGS).unwrap()).unwrap(); + plugin.run(args, plugin_args); + } else { + log::debug!( + "Running normal Rust. Relevant variables:\ +normal_rustc={normal_rustc}, \ +run_on_all_crates={run_on_all_crates}, \ +primary_package={primary_package}" + ); + rustc_driver_impl::run_compiler(&args, &mut DefaultCallbacks); + } + })) +} diff --git a/crates/bevy_api_gen/src/driver/plugin.rs b/crates/bevy_api_gen/src/driver/plugin.rs new file mode 100644 index 0000000000..a15cf3164b --- /dev/null +++ b/crates/bevy_api_gen/src/driver/plugin.rs @@ -0,0 +1,55 @@ +use std::{borrow::Cow, process::Command}; + +use cargo_metadata::camino::Utf8Path; +use serde::{Serialize, de::DeserializeOwned}; + +/// Specification of a set of crates. +pub enum CrateFilter { + /// Every crate in the workspace and all transitive dependencies. + AllCrates, + /// Just crates in the workspace. + OnlyWorkspace, +} + +/// Arguments from your plugin to the rustc_plugin framework. +pub struct RustcPluginArgs { + /// Whatever CLI arguments you want to pass along. + pub args: Args, + + /// Which crates you want to run the plugin on. + pub filter: CrateFilter, +} + +/// Interface between your plugin and the rustc_plugin framework. +pub trait RustcPlugin: Sized { + /// Command-line arguments passed by the user. + type Args: Serialize + DeserializeOwned; + + /// Returns the version of your plugin. + /// + /// A sensible default is your plugin's Cargo version: + /// + /// ```ignore + /// env!("CARGO_PKG_VERSION").into() + /// ``` + fn version(&self) -> Cow<'static, str>; + + /// Returns the name of your driver binary as it's installed in the filesystem. + /// + /// Should be just the filename, not the full path. + fn driver_name(&self) -> Cow<'static, str>; + + /// Parses and returns the CLI arguments for the plugin. + fn args(&self, target_dir: &Utf8Path) -> RustcPluginArgs; + + /// Optionally modify the `cargo` command that launches rustc. + /// For example, you could pass a `--feature` flag here. + fn modify_cargo(&self, _cargo: &mut Command, _args: &Self::Args) {} + + /// Executes the plugin with a set of compiler and plugin args. + fn run(self, compiler_args: Vec, plugin_args: Self::Args); +} + +/// The name of the environment variable shared between the CLI and the driver. +/// Must not conflict with any other env var used by Cargo. +pub const PLUGIN_ARGS: &str = "PLUGIN_ARGS"; diff --git a/crates/bevy_api_gen/src/feature_graph.rs b/crates/bevy_api_gen/src/feature_graph.rs index e75afd9960..9ddefd358b 100644 --- a/crates/bevy_api_gen/src/feature_graph.rs +++ b/crates/bevy_api_gen/src/feature_graph.rs @@ -241,18 +241,18 @@ impl FeatureGraph { } else { let parts = effect.split('/').collect::>(); if parts.len() > 2 { - panic!("Invalid feature effect: {}", effect); + panic!("Invalid feature effect: {effect}"); } else if parts.len() == 1 { - return FeatureEffect::EnableFeature(parts[0].to_owned()); + FeatureEffect::EnableFeature(parts[0].to_owned()) } else { - return FeatureEffect::EnableDepFeature { + FeatureEffect::EnableDepFeature { feature: parts[1].to_owned(), dependency: parts[0] .strip_suffix('?') .unwrap_or(parts[0]) .to_owned(), enable_optional: !parts[0].ends_with('?'), - }; + } } } }) diff --git a/crates/bevy_api_gen/src/import_path.rs b/crates/bevy_api_gen/src/import_path.rs index c8f5522685..4bae0d0f0a 100644 --- a/crates/bevy_api_gen/src/import_path.rs +++ b/crates/bevy_api_gen/src/import_path.rs @@ -17,8 +17,8 @@ pub(crate) enum ImportPathElement { impl std::fmt::Debug for ImportPathElement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ImportPathElement::Rename(did, name) => write!(f, "{:?} as {}", did, name), - ImportPathElement::Item(did) => write!(f, "{:?}", did), + ImportPathElement::Rename(did, name) => write!(f, "{did:?} as {name}"), + ImportPathElement::Item(did) => write!(f, "{did:?}"), } } } @@ -53,7 +53,7 @@ impl<'tcx> ImportPathFinder<'tcx> { } fn crawl_module(&mut self, did: DefId, frontier: &[ImportPathElement]) { - trace!("Crawling module {:?}", did); + trace!("Crawling module {did:?}"); let mut new_frontier = frontier.to_vec(); new_frontier.push(ImportPathElement::Item(did)); @@ -70,7 +70,7 @@ impl<'tcx> ImportPathFinder<'tcx> { let rename = child.ident.to_string(); if !self.include_private_paths && !child.vis.is_public() { - trace!("Skipping private child {:?}", rename); + trace!("Skipping private child {rename:?}"); continue; } @@ -94,7 +94,7 @@ impl<'tcx> ImportPathFinder<'tcx> { let mut new_frontier = new_frontier.clone(); new_frontier.push(ImportPathElement::Rename(did, rename)); - trace!("saving import path for {:?}: {:?}", did, new_frontier); + trace!("saving import path for {did:?}: {new_frontier:?}"); self.cache.entry(did).or_default().push(new_frontier); } _ => continue, diff --git a/crates/bevy_api_gen/src/lib.rs b/crates/bevy_api_gen/src/lib.rs index cc8c1c28da..84345822d4 100644 --- a/crates/bevy_api_gen/src/lib.rs +++ b/crates/bevy_api_gen/src/lib.rs @@ -4,11 +4,13 @@ extern crate rustc_ast; extern crate rustc_const_eval; extern crate rustc_driver; +extern crate rustc_driver_impl; extern crate rustc_errors; extern crate rustc_hir; extern crate rustc_infer; extern crate rustc_interface; extern crate rustc_middle; +extern crate rustc_session; extern crate rustc_span; extern crate rustc_trait_selection; @@ -24,17 +26,17 @@ mod plugin; mod template; // pub(crate) use args::*; +pub use args::{Args, Command, WorkspaceMeta}; pub(crate) use callback::*; pub(crate) use context::*; +pub use feature_graph::*; pub(crate) use import_path::*; +pub use meta::MetaLoader; pub(crate) use meta::*; pub(crate) use passes::*; -pub(crate) use template::*; - -pub use args::{Args, Command, WorkspaceMeta}; -pub use feature_graph::*; -pub use meta::MetaLoader; pub use plugin::BevyAnalyzer; +pub(crate) use template::*; pub use template::{ - configure_tera, extend_context_with_args, Collect, Crate, TemplateKind, TEMPLATE_DIR, + Collect, Crate, TEMPLATE_DIR, TemplateKind, configure_tera, extend_context_with_args, }; +pub mod driver; diff --git a/crates/bevy_api_gen/src/meta.rs b/crates/bevy_api_gen/src/meta.rs index 6492f4f9e5..8f7e848f68 100644 --- a/crates/bevy_api_gen/src/meta.rs +++ b/crates/bevy_api_gen/src/meta.rs @@ -96,7 +96,7 @@ impl MetaLoader { pub fn iter_meta(&self) -> impl Iterator + '_ { self.meta_dirs.iter().flat_map(|dir| { dir.read_dir() - .unwrap_or_else(|_| panic!("Could not read meta directory: {}", dir)) + .unwrap_or_else(|_| panic!("Could not read meta directory: {dir}")) .filter_map(|entry| { let entry = entry.unwrap(); if entry.path().extension().is_some_and(|ext| ext == "json") { @@ -149,13 +149,11 @@ impl MetaLoader { if meta.is_none() { log::trace!( - "Could not find meta file for crate: `{}`, is_workspace_and_included: '{}'", - crate_name, - needs_meta + "Could not find meta file for crate: `{crate_name}`, is_workspace_and_included: '{needs_meta}'" ) } if meta.is_none() && needs_meta { - panic!("Could not find meta for workspace crate: {}", crate_name); + panic!("Could not find meta for workspace crate: {crate_name}"); }; meta @@ -164,17 +162,13 @@ impl MetaLoader { fn meta_for_in_dir(&self, crate_name: &str, dir: &Utf8PathBuf) -> Option { let cache = self.cache.borrow(); if cache.contains_key(crate_name) { - trace!("Loading meta from cache for: {}", crate_name); + trace!("Loading meta from cache for: {crate_name}"); cache.get(crate_name).cloned() } else { drop(cache); let mut cache = self.cache.borrow_mut(); let dir = dir.join(Self::crate_name_to_meta_filename(crate_name)); - trace!( - "Attempting to load meta from filesystem for crate: {}, at: {}", - crate_name, - dir - ); + trace!("Attempting to load meta from filesystem for crate: {crate_name}, at: {dir}"); let meta = Self::opt_load_meta(dir)?; cache.insert(crate_name.to_owned(), meta.clone()); Some(meta) @@ -183,7 +177,7 @@ impl MetaLoader { fn opt_load_meta(path: Utf8PathBuf) -> Option { if !path.exists() { - trace!("Meta not found at: {}", path); + trace!("Meta not found at: {path}"); return None; } let file = File::open(path).unwrap(); @@ -208,6 +202,6 @@ impl MetaLoader { } fn crate_name_to_meta_filename(crate_name: &str) -> String { - format!("{}.json", crate_name) + format!("{crate_name}.json") } } diff --git a/crates/bevy_api_gen/src/passes/cache_traits.rs b/crates/bevy_api_gen/src/passes/cache_traits.rs index af71b7f4fe..d44f30eadb 100644 --- a/crates/bevy_api_gen/src/passes/cache_traits.rs +++ b/crates/bevy_api_gen/src/passes/cache_traits.rs @@ -87,7 +87,7 @@ pub(crate) fn cache_traits(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> bool { .next() .is_none(); - log::trace!("has_std: {}", has_std); + log::trace!("has_std: {has_std}"); // if has_std && !ctxt.cached_traits.has_all_std_source_traits() { // log::debug!( diff --git a/crates/bevy_api_gen/src/passes/codegen.rs b/crates/bevy_api_gen/src/passes/codegen.rs index cd2e9ccdc5..dabd068bdc 100644 --- a/crates/bevy_api_gen/src/passes/codegen.rs +++ b/crates/bevy_api_gen/src/passes/codegen.rs @@ -1,13 +1,14 @@ -use crate::{configure_tera, Args, BevyCtxt, TemplateKind}; - -use log::info; -use rustc_hir::def_id::LOCAL_CRATE; use std::{ fs::{self, File}, io::Write, }; + +use log::info; +use rustc_hir::def_id::LOCAL_CRATE; use tera::Context; +use crate::{Args, BevyCtxt, TemplateKind, configure_tera}; + /// generates a module with the appropriate wrappers for all the found reflection ADT's in the crate pub(crate) fn codegen(ctxt: &mut BevyCtxt<'_>, args: &Args) -> bool { let (output, templates) = match &args.cmd { @@ -21,7 +22,7 @@ pub(crate) fn codegen(ctxt: &mut BevyCtxt<'_>, args: &Args) -> bool { // perform code gen using templates fs::create_dir_all(output).unwrap(); - info!("Writing code files to : {}", output); + info!("Writing code files to : {output}"); let template_data = ctxt.template_context.as_ref().unwrap(); let mut context = Context::from_serialize(template_data).unwrap(); @@ -48,9 +49,8 @@ mod tests { use strum::VariantNames; - use crate::TEMPLATE_DIR; - use super::*; + use crate::TEMPLATE_DIR; #[test] fn test_templates_exist() { @@ -62,8 +62,7 @@ mod tests { TemplateKind::VARIANTS.iter().for_each(|f| { assert!( template_files.contains(f), - "Template file not in variants: {}", - f + "Template file not in variants: {f}" ); }); } diff --git a/crates/bevy_api_gen/src/passes/find_methods_and_fields.rs b/crates/bevy_api_gen/src/passes/find_methods_and_fields.rs index de59f5f973..a2c66f517d 100644 --- a/crates/bevy_api_gen/src/passes/find_methods_and_fields.rs +++ b/crates/bevy_api_gen/src/passes/find_methods_and_fields.rs @@ -1,9 +1,8 @@ use indexmap::IndexMap; use log::{info, trace}; -use rustc_ast::Attribute; use rustc_hir::{ - def_id::{DefId, LOCAL_CRATE}, Safety, + def_id::{DefId, LOCAL_CRATE}, }; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::ty::{ @@ -29,42 +28,89 @@ pub(crate) fn find_methods_and_fields(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> match adt_def.adt_kind() { AdtKind::Enum => { - let strats = adt_def.variants().iter().flat_map(|variant| { - if has_reflect_ignore_attr(ctxt.tcx.get_attrs_unchecked(variant.def_id)) { - // TODO: is this the right approach? do we need to still include those variants? or do we just provide dummies - // or can we just skip those ? - info!("ignoring enum variant: {}::{} due to 'reflect(ignore)' attribute", ctxt.tcx.item_name(def_id), variant.name); - todo!(); - } - let param_env = TypingEnv::non_body_analysis(ctxt.tcx, variant.def_id); - process_fields(ctxt.tcx, &ctxt.meta_loader, &ctxt.reflect_types, &ctxt.cached_traits, variant.fields.iter(), param_env) - }).collect::>(); + let strats = adt_def + .variants() + .iter() + .flat_map(|variant| { + if has_reflect_ignore_attr(ctxt.tcx.get_attrs_unchecked(variant.def_id)) { + // TODO: is this the right approach? do we need to still include those variants? or do we just provide dummies + // or can we just skip those ? + info!( + "ignoring enum variant: {}::{} due to 'reflect(ignore)' attribute", + ctxt.tcx.item_name(def_id), + variant.name + ); + todo!(); + } + let param_env = TypingEnv::non_body_analysis(ctxt.tcx, variant.def_id); + process_fields( + ctxt.tcx, + &ctxt.meta_loader, + &ctxt.reflect_types, + &ctxt.cached_traits, + variant.fields.iter(), + param_env, + ) + }) + .collect::>(); strats.iter().for_each(|(f_did, strat)| match strat { - ReflectionStrategy::Reflection => report_field_not_supported(ctxt.tcx, *f_did, def_id, None, "type is neither a proxy nor a type expressible as lua primitive"), - ReflectionStrategy::Filtered => report_field_not_supported(ctxt.tcx, *f_did, def_id, None, "field has a 'reflect(ignore)' attribute"), + ReflectionStrategy::Reflection => report_field_not_supported( + ctxt.tcx, + *f_did, + def_id, + None, + "type is neither a proxy nor a type expressible as lua primitive", + ), + ReflectionStrategy::Filtered => report_field_not_supported( + ctxt.tcx, + *f_did, + def_id, + None, + "field has a 'reflect(ignore)' attribute", + ), _ => {} }); let ty_ctxt = ctxt.reflect_types.get_mut(&def_id).unwrap(); ty_ctxt.variant_data = Some(adt_def); ty_ctxt.set_field_reflection_strategies(strats.into_iter()); - - }, + } AdtKind::Struct => { let param_env = TypingEnv::non_body_analysis(ctxt.tcx, def_id); - let fields = process_fields(ctxt.tcx, &ctxt.meta_loader, &ctxt.reflect_types,&ctxt.cached_traits, adt_def.all_fields(), param_env); + let fields = process_fields( + ctxt.tcx, + &ctxt.meta_loader, + &ctxt.reflect_types, + &ctxt.cached_traits, + adt_def.all_fields(), + param_env, + ); fields.iter().for_each(|(f_did, strat)| match strat { - ReflectionStrategy::Reflection => report_field_not_supported(ctxt.tcx, *f_did, def_id, None, "type is neither a proxy nor a type expressible as lua primitive"), - ReflectionStrategy::Filtered => report_field_not_supported(ctxt.tcx, *f_did, def_id, None, "field has a 'reflect(ignore)' attribute"), + ReflectionStrategy::Reflection => report_field_not_supported( + ctxt.tcx, + *f_did, + def_id, + None, + "type is neither a proxy nor a type expressible as lua primitive", + ), + ReflectionStrategy::Filtered => report_field_not_supported( + ctxt.tcx, + *f_did, + def_id, + None, + "field has a 'reflect(ignore)' attribute", + ), _ => {} }); let ty_ctxt = ctxt.reflect_types.get_mut(&def_id).unwrap(); assert!(ty_ctxt.variant_data.is_none(), "variant data already set!"); ty_ctxt.variant_data = Some(adt_def); ty_ctxt.set_field_reflection_strategies(fields.into_iter()); - }, - t => panic!("Unexpected item type, all `Reflect` implementing items should be enums or structs. : {:?}", t) + } + t => panic!( + "Unexpected item type, all `Reflect` implementing items should be enums or structs. : {t:?}" + ), }; // borrow checker fucky wucky pt2 @@ -102,10 +148,15 @@ pub(crate) fn find_methods_and_fields(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> .associated_items(impl_did) .in_definition_order() .filter_map(|assoc_item| { - if assoc_item.kind != AssocKind::Fn { + if !matches!(assoc_item.kind, AssocKind::Fn { .. }) { return None; } + let (fn_name, has_self) = match assoc_item.kind { + AssocKind::Fn { has_self, name } => (name, has_self), + _ => return None, + }; + let trait_did = ctxt .tcx .impl_trait_ref(*impl_did) @@ -114,8 +165,7 @@ pub(crate) fn find_methods_and_fields(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> .map(|td| ctxt.tcx.item_name(td).to_ident_string()) .unwrap_or_else(|| "None".to_string()); - let fn_name = assoc_item.name.to_ident_string(); - let has_self = assoc_item.fn_has_self_parameter; + let fn_name = fn_name.to_ident_string(); let fn_did = assoc_item.def_id; trace!( @@ -134,23 +184,23 @@ pub(crate) fn find_methods_and_fields(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> if !function_generics.is_empty() { log::debug!( "Skipping function: `{}` on type: `{}` as it has generics: {:?}", - assoc_item.name, + fn_name, ctxt.tcx.item_name(def_id), function_generics ); return None; } - if let Some(unstability) = ctxt.tcx.lookup_stability(fn_did) { - if unstability.is_unstable() { - log::debug!( - "Skipping unstable function: `{}` on type: `{}` feature: {:?}", - ctxt.tcx.item_name(fn_did), - ctxt.tcx.item_name(def_id), - unstability.feature.as_str() - ); - return None; - } + if let Some(unstability) = ctxt.tcx.lookup_stability(fn_did) + && unstability.is_unstable() + { + log::debug!( + "Skipping unstable function: `{}` on type: `{}` feature: {:?}", + ctxt.tcx.item_name(fn_did), + ctxt.tcx.item_name(def_id), + unstability.feature.as_str() + ); + return None; }; let is_unsafe = sig.safety == Safety::Unsafe; @@ -164,7 +214,7 @@ pub(crate) fn find_methods_and_fields(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> return None; } - let arg_names = ctxt.tcx.fn_arg_names(fn_did); + let arg_names = ctxt.tcx.fn_arg_idents(fn_did); let mut reflection_strategies = Vec::with_capacity(sig.inputs().len()); for (idx, arg_ty) in sig.inputs().iter().enumerate() { @@ -188,7 +238,10 @@ pub(crate) fn find_methods_and_fields(ctxt: &mut BevyCtxt<'_>, _args: &Args) -> fn_did, def_id, *arg_ty, - &format!("argument \"{}\" not supported", arg_names[idx]), + &format!( + "argument \"{:?}\" at idx {idx} not supported", + arg_names[idx] + ), ); return None; } @@ -324,7 +377,7 @@ fn process_fields<'tcx, 'f, I: Iterator>( } /// Checks if the given attributes contain among them a reflect ignore attribute -fn has_reflect_ignore_attr(attrs: &[Attribute]) -> bool { +fn has_reflect_ignore_attr(attrs: &[rustc_hir::Attribute]) -> bool { attrs.iter().any(|a| { a.path_matches(&[Symbol::intern("reflect")]) && a.value_str() @@ -340,7 +393,7 @@ fn type_is_supported_as_proxy_arg<'tcx>( meta_loader: &MetaLoader, ty: Ty, ) -> bool { - log::trace!("Checking type is supported as proxy arg: '{}'", ty); + log::trace!("Checking type is supported as proxy arg: '{ty}'"); type_is_adt_and_reflectable(tcx, reflect_types, meta_loader, ty.peel_refs()) } @@ -351,7 +404,7 @@ fn type_is_supported_as_proxy_return_val<'tcx>( meta_loader: &MetaLoader, ty: Ty, ) -> bool { - log::trace!("Checking type is supported as proxy return val: '{}'", ty); + log::trace!("Checking type is supported as proxy return val: '{ty}'"); type_is_adt_and_reflectable(tcx, reflect_types, meta_loader, ty) } @@ -420,11 +473,13 @@ fn type_is_supported_as_non_proxy_return_val<'tcx>( cached_traits: &CachedTraits, ty: Ty<'tcx>, ) -> bool { - trace!("Checkign type is supported as non proxy return val: '{ty:?}' with param_env: '{param_env:?}'"); - if let TyKind::Ref(region, _, _) = ty.kind() { - if region.get_name().is_none_or(|rn| rn.as_str() != "'static") { - return false; - } + trace!( + "Checkign type is supported as non proxy return val: '{ty:?}' with param_env: '{param_env:?}'" + ); + if let TyKind::Ref(region, _, _) = ty.kind() + && region.get_name().is_none_or(|rn| rn.as_str() != "'static") + { + return false; } impls_trait(tcx, param_env, ty, cached_traits.bms_into_script.unwrap()) diff --git a/crates/bevy_api_gen/src/passes/find_trait_impls.rs b/crates/bevy_api_gen/src/passes/find_trait_impls.rs index 3913ab8296..1d33232bb7 100644 --- a/crates/bevy_api_gen/src/passes/find_trait_impls.rs +++ b/crates/bevy_api_gen/src/passes/find_trait_impls.rs @@ -113,7 +113,7 @@ fn type_impl_of_trait( let ty = tcx.type_of(reflect_ty_did).instantiate_identity(); let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis()); let result = impl_matches(&infcx, ty, impl_did); - log::trace!("Result: {:#?}", result); + log::trace!("Result: {result:#?}"); if result { trace!( "Type: `{}` implements trait: `{}`", diff --git a/crates/bevy_api_gen/src/passes/populate_template_data.rs b/crates/bevy_api_gen/src/passes/populate_template_data.rs index 955845b1fa..5ef1c39ef4 100644 --- a/crates/bevy_api_gen/src/passes/populate_template_data.rs +++ b/crates/bevy_api_gen/src/passes/populate_template_data.rs @@ -1,7 +1,6 @@ use std::{borrow::Cow, convert::identity}; use log::{trace, warn}; -use rustc_ast::Attribute; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_middle::ty::{ AdtDef, FieldDef, GenericArg, GenericParamDefKind, TraitRef, Ty, TyKind, TypingEnv, @@ -127,7 +126,7 @@ pub(crate) fn process_functions(ctxt: &BevyCtxt, fns: &[FunctionContext]) -> Vec let fn_sig = ctxt.tcx.fn_sig(fn_ctxt.def_id).skip_binder().skip_binder(); let args = ctxt .tcx - .fn_arg_names(fn_ctxt.def_id) + .fn_arg_idents(fn_ctxt.def_id) .iter() .zip(fn_sig.inputs()) .enumerate() @@ -137,7 +136,7 @@ pub(crate) fn process_functions(ctxt: &BevyCtxt, fns: &[FunctionContext]) -> Vec *ty, ); Arg { - ident: ident.to_string(), + ident: ident.map(|s| s.to_string()).unwrap_or(format!("arg_{idx}")), ty: ty_to_string(ctxt, normalized_ty, false), proxy_ty: ty_to_string(ctxt, normalized_ty, true), reflection_strategy: fn_ctxt.reflection_strategies[idx], @@ -176,7 +175,7 @@ pub(crate) fn process_functions(ctxt: &BevyCtxt, fns: &[FunctionContext]) -> Vec } /// extracts and normalizes docstrings in a given list of attributes -pub(crate) fn docstrings(attrs: &[Attribute]) -> Vec { +pub(crate) fn docstrings(attrs: &[rustc_hir::Attribute]) -> Vec { attrs .iter() .filter_map(|attr| attr.doc_str()) @@ -414,7 +413,8 @@ impl<'a> TyPrinter<'a> { _ => { warn!( "Type outside the scope of the TyPrinter being printed: pretty=`{}` kind=`{:?}`", - ty, ty.kind() + ty, + ty.kind() ); self.buffer.push_str(&ty.to_string()) } diff --git a/crates/bevy_api_gen/src/plugin.rs b/crates/bevy_api_gen/src/plugin.rs index bae2dbfcf5..63e1f6a921 100644 --- a/crates/bevy_api_gen/src/plugin.rs +++ b/crates/bevy_api_gen/src/plugin.rs @@ -1,13 +1,16 @@ use std::env; +use cargo_metadata::camino::Utf8Path; use clap::Parser; use log::debug; -use rustc_plugin::{CrateFilter, RustcPlugin, RustcPluginArgs, Utf8Path}; -use crate::{modifying_file_loader::ModifyingFileLoader, BevyAnalyzerCallbacks, WorkspaceMeta}; +use crate::{ + BevyAnalyzerCallbacks, WorkspaceMeta, + driver::{CrateFilter, RustcPluginArgs}, +}; pub struct BevyAnalyzer; -impl RustcPlugin for BevyAnalyzer { +impl crate::driver::RustcPlugin for BevyAnalyzer { type Args = crate::Args; fn version(&self) -> std::borrow::Cow<'static, str> { @@ -18,8 +21,8 @@ impl RustcPlugin for BevyAnalyzer { "bevy-api-gen-driver".into() } - fn args(&self, target_dir: &Utf8Path) -> rustc_plugin::RustcPluginArgs { - debug!("Target dir: {}", target_dir); + fn args(&self, target_dir: &Utf8Path) -> RustcPluginArgs { + debug!("Target dir: {target_dir}"); RustcPluginArgs { args: crate::Args::parse_from(std::env::args().skip(1)), @@ -27,11 +30,7 @@ impl RustcPlugin for BevyAnalyzer { } } - fn run( - self, - compiler_args: Vec, - plugin_args: Self::Args, - ) -> rustc_interface::interface::Result<()> { + fn run(self, compiler_args: Vec, plugin_args: Self::Args) { log::set_max_level(plugin_args.verbose.get_log_level().to_level_filter()); if let Some(includes) = WorkspaceMeta::from_env().include_crates { @@ -43,22 +42,19 @@ impl RustcPlugin for BevyAnalyzer { if !includes.contains(crate_name) { log::info!( - "Not running plugin on: '{}', due to feature combination, still compiling.", - crate_name + "Not running plugin on: '{crate_name}', due to feature combination, still compiling." ); struct DefaultCallbacks; impl rustc_driver::Callbacks for DefaultCallbacks {} - rustc_driver::RunCompiler::new(&compiler_args, &mut DefaultCallbacks).run(); - return Ok(()); + rustc_driver_impl::run_compiler(&compiler_args, &mut DefaultCallbacks); + return; } } let mut callbacks = BevyAnalyzerCallbacks::new(plugin_args); - let mut compiler = rustc_driver::RunCompiler::new(&compiler_args, &mut callbacks); - compiler.set_file_loader(Some(Box::new(ModifyingFileLoader))); - compiler.run(); + + rustc_driver_impl::run_compiler(&compiler_args, &mut callbacks); log::trace!("Finished compiling with plugin"); - Ok(()) } fn modify_cargo(&self, cmd: &mut std::process::Command, args: &Self::Args) { diff --git a/crates/bevy_api_gen/src/template.rs b/crates/bevy_api_gen/src/template.rs index ecc5ceb6b0..3b4a54ffa8 100644 --- a/crates/bevy_api_gen/src/template.rs +++ b/crates/bevy_api_gen/src/template.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, str::FromStr}; use clap::ValueEnum; use convert_case::{Case, Casing}; -use include_dir::{include_dir, Dir}; +use include_dir::{Dir, include_dir}; use serde::{Deserialize, Serialize}; use strum::*; use tera::{Tera, Value}; @@ -193,7 +193,7 @@ pub(crate) fn configure_tera_env(tera: &mut Tera, crate_name: &str) { let file = syn::parse_file(&str) .map_err(|e| tera::Error::msg(e.to_string())) .inspect_err(|_| { - log::error!("prettyplease error on input: ```\n{}\n```", str); + log::error!("prettyplease error on input: ```\n{str}\n```"); })?; let out = prettyplease::unparse(&file); @@ -359,5 +359,5 @@ fn expect_str(value: &Value) -> tera::Result<&str> { fn expect_arg<'a>(args: &'a HashMap, key: &str) -> tera::Result<&'a Value> { args.get(key) - .ok_or_else(|| tera::Error::msg(format!("Missing argument {}", key))) + .ok_or_else(|| tera::Error::msg(format!("Missing argument {key}"))) } diff --git a/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs b/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs index c8d78737ca..9b6e3d8fe9 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs @@ -1,12 +1,13 @@ //! The library crate for the mdbook LAD preprocessor. #![allow(missing_docs)] +use std::sync::OnceLock; + use mdbook::{ errors::Error, preprocess::{Preprocessor, PreprocessorContext}, }; use sections::{Section, SectionData}; -use std::sync::OnceLock; mod argument_visitor; mod markdown; mod sections; @@ -105,19 +106,19 @@ impl Preprocessor for LADPreprocessor { .iter() .enumerate() .filter_map(|(idx, item)| { - if let mdbook::BookItem::Chapter(chapter) = item { - if LADPreprocessor::is_lad_file(chapter) { - match LADPreprocessor::process_lad_chapter( - context, - chapter, - Some(parent), - idx, - ) { - Ok(new_chapter) => return Some((idx, new_chapter)), - Err(e) => { - errors.push(e); - return None; - } + if let mdbook::BookItem::Chapter(chapter) = item + && LADPreprocessor::is_lad_file(chapter) + { + match LADPreprocessor::process_lad_chapter( + context, + chapter, + Some(parent), + idx, + ) { + Ok(new_chapter) => return Some((idx, new_chapter)), + Err(e) => { + errors.push(e); + return None; } } } diff --git a/xtask/templates/settings.json.tera b/xtask/templates/settings.json.tera index d8dc91e9dd..39e45ef28c 100644 --- a/xtask/templates/settings.json.tera +++ b/xtask/templates/settings.json.tera @@ -9,8 +9,5 @@ "rust-analyzer.check.overrideCommand": [ "{{ dir }}/check.sh" ], - "rust-analyzer.cargo.buildScripts.invocationStrategy": "per_workspace", - "rust-analyzer.cargo.buildScripts.overrideCommand": [ - "{{ dir }}/build_scripts.sh" - ] + "rust-analyzer.cargo.buildScripts.invocationStrategy": "per_workspace" } \ No newline at end of file From df6b5b66fc606f4f493ca0785725530c9598dc8d Mon Sep 17 00:00:00 2001 From: makspll Date: Thu, 21 Aug 2025 21:54:18 +0100 Subject: [PATCH 10/12] make codegen work again --- crates/bevy_api_gen/src/driver/mod.rs | 2 + crates/bevy_mod_scripting_core/src/asset.rs | 20 ++++----- .../bevy_mod_scripting_core/src/commands.rs | 16 +++---- crates/bevy_mod_scripting_core/src/context.rs | 3 +- crates/bevy_mod_scripting_core/src/error.rs | 40 +++++++++--------- crates/bevy_mod_scripting_core/src/event.rs | 8 ++-- .../bevy_mod_scripting_core/src/extractors.rs | 34 ++++++++------- crates/bevy_mod_scripting_core/src/handler.rs | 19 +++++---- crates/bevy_mod_scripting_core/src/lib.rs | 11 ++--- .../src/reflection_extensions.rs | 12 +++--- crates/bevy_mod_scripting_core/src/runtime.rs | 3 +- .../src/script/context_key.rs | 6 ++- .../bevy_mod_scripting_core/src/script/mod.rs | 16 ++++--- .../src/script/script_context.rs | 6 ++- .../mdbook_lad_preprocessor/src/main.rs | 3 +- .../mdbook_lad_preprocessor/src/sections.rs | 14 ++++--- crates/ladfile/src/lib.rs | 3 +- crates/ladfile_builder/src/lib.rs | 17 ++++---- .../src/bindings/reference.rs | 6 ++- .../src/bindings/script_value.rs | 12 +++--- .../src/bindings/reference.rs | 12 +++--- .../src/bindings/script_value.rs | 3 +- .../src/scenario.rs | 42 +++++++++---------- .../test_utils/src/test_data.rs | 12 +++--- examples/docgen.rs | 14 ++++--- src/prelude.rs | 4 +- tests/script_tests.rs | 1 - xtask/src/main.rs | 13 +++--- 28 files changed, 191 insertions(+), 161 deletions(-) diff --git a/crates/bevy_api_gen/src/driver/mod.rs b/crates/bevy_api_gen/src/driver/mod.rs index f9069efe80..31f5594983 100644 --- a/crates/bevy_api_gen/src/driver/mod.rs +++ b/crates/bevy_api_gen/src/driver/mod.rs @@ -224,6 +224,8 @@ pub fn driver_main(plugin: T) { serde_json::from_str(&env::var(PLUGIN_ARGS).unwrap()).unwrap(); plugin.run(args, plugin_args); } else { + // ignore all lints that could break the comp in crates that we don't care about + args.extend([String::from("--cap-lints"), String::from("warn")]); log::debug!( "Running normal Rust. Relevant variables:\ normal_rustc={normal_rustc}, \ diff --git a/crates/bevy_mod_scripting_core/src/asset.rs b/crates/bevy_mod_scripting_core/src/asset.rs index 021851a7e0..9e0c5e955e 100644 --- a/crates/bevy_mod_scripting_core/src/asset.rs +++ b/crates/bevy_mod_scripting_core/src/asset.rs @@ -1,15 +1,7 @@ //! Systems and resources for handling script assets and events -use std::borrow::Cow; +use std::{borrow::Cow, collections::VecDeque}; -use crate::{ - IntoScriptPluginParams, LanguageExtensions, ScriptComponent, ScriptingSystemSet, StaticScripts, - commands::{CreateOrUpdateScript, DeleteScript}, - context::ContextLoadingSettings, - error::ScriptError, - event::ScriptEvent, - script::{ContextKey, DisplayProxy, ScriptAttachment}, -}; use bevy::{ app::{App, Last}, asset::{Asset, AssetEvent, AssetLoader, Assets, LoadState}, @@ -21,7 +13,15 @@ use bevy::{ reflect::Reflect, }; use serde::{Deserialize, Serialize}; -use std::collections::VecDeque; + +use crate::{ + IntoScriptPluginParams, LanguageExtensions, ScriptComponent, ScriptingSystemSet, StaticScripts, + commands::{CreateOrUpdateScript, DeleteScript}, + context::ContextLoadingSettings, + error::ScriptError, + event::ScriptEvent, + script::{ContextKey, DisplayProxy, ScriptAttachment}, +}; /// Represents a scripting language. Languages which compile into another language should use the target language as their language. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)] diff --git a/crates/bevy_mod_scripting_core/src/commands.rs b/crates/bevy_mod_scripting_core/src/commands.rs index d9018dab0f..a437e8b9f4 100644 --- a/crates/bevy_mod_scripting_core/src/commands.rs +++ b/crates/bevy_mod_scripting_core/src/commands.rs @@ -1,5 +1,14 @@ //! Commands for creating, updating and deleting scripts +use std::marker::PhantomData; + +use bevy::{ + asset::{Assets, Handle}, + ecs::event::Events, + log::{debug, warn}, + prelude::Command, +}; + use crate::{ IntoScriptPluginParams, ScriptContext, asset::ScriptAsset, @@ -14,13 +23,6 @@ use crate::{ handler::{handle_script_errors, send_callback_response}, script::{DisplayProxy, ScriptAttachment, StaticScripts}, }; -use bevy::{ - asset::{Assets, Handle}, - ecs::event::Events, - log::{debug, warn}, - prelude::Command, -}; -use std::marker::PhantomData; /// Detaches a script, invoking the `on_script_unloaded` callback if it exists, and removes the script from the static scripts collection. pub struct DeleteScript { diff --git a/crates/bevy_mod_scripting_core/src/context.rs b/crates/bevy_mod_scripting_core/src/context.rs index c4f6a4010c..f849f5d00f 100644 --- a/crates/bevy_mod_scripting_core/src/context.rs +++ b/crates/bevy_mod_scripting_core/src/context.rs @@ -1,12 +1,13 @@ //! Traits and types for managing script contexts. +use bevy::prelude::Resource; + use crate::{ IntoScriptPluginParams, bindings::{ThreadWorldContainer, WorldContainer, WorldGuard}, error::ScriptError, script::ScriptAttachment, }; -use bevy::prelude::Resource; /// A trait that all script contexts must implement. /// diff --git a/crates/bevy_mod_scripting_core/src/error.rs b/crates/bevy_mod_scripting_core/src/error.rs index 8cf43c38c2..6c9a2c29fd 100644 --- a/crates/bevy_mod_scripting_core/src/error.rs +++ b/crates/bevy_mod_scripting_core/src/error.rs @@ -1,17 +1,14 @@ //! Errors that can occur when interacting with the scripting system -use crate::script::DisplayProxy; -use crate::{ - ScriptAsset, - bindings::{ - ReflectBaseType, ReflectReference, - access_map::{DisplayCodeLocation, ReflectAccessId}, - function::namespace::Namespace, - pretty_print::DisplayWithWorld, - script_value::ScriptValue, - }, - script::ContextKey, +use std::{ + any::TypeId, + borrow::Cow, + fmt::{Debug, Display}, + ops::Deref, + str::Utf8Error, + sync::Arc, }; + use bevy::{ asset::{AssetPath, Handle}, ecs::{ @@ -21,13 +18,17 @@ use bevy::{ prelude::Entity, reflect::{PartialReflect, Reflect}, }; -use std::{ - any::TypeId, - borrow::Cow, - fmt::{Debug, Display}, - ops::Deref, - str::Utf8Error, - sync::Arc, + +use crate::{ + ScriptAsset, + bindings::{ + ReflectBaseType, ReflectReference, + access_map::{DisplayCodeLocation, ReflectAccessId}, + function::namespace::Namespace, + pretty_print::DisplayWithWorld, + script_value::ScriptValue, + }, + script::{ContextKey, DisplayProxy}, }; /// An error with an optional script Context @@ -1623,12 +1624,11 @@ impl Default for InteropErrorInner { mod test { use bevy::prelude::{AppTypeRegistry, World}; + use super::*; use crate::bindings::{ AppReflectAllocator, WorldGuard, function::script_function::AppScriptFunctionRegistry, }; - use super::*; - #[test] fn test_error_display() { let error = diff --git a/crates/bevy_mod_scripting_core/src/event.rs b/crates/bevy_mod_scripting_core/src/event.rs index 62ca10d8af..efda855d4c 100644 --- a/crates/bevy_mod_scripting_core/src/event.rs +++ b/crates/bevy_mod_scripting_core/src/event.rs @@ -2,6 +2,9 @@ use std::sync::Arc; +use bevy::{asset::Handle, ecs::entity::Entity, prelude::Event, reflect::Reflect}; +use parking_lot::Mutex; + use crate::{ IntoScriptPluginParams, asset::Language, @@ -9,8 +12,6 @@ use crate::{ error::ScriptError, script::{ScriptAttachment, ScriptContext, ScriptId}, }; -use bevy::{asset::Handle, ecs::entity::Entity, prelude::Event, reflect::Reflect}; -use parking_lot::Mutex; /// A script event #[derive(Event, Debug, Clone, PartialEq, Eq)] @@ -415,14 +416,13 @@ mod test { use parking_lot::Mutex; use test_utils::make_test_plugin; + use super::FORBIDDEN_KEYWORDS; use crate::{ bindings::ScriptValue, event::Recipients, script::{ContextPolicy, ScriptAttachment, ScriptContext}, }; - use super::FORBIDDEN_KEYWORDS; - #[test] fn test_invalid_strings() { FORBIDDEN_KEYWORDS.iter().for_each(|keyword| { diff --git a/crates/bevy_mod_scripting_core/src/extractors.rs b/crates/bevy_mod_scripting_core/src/extractors.rs index 307bdddc45..413113a6e8 100644 --- a/crates/bevy_mod_scripting_core/src/extractors.rs +++ b/crates/bevy_mod_scripting_core/src/extractors.rs @@ -2,32 +2,34 @@ //! //! These are designed to be used to pipe inputs into other systems which require them, while handling any configuration erorrs nicely. #![allow(deprecated)] -use crate::bindings::pretty_print::DisplayWithWorld; -use crate::handler::ScriptingHandler; -use crate::{ - IntoScriptPluginParams, - bindings::{ - WorldAccessGuard, WorldGuard, access_map::ReflectAccessId, script_value::ScriptValue, - }, - context::ContextLoadingSettings, - error::{InteropError, ScriptError}, - event::{CallbackLabel, IntoCallbackLabel}, - runtime::RuntimeContainer, - script::{ScriptAttachment, ScriptContext, StaticScripts}, +use std::{ + ops::{Deref, DerefMut}, + sync::Arc, }; -use bevy::ecs::resource::Resource; + use bevy::ecs::{ component::ComponentId, query::{Access, AccessConflicts}, + resource::Resource, storage::SparseSetIndex, system::{SystemParam, SystemParamValidationError}, world::World, }; use fixedbitset::FixedBitSet; use parking_lot::Mutex; -use std::{ - ops::{Deref, DerefMut}, - sync::Arc, + +use crate::{ + IntoScriptPluginParams, + bindings::{ + WorldAccessGuard, WorldGuard, access_map::ReflectAccessId, pretty_print::DisplayWithWorld, + script_value::ScriptValue, + }, + context::ContextLoadingSettings, + error::{InteropError, ScriptError}, + event::{CallbackLabel, IntoCallbackLabel}, + handler::ScriptingHandler, + runtime::RuntimeContainer, + script::{ScriptAttachment, ScriptContext, StaticScripts}, }; /// Executes `system_state.get_mut` followed by `system_state.apply` after running the given closure, makes sure state is correctly handled in the context of an exclusive system. diff --git a/crates/bevy_mod_scripting_core/src/handler.rs b/crates/bevy_mod_scripting_core/src/handler.rs index 6fd387b767..01d12e2b97 100644 --- a/crates/bevy_mod_scripting_core/src/handler.rs +++ b/crates/bevy_mod_scripting_core/src/handler.rs @@ -1,4 +1,14 @@ //! Contains the logic for handling script callback events +use bevy::{ + ecs::{ + event::EventCursor, + system::{Local, SystemState}, + world::{Mut, World}, + }, + log::error, + prelude::Events, +}; + use crate::{ IntoScriptPluginParams, Language, bindings::{ @@ -14,15 +24,6 @@ use crate::{ extractors::{HandlerContext, WithWorldGuard}, script::ScriptAttachment, }; -use bevy::{ - ecs::{ - event::EventCursor, - system::{Local, SystemState}, - world::{Mut, World}, - }, - log::error, - prelude::Events, -}; /// A function that handles a callback event pub type HandlerFn

= fn( diff --git a/crates/bevy_mod_scripting_core/src/lib.rs b/crates/bevy_mod_scripting_core/src/lib.rs index 5899e691a6..4709968f1f 100644 --- a/crates/bevy_mod_scripting_core/src/lib.rs +++ b/crates/bevy_mod_scripting_core/src/lib.rs @@ -2,11 +2,6 @@ //! //! Contains language agnostic systems and types for handling scripting in bevy. -use crate::{ - bindings::MarkAsCore, - context::{ContextLoadFn, ContextReloadFn}, - event::ScriptErrorEvent, -}; use asset::{ Language, ScriptAsset, ScriptAssetLoader, configure_asset_systems, configure_asset_systems_for_plugin, @@ -25,6 +20,12 @@ use handler::HandlerFn; use runtime::{Runtime, RuntimeContainer, RuntimeInitializer, RuntimeSettings, initialize_runtime}; use script::{ContextPolicy, ScriptComponent, ScriptContext, StaticScripts}; +use crate::{ + bindings::MarkAsCore, + context::{ContextLoadFn, ContextReloadFn}, + event::ScriptErrorEvent, +}; + pub mod asset; pub mod bindings; pub mod commands; diff --git a/crates/bevy_mod_scripting_core/src/reflection_extensions.rs b/crates/bevy_mod_scripting_core/src/reflection_extensions.rs index 947c948d96..7c3b638d28 100644 --- a/crates/bevy_mod_scripting_core/src/reflection_extensions.rs +++ b/crates/bevy_mod_scripting_core/src/reflection_extensions.rs @@ -1,15 +1,17 @@ //! Various utility functions for working with reflection types. -use crate::{ - bindings::{ReflectReference, WorldGuard}, - error::InteropError, -}; -use bevy::reflect::{PartialReflect, Reflect, ReflectFromReflect, ReflectMut, TypeInfo}; use std::{ any::{Any, TypeId}, cmp::max, }; +use bevy::reflect::{PartialReflect, Reflect, ReflectFromReflect, ReflectMut, TypeInfo}; + +use crate::{ + bindings::{ReflectReference, WorldGuard}, + error::InteropError, +}; + /// Extension trait for [`PartialReflect`] providing additional functionality for working with specific types. pub trait PartialReflectExt { /// Try to get a reference to the given key in an underyling map, if the type is a map. diff --git a/crates/bevy_mod_scripting_core/src/runtime.rs b/crates/bevy_mod_scripting_core/src/runtime.rs index 6f747e150b..ccf740449a 100644 --- a/crates/bevy_mod_scripting_core/src/runtime.rs +++ b/crates/bevy_mod_scripting_core/src/runtime.rs @@ -1,12 +1,13 @@ //! "Runtime" here refers to the execution evironment of scripts. This might be the VM executing bytecode or the interpreter executing source code. //! The important thing is that there is only one runtime which is used to execute all scripts of a particular type or `context`. -use crate::{IntoScriptPluginParams, error::ScriptError}; use bevy::{ ecs::system::ResMut, prelude::{Res, Resource}, }; +use crate::{IntoScriptPluginParams, error::ScriptError}; + /// A trait that all script runtimes must implement. pub trait Runtime: Default + 'static + Send + Sync {} impl Runtime for T {} diff --git a/crates/bevy_mod_scripting_core/src/script/context_key.rs b/crates/bevy_mod_scripting_core/src/script/context_key.rs index 3e12544948..eba9346187 100644 --- a/crates/bevy_mod_scripting_core/src/script/context_key.rs +++ b/crates/bevy_mod_scripting_core/src/script/context_key.rs @@ -1,7 +1,9 @@ +use std::fmt; + +use bevy::prelude::Entity; + use super::*; use crate::ScriptAsset; -use bevy::prelude::Entity; -use std::fmt; /// Specifies a unique attachment of a script. These attachments are mapped to [`ContextKey`]'s depending on the context policy used. #[derive(Debug, Hash, Clone, PartialEq, Eq, Reflect)] diff --git a/crates/bevy_mod_scripting_core/src/script/mod.rs b/crates/bevy_mod_scripting_core/src/script/mod.rs index 02c8cb39a6..01fcda84d2 100644 --- a/crates/bevy_mod_scripting_core/src/script/mod.rs +++ b/crates/bevy_mod_scripting_core/src/script/mod.rs @@ -1,18 +1,16 @@ //! Script related types, functions and components -use crate::asset::ScriptAsset; -use crate::event::ScriptEvent; -use bevy::ecs::component::HookContext; -use bevy::ecs::entity::Entity; -use bevy::ecs::resource::Resource; -use bevy::ecs::world::DeferredWorld; -use bevy::platform::collections::HashSet; -use bevy::prelude::ReflectComponent; +use std::{collections::HashMap, fmt, ops::Deref}; + use bevy::{ asset::{Asset, AssetId, Handle}, + ecs::{component::HookContext, entity::Entity, resource::Resource, world::DeferredWorld}, + platform::collections::HashSet, + prelude::ReflectComponent, reflect::Reflect, }; -use std::{collections::HashMap, fmt, ops::Deref}; + +use crate::{asset::ScriptAsset, event::ScriptEvent}; mod context_key; mod script_context; diff --git a/crates/bevy_mod_scripting_core/src/script/script_context.rs b/crates/bevy_mod_scripting_core/src/script/script_context.rs index 934a09dc54..7a08b38e91 100644 --- a/crates/bevy_mod_scripting_core/src/script/script_context.rs +++ b/crates/bevy_mod_scripting_core/src/script/script_context.rs @@ -1,7 +1,9 @@ +use std::{hash::Hash, sync::Arc}; + +use parking_lot::Mutex; + use super::*; use crate::IntoScriptPluginParams; -use parking_lot::Mutex; -use std::{hash::Hash, sync::Arc}; /// Determines how contexts are grouped by manipulating the context key. pub trait ContextKeySelector: Send + Sync + std::fmt::Debug + 'static { diff --git a/crates/lad_backends/mdbook_lad_preprocessor/src/main.rs b/crates/lad_backends/mdbook_lad_preprocessor/src/main.rs index 335c6517c9..2fb1ba6339 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/src/main.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/src/main.rs @@ -1,10 +1,11 @@ #![allow(missing_docs)] +use std::{env, fs::File, io, process::exit}; + use clap::{Arg, Command}; use env_logger::Builder; use log::LevelFilter; use mdbook::preprocess::{CmdPreprocessor, Preprocessor}; use mdbook_lad_preprocessor::LADPreprocessor; -use std::{env, fs::File, io, process::exit}; // use mdbook_lad_preprocessor::LADPreprocessor; diff --git a/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs b/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs index ddd4e8a8d9..c4d50e3f99 100644 --- a/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs +++ b/crates/lad_backends/mdbook_lad_preprocessor/src/sections.rs @@ -1,14 +1,16 @@ -use crate::{ - argument_visitor::MarkdownArgumentVisitor, - markdown::{IntoMarkdown, Markdown, MarkdownBuilder, TableBuilder, markdown_substring}, - markdown_vec, -}; +use std::{borrow::Cow, collections::HashSet, path::PathBuf}; + use ladfile::{ ArgumentVisitor, LadArgument, LadBMSPrimitiveKind, LadFile, LadFunction, LadInstance, LadType, LadTypeId, LadTypeKind, LadTypeLayout, }; use mdbook::book::{Chapter, SectionNumber}; -use std::{borrow::Cow, collections::HashSet, path::PathBuf}; + +use crate::{ + argument_visitor::MarkdownArgumentVisitor, + markdown::{IntoMarkdown, Markdown, MarkdownBuilder, TableBuilder, markdown_substring}, + markdown_vec, +}; fn print_type(ladfile: &LadFile, type_: &LadTypeId) -> String { let mut visitor = MarkdownArgumentVisitor::new(ladfile); diff --git a/crates/ladfile/src/lib.rs b/crates/ladfile/src/lib.rs index 93ad7518b6..54761ec339 100644 --- a/crates/ladfile/src/lib.rs +++ b/crates/ladfile/src/lib.rs @@ -4,9 +4,10 @@ //! - Centralization, we want to centralize as much of the "documentation" logic in the building of this format. For example, instead of letting each backend parse argument docstrings from the function docstring, we can do this here, and let the backends concentrate on pure generation. //! - Rust centric, the format describes bindings from the Rust side, so we generate rust centric declarations. These can then freely be converted into whatever representaion necessary. -use indexmap::IndexMap; use std::borrow::Cow; +use indexmap::IndexMap; + /// The current version of the LAD_VERSION format supported by this library. /// Earlier versions are not guaranteed to be supported. pub const LAD_VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/ladfile_builder/src/lib.rs b/crates/ladfile_builder/src/lib.rs index 52686c9b63..036aee195c 100644 --- a/crates/ladfile_builder/src/lib.rs +++ b/crates/ladfile_builder/src/lib.rs @@ -1,6 +1,15 @@ //! Parsing definitions for the LAD (Language Agnostic Decleration) file format. pub mod plugin; +use std::{ + any::TypeId, + borrow::Cow, + cmp::{max, min}, + collections::HashMap, + ffi::OsString, + path::PathBuf, +}; + use bevy::{ecs::world::World, log, platform::collections::HashSet}; use bevy_mod_scripting_core::{ bindings::{ @@ -21,14 +30,6 @@ use bevy_mod_scripting_core::{ }; use bevy_reflect::{NamedField, TypeInfo, TypeRegistry, Typed, UnnamedField}; use ladfile::*; -use std::{ - any::TypeId, - borrow::Cow, - cmp::{max, min}, - collections::HashMap, - ffi::OsString, - path::PathBuf, -}; /// We can assume that the types here will be either primitives /// or reflect types, as the rest will be covered by typed wrappers diff --git a/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs b/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs index e84c6b8cfd..7c50ae219d 100644 --- a/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs +++ b/crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs @@ -1,4 +1,5 @@ -use super::script_value::{LUA_CALLER_CONTEXT, LuaScriptValue}; +use std::any::TypeId; + use bevy_mod_scripting_core::{ bindings::{ ReflectReference, ThreadWorldContainer, WorldContainer, pretty_print::DisplayWithWorld, @@ -8,7 +9,8 @@ use bevy_mod_scripting_core::{ reflection_extensions::TypeIdExtensions, }; use mlua::{MetaMethod, UserData, UserDataMethods}; -use std::any::TypeId; + +use super::script_value::{LUA_CALLER_CONTEXT, LuaScriptValue}; /// Lua UserData wrapper for [`bevy_mod_scripting_core::bindings::ReflectReference`]. /// Acts as a lua reflection interface. Any value which is registered in the type registry can be interacted with using this type. diff --git a/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs b/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs index 88f238cb9a..8eff8e51bd 100644 --- a/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs +++ b/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs @@ -1,14 +1,16 @@ -use super::reference::LuaReflectReference; +use std::{ + collections::{HashMap, VecDeque}, + ops::{Deref, DerefMut}, +}; + use bevy_mod_scripting_core::{ asset::Language, bindings::{function::script_function::FunctionCallContext, script_value::ScriptValue}, error::InteropError, }; use mlua::{FromLua, IntoLua, Value, Variadic}; -use std::{ - collections::{HashMap, VecDeque}, - ops::{Deref, DerefMut}, -}; + +use super::reference::LuaReflectReference; #[derive(Debug, Clone)] /// A wrapper around a [`ScriptValue`] that implements [`FromLua`] and [`IntoLua`] diff --git a/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs b/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs index a7cf399b91..0f5189eed1 100644 --- a/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs +++ b/crates/languages/bevy_mod_scripting_rhai/src/bindings/reference.rs @@ -1,4 +1,8 @@ -use super::script_value::{FromDynamic, FunctionWithReceiver, IntoDynamic, RHAI_CALLER_CONTEXT}; +use std::{ + any::TypeId, + ops::{Deref, DerefMut}, +}; + use bevy_mod_scripting_core::{ bindings::{ ReflectReference, ThreadWorldContainer, WorldContainer, @@ -9,12 +13,10 @@ use bevy_mod_scripting_core::{ reflection_extensions::TypeIdExtensions, }; use rhai::{CustomType, Dynamic, EvalAltResult}; -use std::{ - any::TypeId, - ops::{Deref, DerefMut}, -}; use strum::VariantNames; +use super::script_value::{FromDynamic, FunctionWithReceiver, IntoDynamic, RHAI_CALLER_CONTEXT}; + #[derive(Debug, strum::EnumString, strum::VariantNames, Clone)] /// A list of reserved keywords in Rhai #[allow(missing_docs)] diff --git a/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs b/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs index f5448bffc6..2a79bab06e 100644 --- a/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs +++ b/crates/languages/bevy_mod_scripting_rhai/src/bindings/script_value.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use bevy_mod_scripting_core::{ asset::Language, bindings::{ @@ -7,7 +9,6 @@ use bevy_mod_scripting_core::{ error::InteropError, }; use rhai::{Dynamic, EvalAltResult, FnPtr, Map, NativeCallContext}; -use std::str::FromStr; use super::reference::RhaiReflectReference; diff --git a/crates/testing_crates/script_integration_test_harness/src/scenario.rs b/crates/testing_crates/script_integration_test_harness/src/scenario.rs index 4567a7bcd0..e50e2b34b5 100644 --- a/crates/testing_crates/script_integration_test_harness/src/scenario.rs +++ b/crates/testing_crates/script_integration_test_harness/src/scenario.rs @@ -1,39 +1,39 @@ -use crate::{install_test_plugin, parse::*}; +use std::{ + borrow::Cow, + collections::{HashMap, VecDeque}, + path::{Path, PathBuf}, + time::Instant, +}; + use anyhow::{Context, Error, anyhow}; -use bevy::ecs::entity::Entity; -use bevy::ecs::system::Command; -use bevy::prelude::IntoSystem; use bevy::{ app::App, asset::{AssetEvent, Handle, LoadState}, ecs::{ + entity::Entity, event::{Event, EventCursor, Events}, schedule::ScheduleLabel, + system::Command, world::World, }, + prelude::IntoSystem, }; -use bevy_mod_scripting_core::asset::Language; -use bevy_mod_scripting_core::bindings::{DisplayWithWorld, ScriptValue, WorldGuard}; -use bevy_mod_scripting_core::commands::{AddStaticScript, RemoveStaticScript}; -use bevy_mod_scripting_core::event::ScriptEvent; -use bevy_mod_scripting_core::script::ContextPolicy; -use bevy_mod_scripting_core::script::ScriptContext; -use bevy_mod_scripting_core::{ConfigureScriptPlugin, LanguageExtensions}; use bevy_mod_scripting_core::{ - asset::ScriptAsset, - event::{CallbackLabel, IntoCallbackLabel, ScriptCallbackEvent, ScriptCallbackResponseEvent}, + ConfigureScriptPlugin, LanguageExtensions, + asset::{Language, ScriptAsset}, + bindings::{DisplayWithWorld, ScriptValue, WorldGuard}, + commands::{AddStaticScript, RemoveStaticScript}, + event::{ + CallbackLabel, IntoCallbackLabel, ScriptCallbackEvent, ScriptCallbackResponseEvent, + ScriptEvent, + }, handler::event_handler, - script::{ScriptAttachment, ScriptComponent}, -}; -use std::borrow::Cow; -use std::collections::VecDeque; -use std::{ - collections::HashMap, - path::{Path, PathBuf}, - time::Instant, + script::{ContextPolicy, ScriptAttachment, ScriptComponent, ScriptContext}, }; use test_utils::test_data::setup_integration_test; +use crate::{install_test_plugin, parse::*}; + const TIMEOUT_SECONDS: u64 = 10; pub const SCENARIO_SELF_SCRIPT_NAME: &str = "@this_script"; pub const SCENARIO_SELF_LANGUAGE_NAME: &str = "@this_language"; diff --git a/crates/testing_crates/test_utils/src/test_data.rs b/crates/testing_crates/test_utils/src/test_data.rs index 199305d50e..86acbcc7ca 100644 --- a/crates/testing_crates/test_utils/src/test_data.rs +++ b/crates/testing_crates/test_utils/src/test_data.rs @@ -1,10 +1,12 @@ use std::{alloc::Layout, collections::HashMap}; -use bevy::asset::AssetPlugin; -use bevy::diagnostic::DiagnosticsPlugin; -use bevy::ecs::{component::*, world::World}; -use bevy::prelude::*; -use bevy::reflect::*; +use bevy::{ + asset::AssetPlugin, + diagnostic::DiagnosticsPlugin, + ecs::{component::*, world::World}, + prelude::*, + reflect::*, +}; /// Test component with Reflect and ReflectComponent registered #[derive(Component, Reflect, PartialEq, Eq, Debug)] diff --git a/examples/docgen.rs b/examples/docgen.rs index 2294fa5d1e..285c51fd5e 100644 --- a/examples/docgen.rs +++ b/examples/docgen.rs @@ -1,10 +1,12 @@ -use bevy::ecs::reflect::AppTypeRegistry; -use bevy::{DefaultPlugins, app::App}; +use bevy::{DefaultPlugins, app::App, ecs::reflect::AppTypeRegistry}; use bevy_mod_scripting::ScriptFunctionsPlugin; -use bevy_mod_scripting_core::BMSScriptingInfrastructurePlugin; -use bevy_mod_scripting_core::bindings::function::script_function::AppScriptFunctionRegistry; -use bevy_mod_scripting_core::bindings::globals::AppScriptGlobalsRegistry; -use bevy_mod_scripting_core::bindings::globals::core::CoreScriptGlobalsPlugin; +use bevy_mod_scripting_core::{ + BMSScriptingInfrastructurePlugin, + bindings::{ + function::script_function::AppScriptFunctionRegistry, + globals::{AppScriptGlobalsRegistry, core::CoreScriptGlobalsPlugin}, + }, +}; use ladfile_builder::plugin::{LadFileSettings, ScriptingDocgenPlugin, generate_lad_file}; fn main() -> std::io::Result<()> { diff --git a/src/prelude.rs b/src/prelude.rs index bfb525cf08..775d7d6580 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,4 +1,3 @@ -pub use crate::{BMSPlugin, ScriptFunctionsPlugin}; pub use bevy_mod_scripting_core::{ ConfigureScriptAssetSettings, ConfigureScriptPlugin, IntoScriptPluginParams, asset::{Language, ScriptAsset}, @@ -13,8 +12,9 @@ pub use bevy_mod_scripting_core::{ handler::event_handler, script::{ScriptComponent, ScriptId}, }; - #[cfg(feature = "lua")] pub use bevy_mod_scripting_lua::LuaScriptingPlugin; #[cfg(feature = "rhai")] pub use bevy_mod_scripting_rhai::RhaiScriptingPlugin; + +pub use crate::{BMSPlugin, ScriptFunctionsPlugin}; diff --git a/tests/script_tests.rs b/tests/script_tests.rs index e3a58d383a..0134360599 100644 --- a/tests/script_tests.rs +++ b/tests/script_tests.rs @@ -4,7 +4,6 @@ use std::path::PathBuf; use libtest_mimic::{Arguments, Failed, Trial}; use script_integration_test_harness::{execute_integration_test, scenario::Scenario}; - use test_utils::{Test, discover_all_tests}; trait TestExecutor { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 5b8da93ebf..7541c068f1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,9 +1,3 @@ -use anyhow::{Context, *}; -use clap::Parser; -use itertools::Itertools; -use json_comments::StripComments; -use log::*; -use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, ffi::{OsStr, OsString}, @@ -12,6 +6,13 @@ use std::{ process::{Command, Output}, str::FromStr, }; + +use anyhow::{Context, *}; +use clap::Parser; +use itertools::Itertools; +use json_comments::StripComments; +use log::*; +use serde::{Deserialize, Serialize}; use strum::{IntoEnumIterator, VariantNames}; #[derive( From a39c0c362a03f35a3e257ddb5f47c9c19d70242a Mon Sep 17 00:00:00 2001 From: makspll Date: Thu, 21 Aug 2025 23:54:02 +0100 Subject: [PATCH 11/12] fix examples not actually getting checked by by CI or locally --- Cargo.toml | 7 +---- crates/bevy_api_gen/src/bin/main.rs | 5 +-- examples/game_of_life.rs | 49 ++++++----------------------- xtask/src/main.rs | 5 ++- 4 files changed, 17 insertions(+), 49 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b861179cb3..451d28cb4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -156,12 +156,7 @@ debug = true [[example]] name = "game_of_life" path = "examples/game_of_life.rs" -required-features = [ - "lua54", - "rhai", - "bevy/file_watcher", - "bevy/multi_threaded", -] +required-features = ["lua54", "rhai"] [[example]] name = "docgen" diff --git a/crates/bevy_api_gen/src/bin/main.rs b/crates/bevy_api_gen/src/bin/main.rs index 7725a3f27e..181352f065 100644 --- a/crates/bevy_api_gen/src/bin/main.rs +++ b/crates/bevy_api_gen/src/bin/main.rs @@ -52,8 +52,9 @@ fn main() { ); info!( - "Computing all transitive dependencies for enabled top-level features: {}", - args.features.join(",") + "Computing all transitive dependencies for enabled top-level features: {}. using default features: {}", + args.features.join(","), + !args.no_default_features ); let dependencies = feature_graph diff --git a/examples/game_of_life.rs b/examples/game_of_life.rs index 3acb6af3b6..4c769b462d 100644 --- a/examples/game_of_life.rs +++ b/examples/game_of_life.rs @@ -16,6 +16,7 @@ use bevy::{ }; use bevy_console::{AddConsoleCommand, ConsoleCommand, ConsoleOpen, ConsolePlugin, make_layer}; use bevy_mod_scripting::{core::bindings::AllocatorDiagnosticPlugin, prelude::*}; +use bevy_mod_scripting_core::{commands::RemoveStaticScript, script::StaticScripts}; use clap::Parser; // CONSOLE SETUP @@ -41,8 +42,7 @@ fn run_script_cmd( mut commands: Commands, asset_server: Res, script_comps: Query<(Entity, &ScriptComponent)>, - mut static_lua_scripts: Local>, - mut static_rhai_scripts: Local>, + static_scripts: Res, ) { if let Some(Ok(command)) = log.take() { match command { @@ -53,58 +53,27 @@ fn run_script_cmd( // create an entity with the script component bevy::log::info!("Using game of life script game_of_life.{}", language); - let script_path = format!("scripts/game_of_life.{}", language); + let script_path = format!("scripts/game_of_life.{language}"); if !use_static_script { bevy::log::info!("Spawning an entity with ScriptComponent"); commands.spawn(ScriptComponent::new(vec![asset_server.load(script_path)])); } else { bevy::log::info!("Using static script instead of spawning an entity"); let handle = asset_server.load(script_path); - if language == "lua" { - static_lua_scripts.push(handle.id()); - } else { - static_rhai_scripts.push(handle.id()); - } commands.queue(AddStaticScript::new(handle)) } } GameOfLifeCommand::Stop => { // we can simply drop the handle, or manually delete, I'll just drop the handle - bevy::log::info!("Stopping game of life by dropping the handles to all scripts"); - for (id, script_component) in &script_comps { - for script in &script_component.0 { - match script - .path() - .and_then(|p| p.get_full_extension()) - .unwrap_or_default() - .as_str() - { - "lua" => { - commands - .entity(id) - .queue(DeleteScript::::new(script.id())); - } - "rhai" => { - #[cfg(feature = "rhai")] - commands - .entity(id) - .queue(DeleteScript::::new(script.id())); - } - ext => { - warn!("Can't delete script with extension {ext:?}."); - } - } - } + bevy::log::info!( + "Stopping game of life by detaching each script and static script" + ); + for (id, _) in &script_comps { commands.entity(id).despawn(); } - for script in static_lua_scripts.drain(..) { - commands.queue(DeleteScript::::new(script)); - } - - #[cfg(feature = "rhai")] - for script in static_rhai_scripts.drain(..) { - commands.queue(DeleteScript::::new(script)); + for script in static_scripts.values() { + commands.queue(RemoveStaticScript::new(script.clone())); } } } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 7541c068f1..d7534cd88d 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -129,6 +129,7 @@ impl Default for Features { // should be kept up to date with the default feature + lua54 on top of anything that is handy to run locally every time Features::new(vec![ Feature::Lua54, + Feature::Rhai, Feature::CoreFunctions, Feature::BevyEcsBindings, Feature::BevyInputBindings, @@ -997,9 +998,11 @@ impl Xtasks { clippy_args.push("--message-format=json"); } + clippy_args.extend(["--all-targets", "--examples"]); + let keep_going = std::env::var(XTASK_KEEP_GOING).is_ok(); if !keep_going { - clippy_args.extend(vec!["--all-targets", "--", "-D", "warnings"]); + clippy_args.extend(vec!["--", "-D", "warnings"]); } Self::run_workspace_command( From 3da599c4bfe6f895e21d303cb3ceefe5044a4a3a Mon Sep 17 00:00:00 2001 From: makspll Date: Fri, 22 Aug 2025 00:26:09 +0100 Subject: [PATCH 12/12] fix never type coercion --- crates/bevy_mod_scripting_core/src/commands.rs | 1 - crates/languages/bevy_mod_scripting_rhai/src/lib.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/bevy_mod_scripting_core/src/commands.rs b/crates/bevy_mod_scripting_core/src/commands.rs index a437e8b9f4..2d87449429 100644 --- a/crates/bevy_mod_scripting_core/src/commands.rs +++ b/crates/bevy_mod_scripting_core/src/commands.rs @@ -262,7 +262,6 @@ impl CreateOrUpdateScript

{ if is_reload { phrase = "reloading"; success = "reloaded"; - script_state = Self::before_reload( attachment.clone(), guard.clone(), diff --git a/crates/languages/bevy_mod_scripting_rhai/src/lib.rs b/crates/languages/bevy_mod_scripting_rhai/src/lib.rs index 3100849ae7..acbbd201fd 100644 --- a/crates/languages/bevy_mod_scripting_rhai/src/lib.rs +++ b/crates/languages/bevy_mod_scripting_rhai/src/lib.rs @@ -219,7 +219,7 @@ fn load_rhai_content_into_context( pre_handling_initializers .iter() .try_for_each(|init| init(context_key, context))?; - runtime.eval_ast_with_scope(&mut context.scope, &context.ast)?; + runtime.eval_ast_with_scope::<()>(&mut context.scope, &context.ast)?; context.ast.clear_statements(); Ok(())