From bc7e17e58e5628e4d9be021dc3204f976274713f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Wed, 22 Apr 2026 09:04:03 -0600 Subject: [PATCH] chore: prepare 0.1.0 for crates.io publish Add LICENSE-MIT and LICENSE-APACHE at workspace root and in each member package so the dual MIT OR Apache-2.0 license ships in the published .crate. Fill in publish metadata (authors, repository, homepage, readme, keywords, categories) across the workspace and both members. Add CHANGELOG.md with a 0.1.0 initial release entry. Fix clippy lints: unused enumerate index, collapsible if, Default impls for TimerTable, SimRadio, and Ctx, use RangeInclusive::contains. Exclude examples/microwave_tui.rs from the published package. The file stays in-tree but has known unawaited async log futures that need a dedicated pass before it ships. Apply cargo fmt across the workspace. --- CHANGELOG.md | 43 + Cargo.toml | 3 + LICENSE-APACHE | 201 ++++ LICENSE-MIT | 21 + hsmc-macros/Cargo.toml | 6 + hsmc-macros/LICENSE-APACHE | 201 ++++ hsmc-macros/LICENSE-MIT | 21 + hsmc-macros/src/codegen.rs | 432 ++++--- hsmc-macros/src/ir.rs | 41 +- hsmc-macros/src/lib.rs | 6 +- hsmc-macros/src/parse.rs | 28 +- hsmc-macros/src/validate.rs | 33 +- hsmc/Cargo.toml | 12 +- hsmc/LICENSE-APACHE | 201 ++++ hsmc/LICENSE-MIT | 21 + hsmc/examples/during_radio.rs | 12 + hsmc/examples/microwave.rs | 5 +- hsmc/src/lib.rs | 31 +- hsmc/tests/behavior.rs | 1534 ++++++++++++++---------- hsmc/tests/during_concurrent.rs | 6 +- hsmc/tests/tokio_nested_alternation.rs | 22 +- hsmc/tests/tokio_repeat_and_payload.rs | 7 +- hsmc/tests/tokio_run.rs | 8 +- 23 files changed, 2046 insertions(+), 849 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 hsmc-macros/LICENSE-APACHE create mode 100644 hsmc-macros/LICENSE-MIT create mode 100644 hsmc/LICENSE-APACHE create mode 100644 hsmc/LICENSE-MIT diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..559ee3c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,43 @@ +# Changelog + +All notable changes to this workspace are documented here. The format +follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and +this project adheres to [Semantic Versioning](https://semver.org/). + +## 0.1.0 — 2026-04-22 + +Initial release. + +### Added + +- `statechart!` proc macro: declarative Harel-style hierarchical state + machines with nested states, `entry:` / `exit:` actions, LCA-aware + transitions, default-child descent, and `terminate` semantics. +- Typed event payload bindings: + `on(PacketRx { rssi: i16 }) => handler;` expands into a typed handler + signature, verified at compile time. +- Timer triggers: `on(after Duration::from_secs(5)) => Next;` and + `on(every Duration::from_millis(100)) => tick;`, tracked in a + fixed-capacity `TimerTable`. +- `during:` activities (v0.2 semantics): async functions that run + while a state is on the active path and produce events. Multiple + concurrent durings on a single state borrow disjoint `&mut` slices of + the context, enforced by Rust's native split-borrow. +- Runtime: `machine.run().await` races active durings, the external + event channel, and timer deadlines — one future, cooperative on + embassy, multi-threaded on tokio. +- Feature gates: `tokio` (std + tokio runtime), `embassy` (no_std + + embassy-time / embassy-sync). The two features are mutually + exclusive and enforced via `compile_error!`. +- `no_std` by default; `std` pulled in only via the `tokio` feature. +- `STATE_CHART` const and `dispatch()` helper for introspection. +- Workspace: `hsmc` (library) and `hsmc-macros` (proc-macro front-end) + both at `0.1.0`. + +### Docs + +- 320-line `README.md` with quickstart, semantics, and examples. +- Runnable examples: `microwave` and `during_radio` under tokio, + `embassy_full` under embassy. +- Behavior, hierarchy, during, timer, and payload-binding test suites + (13 integration tests). diff --git a/Cargo.toml b/Cargo.toml index 28f5e39..1e269ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,6 @@ members = ["hsmc", "hsmc-macros"] version = "0.1.0" edition = "2021" license = "MIT OR Apache-2.0" +authors = ["Stephen Waits "] +repository = "https://github.com/swaits/hsmc" +homepage = "https://github.com/swaits/hsmc" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d92df63 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for describing the origin of the Work and + reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Support. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or support. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Stephen Waits + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing permissions + and limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..694cb77 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Stephen Waits + +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. diff --git a/hsmc-macros/Cargo.toml b/hsmc-macros/Cargo.toml index 0a58664..dd749c0 100644 --- a/hsmc-macros/Cargo.toml +++ b/hsmc-macros/Cargo.toml @@ -3,7 +3,13 @@ name = "hsmc-macros" version.workspace = true edition.workspace = true license.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true description = "Procedural macro implementation for the hsmc crate." +readme = "../README.md" +keywords = ["statechart", "state-machine", "hsm", "macros", "proc-macro"] +categories = ["rust-patterns", "development-tools::procedural-macro-helpers"] [lib] proc-macro = true diff --git a/hsmc-macros/LICENSE-APACHE b/hsmc-macros/LICENSE-APACHE new file mode 100644 index 0000000..d92df63 --- /dev/null +++ b/hsmc-macros/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for describing the origin of the Work and + reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Support. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or support. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Stephen Waits + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing permissions + and limitations under the License. diff --git a/hsmc-macros/LICENSE-MIT b/hsmc-macros/LICENSE-MIT new file mode 100644 index 0000000..694cb77 --- /dev/null +++ b/hsmc-macros/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Stephen Waits + +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. diff --git a/hsmc-macros/src/codegen.rs b/hsmc-macros/src/codegen.rs index 1638e3c..53998b9 100644 --- a/hsmc-macros/src/codegen.rs +++ b/hsmc-macros/src/codegen.rs @@ -154,7 +154,7 @@ fn render_state( out.push('\n'); let child_prefix = format!("{}{}", prefix, if is_last { " " } else { "│ " }); // Entry actions - for (_i, aid) in s.entries.iter().enumerate() { + for aid in &s.entries { let name = &ir.actions[*aid as usize].name; out.push_str(&child_prefix); out.push_str("• entry: "); @@ -289,7 +289,8 @@ fn emit_embassy_race_arms_with_channel(ir: &Ir) -> Vec { let (sel_fn, variants) = embassy_select_for_arity(n + 2); let ch_variant = &variants[n]; let tm_variant = &variants[n + 1]; - let call_args = binds.iter() + let call_args = binds + .iter() .map(|b| quote! { #b }) .chain(std::iter::once(quote! { rx.receive() })) .chain(std::iter::once(quote! { timer_fut })); @@ -352,7 +353,8 @@ fn emit_embassy_race_arms_timer_only(ir: &Ir) -> Vec { } let (binds, stmts) = emit_during_bindings(&chain); let (sel_fn, variants) = embassy_select_for_arity(n + 1); - let call_args = binds.iter() + let call_args = binds + .iter() .map(|b| quote! { #b }) .chain(std::iter::once(quote! { timer_fut })); let either_path = if n + 1 == 2 { @@ -412,203 +414,275 @@ pub fn generate(ir: &Ir) -> TokenStream { .map(|s| s.name.clone()) .collect(); - let entries_of_arms: Vec<_> = ir.states.iter().map(|s| { - let sid = s.id; - let entries_tok: Vec<_> = s.entries.iter().map(|a| quote! { #a }).collect(); - quote! { #sid => &[#(#entries_tok),*], } - }).collect(); - let exits_of_arms: Vec<_> = ir.states.iter().map(|s| { - let sid = s.id; - let exits_tok: Vec<_> = s.exits.iter().map(|a| quote! { #a }).collect(); - quote! { #sid => &[#(#exits_tok),*], } - }).collect(); + let entries_of_arms: Vec<_> = ir + .states + .iter() + .map(|s| { + let sid = s.id; + let entries_tok: Vec<_> = s.entries.iter().map(|a| quote! { #a }).collect(); + quote! { #sid => &[#(#entries_tok),*], } + }) + .collect(); + let exits_of_arms: Vec<_> = ir + .states + .iter() + .map(|s| { + let sid = s.id; + let exits_tok: Vec<_> = s.exits.iter().map(|a| quote! { #a }).collect(); + quote! { #sid => &[#(#exits_tok),*], } + }) + .collect(); - let parent_table = ir.states.iter().map(|s| match s.parent { - Some(p) => quote! { Some(#p) }, - None => quote! { None }, - }).collect::>(); - let depth_table = ir.states.iter().map(|s| { - let d = s.depth; - quote! { #d } - }).collect::>(); - let default_child_table = ir.states.iter().map(|s| match s.default_child { - Some(c) => quote! { Some(#c) }, - None => quote! { None }, - }).collect::>(); - let state_id_to_variant_arms = ir.states.iter().filter(|s| s.parent.is_some()).map(|s| { - let id = s.id; - let nm = &s.name; - quote! { #id => #state_enum_name::#nm, } - }).collect::>(); + let parent_table = ir + .states + .iter() + .map(|s| match s.parent { + Some(p) => quote! { Some(#p) }, + None => quote! { None }, + }) + .collect::>(); + let depth_table = ir + .states + .iter() + .map(|s| { + let d = s.depth; + quote! { #d } + }) + .collect::>(); + let default_child_table = ir + .states + .iter() + .map(|s| match s.default_child { + Some(c) => quote! { Some(#c) }, + None => quote! { None }, + }) + .collect::>(); + let state_id_to_variant_arms = ir + .states + .iter() + .filter(|s| s.parent.is_some()) + .map(|s| { + let id = s.id; + let nm = &s.name; + quote! { #id => #state_enum_name::#nm, } + }) + .collect::>(); // Trait methods, possibly with typed params for payload-bearing actions. - let action_methods_sync = ir.actions.iter().map(|a| { - let name = &a.name; - let params = a.params.iter().map(|f| { - let n = &f.name; - let t = &f.ty; - quote! { #n: #t } - }); - quote! { fn #name(&mut self, #(#params),*); } - }).collect::>(); - let action_methods_async = ir.actions.iter().map(|a| { - let name = &a.name; - let params = a.params.iter().map(|f| { - let n = &f.name; - let t = &f.ty; - quote! { #n: #t } - }); - quote! { - fn #name(&mut self, #(#params),*) -> impl ::core::future::Future; - } - }).collect::>(); + let action_methods_sync = ir + .actions + .iter() + .map(|a| { + let name = &a.name; + let params = a.params.iter().map(|f| { + let n = &f.name; + let t = &f.ty; + quote! { #n: #t } + }); + quote! { fn #name(&mut self, #(#params),*); } + }) + .collect::>(); + let action_methods_async = ir + .actions + .iter() + .map(|a| { + let name = &a.name; + let params = a.params.iter().map(|f| { + let n = &f.name; + let t = &f.ty; + quote! { #n: #t } + }); + quote! { + fn #name(&mut self, #(#params),*) -> impl ::core::future::Future; + } + }) + .collect::>(); // Dispatch arms: for unit-signature actions call straight through; for // payload-bearing actions, re-match on the passed event and destructure. // Payload dispatch binds each field by reference (scrutinee is `&Ev`) // then `.clone()`s it to produce an owned value matching the handler's // declared signature. For `Copy` types this optimizes away. - let run_action_arms_sync = ir.actions.iter().enumerate().map(|(i, a)| { - let i = i as u16; - let name = &a.name; - if a.params.is_empty() { - quote! { #i => ::#name(ctx), } - } else { - let field_idents: Vec<_> = a.params.iter().map(|f| f.name.clone()).collect(); - let clone_args = field_idents.iter().map(|n| quote! { #n.clone() }); - let variant_arms = a.bound_variants.iter().map(|bv| { - let vname = &bv.name; - let binds = &field_idents; - let call = { - let clones = clone_args.clone(); - quote! { ::#name(ctx, #(#clones),*); } - }; - match bv.kind { - PayloadKind::Tuple => quote! { - #ev_ty::#vname(#(#binds),*) => { #call } - }, - PayloadKind::Struct => quote! { - #ev_ty::#vname { #(#binds),* } => { #call } - }, - } - }); - quote! { - #i => { - if let Some(__ev) = __event { - match __ev { - #(#variant_arms)* - _ => {} + let run_action_arms_sync = ir + .actions + .iter() + .enumerate() + .map(|(i, a)| { + let i = i as u16; + let name = &a.name; + if a.params.is_empty() { + quote! { #i => ::#name(ctx), } + } else { + let field_idents: Vec<_> = a.params.iter().map(|f| f.name.clone()).collect(); + let clone_args = field_idents.iter().map(|n| quote! { #n.clone() }); + let variant_arms = a.bound_variants.iter().map(|bv| { + let vname = &bv.name; + let binds = &field_idents; + let call = { + let clones = clone_args.clone(); + quote! { ::#name(ctx, #(#clones),*); } + }; + match bv.kind { + PayloadKind::Tuple => quote! { + #ev_ty::#vname(#(#binds),*) => { #call } + }, + PayloadKind::Struct => quote! { + #ev_ty::#vname { #(#binds),* } => { #call } + }, + } + }); + quote! { + #i => { + if let Some(__ev) = __event { + match __ev { + #(#variant_arms)* + _ => {} + } } } } } - } - }).collect::>(); - let run_action_arms_async = ir.actions.iter().enumerate().map(|(i, a)| { - let i = i as u16; - let name = &a.name; - if a.params.is_empty() { - quote! { #i => ::#name(ctx).await, } - } else { - let field_idents: Vec<_> = a.params.iter().map(|f| f.name.clone()).collect(); - let clone_args = field_idents.iter().map(|n| quote! { #n.clone() }); - let variant_arms = a.bound_variants.iter().map(|bv| { - let vname = &bv.name; - let binds = &field_idents; - let call = { - let clones = clone_args.clone(); - quote! { ::#name(ctx, #(#clones),*).await; } - }; - match bv.kind { - PayloadKind::Tuple => quote! { - #ev_ty::#vname(#(#binds),*) => { #call } - }, - PayloadKind::Struct => quote! { - #ev_ty::#vname { #(#binds),* } => { #call } - }, - } - }); - quote! { - #i => { - if let Some(__ev) = __event { - match __ev { - #(#variant_arms)* - _ => {} + }) + .collect::>(); + let run_action_arms_async = ir + .actions + .iter() + .enumerate() + .map(|(i, a)| { + let i = i as u16; + let name = &a.name; + if a.params.is_empty() { + quote! { #i => ::#name(ctx).await, } + } else { + let field_idents: Vec<_> = a.params.iter().map(|f| f.name.clone()).collect(); + let clone_args = field_idents.iter().map(|n| quote! { #n.clone() }); + let variant_arms = a.bound_variants.iter().map(|bv| { + let vname = &bv.name; + let binds = &field_idents; + let call = { + let clones = clone_args.clone(); + quote! { ::#name(ctx, #(#clones),*).await; } + }; + match bv.kind { + PayloadKind::Tuple => quote! { + #ev_ty::#vname(#(#binds),*) => { #call } + }, + PayloadKind::Struct => quote! { + #ev_ty::#vname { #(#binds),* } => { #call } + }, + } + }); + quote! { + #i => { + if let Some(__ev) = __event { + match __ev { + #(#variant_arms)* + _ => {} + } } } } } - } - }).collect::>(); - let duration_expr_arms = ir.duration_triggers.iter().enumerate().map(|(i, d)| { - let i = i as u16; - let expr = &d.expr; - quote! { #i => { let __d: ::hsmc::Duration = #expr; __d }, } - }).collect::>(); - let duration_repeat_arms = ir.duration_triggers.iter().enumerate().map(|(i, d)| { - let i = i as u16; - let repeat = d.repeat; - quote! { #i => #repeat, } - }).collect::>(); - let event_variant_arms = ir.event_variants.iter().enumerate().map(|(i, v)| { - let i = i as u16; - let name = &v.name; - let pat = match v.kind { - VariantKind::Unit => quote! { #ev_ty::#name }, - VariantKind::Tuple => quote! { #ev_ty::#name(..) }, - VariantKind::Struct => quote! { #ev_ty::#name { .. } }, - }; - quote! { #pat => #i, } - }).collect::>(); - let state_handler_arms = ir.states.iter().map(|s| { - use std::collections::BTreeMap; - #[derive(Default)] - struct Group { action_ids: Vec, transition_target: Option } - let mut groups: BTreeMap<(u8, u16), Group> = BTreeMap::new(); - let mut handlers = s.handlers.iter().collect::>(); - handlers.sort_by_key(|h| h.decl_index); - for h in handlers { - let key = match &h.trigger { - TriggerIr::Event(id, _, _) => (0u8, *id), - TriggerIr::Duration(id) => (1u8, *id), + }) + .collect::>(); + let duration_expr_arms = ir + .duration_triggers + .iter() + .enumerate() + .map(|(i, d)| { + let i = i as u16; + let expr = &d.expr; + quote! { #i => { let __d: ::hsmc::Duration = #expr; __d }, } + }) + .collect::>(); + let duration_repeat_arms = ir + .duration_triggers + .iter() + .enumerate() + .map(|(i, d)| { + let i = i as u16; + let repeat = d.repeat; + quote! { #i => #repeat, } + }) + .collect::>(); + let event_variant_arms = ir + .event_variants + .iter() + .enumerate() + .map(|(i, v)| { + let i = i as u16; + let name = &v.name; + let pat = match v.kind { + VariantKind::Unit => quote! { #ev_ty::#name }, + VariantKind::Tuple => quote! { #ev_ty::#name(..) }, + VariantKind::Struct => quote! { #ev_ty::#name { .. } }, }; - let g = groups.entry(key).or_default(); - match &h.kind { - HandlerKindIr::Action(aid, _) => g.action_ids.push(*aid), - HandlerKindIr::Transition(_, Some(tid)) => g.transition_target = Some(*tid), - HandlerKindIr::Transition(_, None) => {} + quote! { #pat => #i, } + }) + .collect::>(); + let state_handler_arms = ir + .states + .iter() + .map(|s| { + use std::collections::BTreeMap; + #[derive(Default)] + struct Group { + action_ids: Vec, + transition_target: Option, } - } - let sid = s.id; - let inner_arms = groups.iter().map(|((kind, tid), g)| { - let kind = *kind; - let tid = *tid; - let actions = g.action_ids.iter().map(|a| quote! { #a }); - let transition_tok = match g.transition_target { - Some(t) => quote! { Some(#t) }, - None => quote! { None }, - }; + let mut groups: BTreeMap<(u8, u16), Group> = BTreeMap::new(); + let mut handlers = s.handlers.iter().collect::>(); + handlers.sort_by_key(|h| h.decl_index); + for h in handlers { + let key = match &h.trigger { + TriggerIr::Event(id, _, _) => (0u8, *id), + TriggerIr::Duration(id) => (1u8, *id), + }; + let g = groups.entry(key).or_default(); + match &h.kind { + HandlerKindIr::Action(aid, _) => g.action_ids.push(*aid), + HandlerKindIr::Transition(_, Some(tid)) => g.transition_target = Some(*tid), + HandlerKindIr::Transition(_, None) => {} + } + } + let sid = s.id; + let inner_arms = groups + .iter() + .map(|((kind, tid), g)| { + let kind = *kind; + let tid = *tid; + let actions = g.action_ids.iter().map(|a| quote! { #a }); + let transition_tok = match g.transition_target { + Some(t) => quote! { Some(#t) }, + None => quote! { None }, + }; + quote! { + (#kind, #tid) => { + let actions: &'static [u16] = &[#(#actions),*]; + let target: Option = #transition_tok; + return Some((actions, target)); + } + } + }) + .collect::>(); quote! { - (#kind, #tid) => { - let actions: &'static [u16] = &[#(#actions),*]; - let target: Option = #transition_tok; - return Some((actions, target)); + #sid => { + match (trigger_kind, trigger_id) { + #(#inner_arms)* + _ => {} + } } } - }).collect::>(); - quote! { - #sid => { - match (trigger_kind, trigger_id) { - #(#inner_arms)* - _ => {} - } - } - } - }).collect::>(); - let owned_timers_arms = ir.states.iter().map(|s| { - let sid = s.id; - let ids = s.owned_timers.iter().map(|t| quote! { #t }); - quote! { #sid => &[#(#ids),*], } - }).collect::>(); + }) + .collect::>(); + let owned_timers_arms = ir + .states + .iter() + .map(|s| { + let sid = s.id; + let ids = s.owned_timers.iter().map(|t| quote! { #t }); + quote! { #sid => &[#(#ids),*], } + }) + .collect::>(); let terminate_match = if let Some(tev) = &ir.terminate_event { // Use the kind recorded for this variant (unit/tuple/struct). let kind = ir diff --git a/hsmc-macros/src/ir.rs b/hsmc-macros/src/ir.rs index 0dacc5f..cc61922 100644 --- a/hsmc-macros/src/ir.rs +++ b/hsmc-macros/src/ir.rs @@ -143,7 +143,13 @@ pub fn build_ir(input: StatechartInput) -> syn::Result { let name_span = ir.name.span(); let root_name = Ident::new("__Root", name_span); - let root_id = alloc_state(&mut ir, root_name, None, 0, root_body.default_span.unwrap_or(name_span)); + let root_id = alloc_state( + &mut ir, + root_name, + None, + 0, + root_body.default_span.unwrap_or(name_span), + ); lower_body(&mut ir, root_id, &root_body, true, &state_names)?; Ok(ir) @@ -271,11 +277,7 @@ fn params_match(a: &[PayloadField], b: &[PayloadField]) -> bool { }) } -fn intern_event( - ir: &mut Ir, - i: &Ident, - payload: Option<&EventPayload>, -) -> syn::Result { +fn intern_event(ir: &mut Ir, i: &Ident, payload: Option<&EventPayload>) -> syn::Result { let kind = match payload { None => VariantKind::Unit, Some(p) => match p.kind { @@ -348,13 +350,7 @@ fn variant_kind_name(k: VariantKind) -> &'static str { } } -fn intern_duration( - ir: &mut Ir, - expr: &Expr, - key: &str, - repeat: bool, - span: Span, -) -> u16 { +fn intern_duration(ir: &mut Ir, expr: &Expr, key: &str, repeat: bool, span: Span) -> u16 { let full_key = format!("{}:{}", key, repeat); if let Some(dt) = ir.duration_triggers.iter().find(|d| d.key == full_key) { return dt.id; @@ -395,7 +391,12 @@ fn lower_body( let id = intern_event(ir, variant, payload.as_ref())?; TriggerIr::Event(id, variant.clone(), payload.clone()) } - Trigger::Duration { expr, key, span, repeat } => { + Trigger::Duration { + expr, + key, + span, + repeat, + } => { let id = intern_duration(ir, expr, key, *repeat, *span); let owned = &mut ir.states[state_id as usize].owned_timers; if !owned.contains(&id) { @@ -477,13 +478,9 @@ fn classify_target( } else { // Action handler. let aid = match trig { - TriggerIr::Event(_, variant, Some(payload)) => intern_action_with_params( - ir, - target, - &payload.fields, - variant, - payload.kind, - )?, + TriggerIr::Event(_, variant, Some(payload)) => { + intern_action_with_params(ir, target, &payload.fields, variant, payload.kind)? + } _ => intern_action_unit(ir, target)?, }; Ok(HandlerKindIr::Action(aid, target.clone())) @@ -495,7 +492,7 @@ pub fn resolve_transitions(ir: &mut Ir) -> syn::Result<()> { let mut name_map = std::collections::HashMap::new(); for s in &ir.states { if s.name != "__Root" { - if name_map.insert(s.name.to_string(), s.id).is_some() {} + name_map.insert(s.name.to_string(), s.id); } } diff --git a/hsmc-macros/src/lib.rs b/hsmc-macros/src/lib.rs index b19c526..de3855a 100644 --- a/hsmc-macros/src/lib.rs +++ b/hsmc-macros/src/lib.rs @@ -4,10 +4,10 @@ use proc_macro::TokenStream; -mod parse; -mod ir; -mod validate; mod codegen; +mod ir; +mod parse; +mod validate; /// See the `hsmc` crate for documentation. #[proc_macro] diff --git a/hsmc-macros/src/parse.rs b/hsmc-macros/src/parse.rs index 04d1028..8371348 100644 --- a/hsmc-macros/src/parse.rs +++ b/hsmc-macros/src/parse.rs @@ -176,7 +176,10 @@ fn parse_body(input: ParseStream, is_root: bool) -> syn::Result { let ty: Type = input.parse()?; input.parse::()?; if !is_root { - return Err(syn::Error::new(ident.span(), "`context:` is only valid at root")); + return Err(syn::Error::new( + ident.span(), + "`context:` is only valid at root", + )); } body.context_ty = Some(ty); } @@ -186,7 +189,10 @@ fn parse_body(input: ParseStream, is_root: bool) -> syn::Result { let ty: Type = input.parse()?; input.parse::()?; if !is_root { - return Err(syn::Error::new(ident.span(), "`events:` is only valid at root")); + return Err(syn::Error::new( + ident.span(), + "`events:` is only valid at root", + )); } body.event_ty = Some(ty); } @@ -290,10 +296,17 @@ fn parse_body(input: ParseStream, is_root: bool) -> syn::Result { let content; braced!(content in input); let cbody = parse_body(&content, false)?; - body.children.push(StateDecl { name: sname.clone(), body: cbody, span: sname.span() }); + body.children.push(StateDecl { + name: sname.clone(), + body: cbody, + span: sname.span(), + }); } other => { - return Err(syn::Error::new(ident.span(), format!("unknown item `{}` in statechart body", other))); + return Err(syn::Error::new( + ident.span(), + format!("unknown item `{}` in statechart body", other), + )); } } } else { @@ -423,7 +436,12 @@ fn parse_duration_rest(input: ParseStream, repeat: bool) -> syn::Result } } let key = expr_to_string(&expr); - Ok(Trigger::Duration { expr, key, span, repeat }) + Ok(Trigger::Duration { + expr, + key, + span, + repeat, + }) } fn expr_to_string(e: &Expr) -> String { diff --git a/hsmc-macros/src/validate.rs b/hsmc-macros/src/validate.rs index 42a41b2..4829e36 100644 --- a/hsmc-macros/src/validate.rs +++ b/hsmc-macros/src/validate.rs @@ -15,7 +15,10 @@ pub fn validate(ir: &Ir) -> syn::Result<()> { continue; } if let Some(_prev) = seen.insert(s.name.to_string(), s.id) { - return Err(syn::Error::new(s.span, format!("duplicate state name `{}`", s.name))); + return Err(syn::Error::new( + s.span, + format!("duplicate state name `{}`", s.name), + )); } } @@ -90,7 +93,10 @@ pub fn validate(ir: &Ir) -> syn::Result<()> { if !s.children.is_empty() && s.default_child.is_none() { return Err(syn::Error::new( s.span, - format!("state `{}` has children but no `default` declaration", s.name), + format!( + "state `{}` has children but no `default` declaration", + s.name + ), )); } @@ -118,7 +124,10 @@ pub fn validate(ir: &Ir) -> syn::Result<()> { if let Some(_prev) = trig_txn_seen.insert(key.clone(), h.decl_index) { return Err(syn::Error::new( trig_span, - format!("duplicate transition on trigger `{}` in state `{}`", trig_display, s.name), + format!( + "duplicate transition on trigger `{}` in state `{}`", + trig_display, s.name + ), )); } if !name_map.contains_key(&target.to_string()) { @@ -181,25 +190,35 @@ pub fn validate_parse_tree(input: &StatechartInput) -> syn::Result<()> { fn validate_body(body: &StateBody, is_root: bool, state_name: &str) -> syn::Result<()> { if body.default_count > 1 { return Err(syn::Error::new( - body.default_span.unwrap_or_else(proc_macro2::Span::call_site), + body.default_span + .unwrap_or_else(proc_macro2::Span::call_site), format!("multiple `default` declarations in state `{}`", state_name), )); } if body.terminate_count > 1 { return Err(syn::Error::new( - body.terminate.as_ref().map(|(_, s)| *s).unwrap_or_else(proc_macro2::Span::call_site), + body.terminate + .as_ref() + .map(|(_, s)| *s) + .unwrap_or_else(proc_macro2::Span::call_site), "multiple `terminate` declarations", )); } if !is_root { if let Some((_, span)) = &body.terminate { - return Err(syn::Error::new(*span, "`terminate` is only valid at the root level")); + return Err(syn::Error::new( + *span, + "`terminate` is only valid at the root level", + )); } } if body.default_child.is_some() && body.children.is_empty() { return Err(syn::Error::new( body.default_span.unwrap(), - format!("`default` in state `{}` which has no child states", state_name), + format!( + "`default` in state `{}` which has no child states", + state_name + ), )); } if let (Some((dc, dspan)), false) = (&body.default_child, body.children.is_empty()) { diff --git a/hsmc/Cargo.toml b/hsmc/Cargo.toml index 8cb6d77..3864bf6 100644 --- a/hsmc/Cargo.toml +++ b/hsmc/Cargo.toml @@ -3,7 +3,15 @@ name = "hsmc" version.workspace = true edition.workspace = true license.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true description = "Hierarchical state machines (statecharts) with a declarative proc macro." +readme = "../README.md" +keywords = ["statechart", "state-machine", "hsm", "embassy", "embedded"] +categories = ["embedded", "no-std", "asynchronous", "rust-patterns"] +autoexamples = false +exclude = ["examples/microwave_tui.rs"] [features] default = [] @@ -29,10 +37,6 @@ futures = "0.3" name = "microwave" required-features = ["tokio"] -[[example]] -name = "microwave_tui" -required-features = ["tokio"] - [[example]] name = "during_radio" required-features = ["tokio"] diff --git a/hsmc/LICENSE-APACHE b/hsmc/LICENSE-APACHE new file mode 100644 index 0000000..d92df63 --- /dev/null +++ b/hsmc/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for describing the origin of the Work and + reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Support. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or support. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Stephen Waits + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing permissions + and limitations under the License. diff --git a/hsmc/LICENSE-MIT b/hsmc/LICENSE-MIT new file mode 100644 index 0000000..694cb77 --- /dev/null +++ b/hsmc/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Stephen Waits + +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. diff --git a/hsmc/examples/during_radio.rs b/hsmc/examples/during_radio.rs index f4de362..67b8dc4 100644 --- a/hsmc/examples/during_radio.rs +++ b/hsmc/examples/during_radio.rs @@ -23,6 +23,12 @@ pub struct SimRadio { tx_pending: bool, } +impl Default for SimRadio { + fn default() -> Self { + Self::new() + } +} + impl SimRadio { pub fn new() -> Self { Self { @@ -57,6 +63,12 @@ pub struct Ctx { pub last_payload: heapless::Vec, } +impl Default for Ctx { + fn default() -> Self { + Self::new() + } +} + impl Ctx { pub fn new() -> Self { Self { diff --git a/hsmc/examples/microwave.rs b/hsmc/examples/microwave.rs index fe0ee1a..52ba18d 100644 --- a/hsmc/examples/microwave.rs +++ b/hsmc/examples/microwave.rs @@ -301,7 +301,10 @@ impl OvenActions for OvenActionContext<'_> { #[tokio::main(flavor = "current_thread")] async fn main() { let hw = Arc::new(Mutex::new(Hardware::default())); - let ctx = OvenContext { hw: Arc::clone(&hw), ..Default::default() }; + let ctx = OvenContext { + hw: Arc::clone(&hw), + ..Default::default() + }; // `with_queue_capacity::` overrides the default queue size (8). We // pick 16 to comfortably hold the burst of events below. diff --git a/hsmc/src/lib.rs b/hsmc/src/lib.rs index 924d41e..09d86ee 100644 --- a/hsmc/src/lib.rs +++ b/hsmc/src/lib.rs @@ -118,7 +118,9 @@ pub mod __private { impl EventQueue { pub const fn new() -> Self { - Self { inner: heapless::Deque::new() } + Self { + inner: heapless::Deque::new(), + } } pub fn push(&mut self, ev: E) -> Result<(), HsmcError> { self.inner.push_back(ev).map_err(|_| HsmcError::QueueFull) @@ -135,7 +137,9 @@ pub mod __private { } impl Default for EventQueue { - fn default() -> Self { Self::new() } + fn default() -> Self { + Self::new() + } } /// A fixed-capacity timer table: `(state_index, trigger_index, remaining_nanos)`. @@ -150,9 +154,17 @@ pub mod __private { pub remaining_ns: u128, } + impl Default for TimerTable { + fn default() -> Self { + Self::new() + } + } + impl TimerTable { pub const fn new() -> Self { - Self { entries: heapless::Vec::new() } + Self { + entries: heapless::Vec::new(), + } } pub fn start(&mut self, state: u16, trigger: u16, duration: core::time::Duration) { let ns = duration.as_nanos(); @@ -163,13 +175,18 @@ pub mod __private { return; } } - let _ = self.entries.push(TimerEntry { state, trigger, remaining_ns: ns }); + let _ = self.entries.push(TimerEntry { + state, + trigger, + remaining_ns: ns, + }); } pub fn cancel_state(&mut self, state: u16) { self.entries.retain(|e| e.state != state); } pub fn cancel_one(&mut self, state: u16, trigger: u16) { - self.entries.retain(|e| !(e.state == state && e.trigger == trigger)); + self.entries + .retain(|e| !(e.state == state && e.trigger == trigger)); } pub fn decrement(&mut self, elapsed: core::time::Duration) { let ns = elapsed.as_nanos(); @@ -198,7 +215,9 @@ pub mod __private { if let Some(i) = best { let e = self.entries.swap_remove(i); Some((e.state, e.trigger)) - } else { None } + } else { + None + } } pub fn min_remaining(&self) -> Option { self.entries.iter().map(|e| e.remaining_ns).min().map(|ns| { diff --git a/hsmc/tests/behavior.rs b/hsmc/tests/behavior.rs index 658b43b..b6a7787 100644 --- a/hsmc/tests/behavior.rs +++ b/hsmc/tests/behavior.rs @@ -24,25 +24,33 @@ impl TestCtx { mod t1_1 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _Unused } + pub enum Ev { + _Unused, + } statechart! { -T11 { - context: TestCtx; - events: Ev; - default(Red); - entry: do_post; - state Red { - entry: red_on; - exit: red_off; + T11 { + context: TestCtx; + events: Ev; + default(Red); + entry: do_post; + state Red { + entry: red_on; + exit: red_off; + } + } } - } - } impl T11Actions for T11ActionContext<'_> { - fn do_post(&mut self) { self.log.push("do_post".into()); } - fn red_on(&mut self) { self.log.push("red_on".into()); } - fn red_off(&mut self) { self.log.push("red_off".into()); } + fn do_post(&mut self) { + self.log.push("do_post".into()); + } + fn red_on(&mut self) { + self.log.push("red_on".into()); + } + fn red_off(&mut self) { + self.log.push("red_off".into()); + } } #[test] @@ -59,38 +67,51 @@ T11 { mod t1_2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _Unused } + pub enum Ev { + _Unused, + } statechart! { -T12 { - context: TestCtx; - events: Ev; - default(A); - entry: r_entry; - state A { - entry: a_entry; - default(B); - state B { - entry: b_entry; - default(C); - state C { entry: c_entry; } + T12 { + context: TestCtx; + events: Ev; + default(A); + entry: r_entry; + state A { + entry: a_entry; + default(B); + state B { + entry: b_entry; + default(C); + state C { entry: c_entry; } + } } } - } - } + } impl T12Actions for T12ActionContext<'_> { - fn r_entry(&mut self) { self.log.push("r_entry".into()); } - fn a_entry(&mut self) { self.log.push("a_entry".into()); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } - fn c_entry(&mut self) { self.log.push("c_entry".into()); } + fn r_entry(&mut self) { + self.log.push("r_entry".into()); + } + fn a_entry(&mut self) { + self.log.push("a_entry".into()); + } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } + fn c_entry(&mut self) { + self.log.push("c_entry".into()); + } } #[test] fn t1_2_nested_default() { let mut m = T12::new(TestCtx::default()); m.step(Duration::ZERO); - assert_eq!(m.context().logs(), ["r_entry", "a_entry", "b_entry", "c_entry"]); + assert_eq!( + m.context().logs(), + ["r_entry", "a_entry", "b_entry", "c_entry"] + ); assert_eq!(m.current_state(), T12State::C); } } @@ -99,32 +120,43 @@ T12 { mod t2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { GoGreen, Reset } + pub enum Ev { + GoGreen, + Reset, + } statechart! { -T2A { - context: TestCtx; - events: Ev; - default(Red); - state Red { - entry: red_on; - exit: red_off; - on(GoGreen) => Green; - on(Reset) => Red; - on(after Duration::from_millis(200)) => Green; + T2A { + context: TestCtx; + events: Ev; + default(Red); + state Red { + entry: red_on; + exit: red_off; + on(GoGreen) => Green; + on(Reset) => Red; + on(after Duration::from_millis(200)) => Green; + } + state Green { + entry: green_on; + exit: green_off; + } } - state Green { - entry: green_on; - exit: green_off; } - } - } impl T2AActions for T2AActionContext<'_> { - fn red_on(&mut self) { self.log.push("red_on".into()); } - fn red_off(&mut self) { self.log.push("red_off".into()); } - fn green_on(&mut self) { self.log.push("green_on".into()); } - fn green_off(&mut self) { self.log.push("green_off".into()); } + fn red_on(&mut self) { + self.log.push("red_on".into()); + } + fn red_off(&mut self) { + self.log.push("red_off".into()); + } + fn green_on(&mut self) { + self.log.push("green_on".into()); + } + fn green_off(&mut self) { + self.log.push("green_off".into()); + } } #[test] @@ -165,28 +197,38 @@ T2A { mod t3_3 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go } + pub enum Ev { + Go, + } statechart! { -T33 { - context: TestCtx; - events: Ev; - default(Red); - state Red { - exit: red_off; - on(Go) => log_go; - on(Go) => prepare; - on(Go) => Green; + T33 { + context: TestCtx; + events: Ev; + default(Red); + state Red { + exit: red_off; + on(Go) => log_go; + on(Go) => prepare; + on(Go) => Green; + } + state Green { entry: green_on; } + } } - state Green { entry: green_on; } - } - } impl T33Actions for T33ActionContext<'_> { - fn log_go(&mut self) { self.log.push("log_go".into()); } - fn prepare(&mut self) { self.log.push("prepare".into()); } - fn red_off(&mut self) { self.log.push("red_off".into()); } - fn green_on(&mut self) { self.log.push("green_on".into()); } + fn log_go(&mut self) { + self.log.push("log_go".into()); + } + fn prepare(&mut self) { + self.log.push("prepare".into()); + } + fn red_off(&mut self) { + self.log.push("red_off".into()); + } + fn green_on(&mut self) { + self.log.push("green_on".into()); + } } #[test] @@ -195,7 +237,10 @@ T33 { m.step(Duration::ZERO); m.send(Ev::Go).unwrap(); m.step(Duration::ZERO); - assert_eq!(m.context().logs(), ["log_go", "prepare", "red_off", "green_on"]); + assert_eq!( + m.context().logs(), + ["log_go", "prepare", "red_off", "green_on"] + ); assert_eq!(m.current_state(), T33State::Green); } } @@ -204,21 +249,27 @@ T33 { mod t2_2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _Unused } + pub enum Ev { + _Unused, + } statechart! { -T22 { - context: TestCtx; - events: Ev; - default(Red); - state Red { on(after Duration::from_secs(5)) => Green; exit: red_off; } - state Green { entry: green_on; } - } - } + T22 { + context: TestCtx; + events: Ev; + default(Red); + state Red { on(after Duration::from_secs(5)) => Green; exit: red_off; } + state Green { entry: green_on; } + } + } impl T22Actions for T22ActionContext<'_> { - fn red_off(&mut self) { self.log.push("red_off".into()); } - fn green_on(&mut self) { self.log.push("green_on".into()); } + fn red_off(&mut self) { + self.log.push("red_off".into()); + } + fn green_on(&mut self) { + self.log.push("green_on".into()); + } } #[test] @@ -237,32 +288,42 @@ T22 { mod t4_2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo } + pub enum Ev { + Foo, + } statechart! { -T42 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - exit: a_exit; - on(Foo) => D; - state B { - default(C); - exit: b_exit; - state C { exit: c_exit; } + T42 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + exit: a_exit; + on(Foo) => D; + state B { + default(C); + exit: b_exit; + state C { exit: c_exit; } + } } + state D { entry: d_entry; } + } } - state D { entry: d_entry; } - } - } impl T42Actions for T42ActionContext<'_> { - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_exit(&mut self) { self.log.push("b_exit".into()); } - fn c_exit(&mut self) { self.log.push("c_exit".into()); } - fn d_entry(&mut self) { self.log.push("d_entry".into()); } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_exit(&mut self) { + self.log.push("b_exit".into()); + } + fn c_exit(&mut self) { + self.log.push("c_exit".into()); + } + fn d_entry(&mut self) { + self.log.push("d_entry".into()); + } } #[test] @@ -273,7 +334,10 @@ T42 { m.send(Ev::Foo).unwrap(); m.step(Duration::ZERO); assert_eq!(m.current_state(), T42State::D); - assert_eq!(m.context().logs(), ["c_exit", "b_exit", "a_exit", "d_entry"]); + assert_eq!( + m.context().logs(), + ["c_exit", "b_exit", "a_exit", "d_entry"] + ); } } @@ -281,32 +345,42 @@ T42 { mod t6_1 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Halt } + pub enum Ev { + Halt, + } statechart! { -T61 { - context: TestCtx; - events: Ev; - default(A); - terminate(Halt); - exit: root_exit; - state A { - default(B); - exit: a_exit; - state B { - default(C); - exit: b_exit; - state C { exit: c_exit; } + T61 { + context: TestCtx; + events: Ev; + default(A); + terminate(Halt); + exit: root_exit; + state A { + default(B); + exit: a_exit; + state B { + default(C); + exit: b_exit; + state C { exit: c_exit; } + } } } - } - } + } impl T61Actions for T61ActionContext<'_> { - fn root_exit(&mut self) { self.log.push("root_exit".into()); } - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_exit(&mut self) { self.log.push("b_exit".into()); } - fn c_exit(&mut self) { self.log.push("c_exit".into()); } + fn root_exit(&mut self) { + self.log.push("root_exit".into()); + } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_exit(&mut self) { + self.log.push("b_exit".into()); + } + fn c_exit(&mut self) { + self.log.push("c_exit".into()); + } } #[test] @@ -316,7 +390,10 @@ T61 { m.send(Ev::Halt).unwrap(); m.step(Duration::ZERO); assert!(m.is_terminated()); - assert_eq!(m.context().logs(), ["c_exit", "b_exit", "a_exit", "root_exit"]); + assert_eq!( + m.context().logs(), + ["c_exit", "b_exit", "a_exit", "root_exit"] + ); assert!(m.step(Duration::ZERO).is_none()); } } @@ -325,27 +402,32 @@ T61 { mod t7_1 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo, Bar } + pub enum Ev { + Foo, + Bar, + } statechart! { -T71 { - context: TestCtx; - events: Ev; - default(A); - state A { - on(Foo) => emit_bar; - on(Bar) => B; + T71 { + context: TestCtx; + events: Ev; + default(A); + state A { + on(Foo) => emit_bar; + on(Bar) => B; + } + state B { entry: b_entry; } + } } - state B { entry: b_entry; } - } - } impl T71Actions for T71ActionContext<'_> { fn emit_bar(&mut self) { self.log.push("emit_bar".into()); self.emit(Ev::Bar).unwrap(); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } } #[test] @@ -365,21 +447,27 @@ T71 { mod t1_3 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T13 { - context: TestCtx; - events: Ev; - default(Red); - entry: r_entry; - state Red { entry: red_on; } - } - } + T13 { + context: TestCtx; + events: Ev; + default(Red); + entry: r_entry; + state Red { entry: red_on; } + } + } impl T13Actions for T13ActionContext<'_> { - fn r_entry(&mut self) { self.log.push("r_entry".into()); } - fn red_on(&mut self) { self.log.push("red_on".into()); } + fn r_entry(&mut self) { + self.log.push("r_entry".into()); + } + fn red_on(&mut self) { + self.log.push("red_on".into()); + } } #[test] @@ -394,25 +482,31 @@ T13 { mod t2_3 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { EarlyExit } + pub enum Ev { + EarlyExit, + } statechart! { -T23 { - context: TestCtx; - events: Ev; - default(Red); - state Red { - on(after Duration::from_secs(5)) => Green; - on(EarlyExit) => Yellow; + T23 { + context: TestCtx; + events: Ev; + default(Red); + state Red { + on(after Duration::from_secs(5)) => Green; + on(EarlyExit) => Yellow; + } + state Green { entry: green_on; } + state Yellow { entry: yellow_on; } + } } - state Green { entry: green_on; } - state Yellow { entry: yellow_on; } - } - } impl T23Actions for T23ActionContext<'_> { - fn green_on(&mut self) { self.log.push("green_on".into()); } - fn yellow_on(&mut self) { self.log.push("yellow_on".into()); } + fn green_on(&mut self) { + self.log.push("green_on".into()); + } + fn yellow_on(&mut self) { + self.log.push("yellow_on".into()); + } } #[test] @@ -432,34 +526,44 @@ T23 { mod t2_4 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Jump } + pub enum Ev { + Jump, + } statechart! { -T24 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - exit: a_exit; - state B { - default(C); - exit: b_exit; - state C { - exit: c_exit; - on(Jump) => D; + T24 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + exit: a_exit; + state B { + default(C); + exit: b_exit; + state C { + exit: c_exit; + on(Jump) => D; + } } } + state D { entry: d_entry; } + } } - state D { entry: d_entry; } - } - } impl T24Actions for T24ActionContext<'_> { - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_exit(&mut self) { self.log.push("b_exit".into()); } - fn c_exit(&mut self) { self.log.push("c_exit".into()); } - fn d_entry(&mut self) { self.log.push("d_entry".into()); } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_exit(&mut self) { + self.log.push("b_exit".into()); + } + fn c_exit(&mut self) { + self.log.push("c_exit".into()); + } + fn d_entry(&mut self) { + self.log.push("d_entry".into()); + } } #[test] @@ -469,7 +573,10 @@ T24 { m.send(Ev::Jump).unwrap(); m.step(Duration::ZERO); assert_eq!(m.current_state(), T24State::D); - assert_eq!(m.context().logs(), ["c_exit", "b_exit", "a_exit", "d_entry"]); + assert_eq!( + m.context().logs(), + ["c_exit", "b_exit", "a_exit", "d_entry"] + ); } } @@ -477,30 +584,38 @@ T24 { mod t2_5 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go } + pub enum Ev { + Go, + } statechart! { -T25 { - context: TestCtx; - events: Ev; - default(A); - state A { on(Go) => B; } - state B { - default(C); - entry: b_entry; - state C { - default(D); - entry: c_entry; - state D { entry: d_entry; } + T25 { + context: TestCtx; + events: Ev; + default(A); + state A { on(Go) => B; } + state B { + default(C); + entry: b_entry; + state C { + default(D); + entry: c_entry; + state D { entry: d_entry; } + } } } - } - } + } impl T25Actions for T25ActionContext<'_> { - fn b_entry(&mut self) { self.log.push("b_entry".into()); } - fn c_entry(&mut self) { self.log.push("c_entry".into()); } - fn d_entry(&mut self) { self.log.push("d_entry".into()); } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } + fn c_entry(&mut self) { + self.log.push("c_entry".into()); + } + fn d_entry(&mut self) { + self.log.push("d_entry".into()); + } } #[test] @@ -518,26 +633,34 @@ T25 { mod t2_7 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go } + pub enum Ev { + Go, + } statechart! { -T27 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - exit: a_exit; - state B { exit: b_exit; on(Go) => C; } + T27 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + exit: a_exit; + state B { exit: b_exit; on(Go) => C; } + } + state C { entry: c_entry; } + } } - state C { entry: c_entry; } - } - } impl T27Actions for T27ActionContext<'_> { - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_exit(&mut self) { self.log.push("b_exit".into()); } - fn c_entry(&mut self) { self.log.push("c_entry".into()); } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_exit(&mut self) { + self.log.push("b_exit".into()); + } + fn c_entry(&mut self) { + self.log.push("c_entry".into()); + } } #[test] @@ -555,31 +678,41 @@ T27 { mod t2_8 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Up } + pub enum Ev { + Up, + } statechart! { -T28 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - entry: a_entry; - exit: a_exit; - state B { - entry: b_entry; - exit: b_exit; - on(Up) => A; + T28 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + entry: a_entry; + exit: a_exit; + state B { + entry: b_entry; + exit: b_exit; + on(Up) => A; + } } } - } - } + } impl T28Actions for T28ActionContext<'_> { - fn a_entry(&mut self) { self.log.push("a_entry".into()); } - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } - fn b_exit(&mut self) { self.log.push("b_exit".into()); } + fn a_entry(&mut self) { + self.log.push("a_entry".into()); + } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } + fn b_exit(&mut self) { + self.log.push("b_exit".into()); + } } #[test] @@ -591,7 +724,10 @@ T28 { m.send(Ev::Up).unwrap(); m.step(Duration::ZERO); assert_eq!(m.current_state(), T28State::B); - assert_eq!(m.context().logs(), ["b_exit", "a_exit", "a_entry", "b_entry"]); + assert_eq!( + m.context().logs(), + ["b_exit", "a_exit", "a_entry", "b_entry"] + ); } } @@ -599,25 +735,33 @@ T28 { mod t3_12 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Beep } + pub enum Ev { + Beep, + } statechart! { -T312 { - context: TestCtx; - events: Ev; - default(Red); - state Red { - on(Beep) => honk1; - on(Beep) => honk2; - on(Beep) => honk3; + T312 { + context: TestCtx; + events: Ev; + default(Red); + state Red { + on(Beep) => honk1; + on(Beep) => honk2; + on(Beep) => honk3; + } + } } - } - } impl T312Actions for T312ActionContext<'_> { - fn honk1(&mut self) { self.log.push("honk1".into()); } - fn honk2(&mut self) { self.log.push("honk2".into()); } - fn honk3(&mut self) { self.log.push("honk3".into()); } + fn honk1(&mut self) { + self.log.push("honk1".into()); + } + fn honk2(&mut self) { + self.log.push("honk2".into()); + } + fn honk3(&mut self) { + self.log.push("honk3".into()); + } } #[test] @@ -635,21 +779,25 @@ T312 { mod t3_4 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T34 { - context: TestCtx; - events: Ev; - default(Red); - state Red { - on(after Duration::from_millis(500)) => heartbeat; + T34 { + context: TestCtx; + events: Ev; + default(Red); + state Red { + on(after Duration::from_millis(500)) => heartbeat; + } + } } - } - } impl T34Actions for T34ActionContext<'_> { - fn heartbeat(&mut self) { self.log.push("beat".into()); } + fn heartbeat(&mut self) { + self.log.push("beat".into()); + } } #[test] @@ -670,27 +818,33 @@ T34 { mod t4_misc { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo, Unknown } + pub enum Ev { + Foo, + Unknown, + } statechart! { -T4M { - context: TestCtx; - events: Ev; - default(A); - on(Foo) => root_handler; - state A { - default(B); - state B { - default(C); - state C { entry: c_entry; } + T4M { + context: TestCtx; + events: Ev; + default(A); + on(Foo) => root_handler; + state A { + default(B); + state B { + default(C); + state C { entry: c_entry; } + } } } - } - } + } impl T4MActions for T4MActionContext<'_> { - fn root_handler(&mut self) { self.log.push("root".into()); } - fn c_entry(&mut self) { /* nop */ } + fn root_handler(&mut self) { + self.log.push("root".into()); + } + fn c_entry(&mut self) { /* nop */ + } } #[test] @@ -716,26 +870,32 @@ T4M { mod t4_14 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo } + pub enum Ev { + Foo, + } statechart! { -T414 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(C); - on(Foo) => E; - state C { on(Foo) => D; } + T414 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(C); + on(Foo) => E; + state C { on(Foo) => D; } + } + state D { entry: d_entry; } + state E { entry: e_entry; } + } } - state D { entry: d_entry; } - state E { entry: e_entry; } - } - } impl T414Actions for T414ActionContext<'_> { - fn d_entry(&mut self) { self.log.push("d_entry".into()); } - fn e_entry(&mut self) { self.log.push("e_entry".into()); } + fn d_entry(&mut self) { + self.log.push("d_entry".into()); + } + fn e_entry(&mut self) { + self.log.push("e_entry".into()); + } } #[test] @@ -754,28 +914,33 @@ T414 { mod t4_6 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T46 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - on(after Duration::from_secs(10)) => D; - state B { - default(C); - state C { entry: c_entry; } + T46 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + on(after Duration::from_secs(10)) => D; + state B { + default(C); + state C { entry: c_entry; } + } } + state D { entry: d_entry; } + } } - state D { entry: d_entry; } - } - } impl T46Actions for T46ActionContext<'_> { - fn d_entry(&mut self) { self.log.push("d_entry".into()); } - fn c_entry(&mut self) { /* nop */ } + fn d_entry(&mut self) { + self.log.push("d_entry".into()); + } + fn c_entry(&mut self) { /* nop */ + } } #[test] @@ -792,38 +957,56 @@ T46 { mod t5 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go } + pub enum Ev { + Go, + } statechart! { -T5X { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - entry: alpha, beta; - entry: gamma; - exit: cleanup1; - exit: cleanup2; - state B { - entry: b_entry; - exit: b_exit; - on(Go) => Z; + T5X { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + entry: alpha, beta; + entry: gamma; + exit: cleanup1; + exit: cleanup2; + state B { + entry: b_entry; + exit: b_exit; + on(Go) => Z; + } } + state Z { entry: z_entry; } + } } - state Z { entry: z_entry; } - } - } impl T5XActions for T5XActionContext<'_> { - fn alpha(&mut self) { self.log.push("alpha".into()); } - fn beta(&mut self) { self.log.push("beta".into()); } - fn gamma(&mut self) { self.log.push("gamma".into()); } - fn cleanup1(&mut self) { self.log.push("cleanup1".into()); } - fn cleanup2(&mut self) { self.log.push("cleanup2".into()); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } - fn b_exit(&mut self) { self.log.push("b_exit".into()); } - fn z_entry(&mut self) { self.log.push("z_entry".into()); } + fn alpha(&mut self) { + self.log.push("alpha".into()); + } + fn beta(&mut self) { + self.log.push("beta".into()); + } + fn gamma(&mut self) { + self.log.push("gamma".into()); + } + fn cleanup1(&mut self) { + self.log.push("cleanup1".into()); + } + fn cleanup2(&mut self) { + self.log.push("cleanup2".into()); + } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } + fn b_exit(&mut self) { + self.log.push("b_exit".into()); + } + fn z_entry(&mut self) { + self.log.push("z_entry".into()); + } } #[test] @@ -840,7 +1023,10 @@ T5X { m.context_mut().log.clear(); m.send(Ev::Go).unwrap(); m.step(Duration::ZERO); - assert_eq!(m.context().logs(), ["b_exit", "cleanup1", "cleanup2", "z_entry"]); + assert_eq!( + m.context().logs(), + ["b_exit", "cleanup1", "cleanup2", "z_entry"] + ); } } @@ -848,32 +1034,46 @@ T5X { mod t5_5 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go } + pub enum Ev { + Go, + } statechart! { -T55 { - context: TestCtx; - events: Ev; - default(Parent); - state Parent { - default(A); - entry: parent_entry; - exit: parent_exit; - on(after Duration::from_secs(10)) => Somewhere; - state A { entry: a_entry; exit: a_exit; on(Go) => B; } - state B { entry: b_entry; } + T55 { + context: TestCtx; + events: Ev; + default(Parent); + state Parent { + default(A); + entry: parent_entry; + exit: parent_exit; + on(after Duration::from_secs(10)) => Somewhere; + state A { entry: a_entry; exit: a_exit; on(Go) => B; } + state B { entry: b_entry; } + } + state Somewhere { entry: somewhere_entry; } + } } - state Somewhere { entry: somewhere_entry; } - } - } impl T55Actions for T55ActionContext<'_> { - fn parent_entry(&mut self) { self.log.push("parent_entry".into()); } - fn parent_exit(&mut self) { self.log.push("parent_exit".into()); } - fn a_entry(&mut self) { self.log.push("a_entry".into()); } - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } - fn somewhere_entry(&mut self) { self.log.push("somewhere_entry".into()); } + fn parent_entry(&mut self) { + self.log.push("parent_entry".into()); + } + fn parent_exit(&mut self) { + self.log.push("parent_exit".into()); + } + fn a_entry(&mut self) { + self.log.push("a_entry".into()); + } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } + fn somewhere_entry(&mut self) { + self.log.push("somewhere_entry".into()); + } } #[test] @@ -906,20 +1106,25 @@ T55 { mod t6_2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Halt, Other } + pub enum Ev { + Halt, + Other, + } statechart! { -T62 { - context: TestCtx; - events: Ev; - default(A); - terminate(Halt); - state A { entry: a_entry; } - } - } + T62 { + context: TestCtx; + events: Ev; + default(A); + terminate(Halt); + state A { entry: a_entry; } + } + } impl T62Actions for T62ActionContext<'_> { - fn a_entry(&mut self) { self.log.push("a".into()); } + fn a_entry(&mut self) { + self.log.push("a".into()); + } } #[test] @@ -938,20 +1143,24 @@ T62 { mod t6_4 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Halt } + pub enum Ev { + Halt, + } statechart! { -T64 { - context: TestCtx; - events: Ev; - default(A); - terminate(Halt); - state A { entry: a_entry; } - } - } + T64 { + context: TestCtx; + events: Ev; + default(A); + terminate(Halt); + state A { entry: a_entry; } + } + } impl T64Actions for T64ActionContext<'_> { - fn a_entry(&mut self) { self.log.push("a".into()); } + fn a_entry(&mut self) { + self.log.push("a".into()); + } } #[test] @@ -971,29 +1180,36 @@ T64 { mod t7_2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go, Cleanup } + pub enum Ev { + Go, + Cleanup, + } statechart! { -T72 { - context: TestCtx; - events: Ev; - default(A); - on(Cleanup) => do_cleanup; - state A { - exit: emit_cleanup; - on(Go) => B; + T72 { + context: TestCtx; + events: Ev; + default(A); + on(Cleanup) => do_cleanup; + state A { + exit: emit_cleanup; + on(Go) => B; + } + state B { entry: b_entry; } + } } - state B { entry: b_entry; } - } - } impl T72Actions for T72ActionContext<'_> { fn emit_cleanup(&mut self) { self.log.push("a_exit".into()); self.emit(Ev::Cleanup).unwrap(); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } - fn do_cleanup(&mut self) { self.log.push("do_cleanup".into()); } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } + fn do_cleanup(&mut self) { + self.log.push("do_cleanup".into()); + } } #[test] @@ -1012,25 +1228,30 @@ T72 { mod t7_3 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Start, Tick } + pub enum Ev { + Start, + Tick, + } statechart! { -T73 { - context: TestCtx; - events: Ev; - default(A); - state A { - on(Start) => flood; + T73 { + context: TestCtx; + events: Ev; + default(A); + state A { + on(Start) => flood; + } + } } - } - } impl T73Actions for T73ActionContext<'_> { fn flood(&mut self) { // Queue capacity is 8 (via with_queue_capacity). Emit 9 times. let mut errors = 0; for _ in 0..9 { - if self.emit(Ev::Tick).is_err() { errors += 1; } + if self.emit(Ev::Tick).is_err() { + errors += 1; + } } self.log.push(format!("err={}", errors)); } @@ -1052,33 +1273,45 @@ T73 { mod t8_3 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T83 { - context: TestCtx; - events: Ev; - default(Parent); - state Parent { - default(ChildA); - exit: parent_exit; - on(after Duration::from_secs(10)) => Done; - state ChildA { - exit: childa_exit; - on(after Duration::from_secs(3)) => ChildB; + T83 { + context: TestCtx; + events: Ev; + default(Parent); + state Parent { + default(ChildA); + exit: parent_exit; + on(after Duration::from_secs(10)) => Done; + state ChildA { + exit: childa_exit; + on(after Duration::from_secs(3)) => ChildB; + } + state ChildB { exit: childb_exit; entry: childb_entry; } } - state ChildB { exit: childb_exit; entry: childb_entry; } + state Done { entry: done_entry; } + } } - state Done { entry: done_entry; } - } - } impl T83Actions for T83ActionContext<'_> { - fn parent_exit(&mut self) { self.log.push("parent_exit".into()); } - fn childa_exit(&mut self) { self.log.push("childa_exit".into()); } - fn childb_exit(&mut self) { self.log.push("childb_exit".into()); } - fn childb_entry(&mut self) { self.log.push("childb_entry".into()); } - fn done_entry(&mut self) { self.log.push("done_entry".into()); } + fn parent_exit(&mut self) { + self.log.push("parent_exit".into()); + } + fn childa_exit(&mut self) { + self.log.push("childa_exit".into()); + } + fn childb_exit(&mut self) { + self.log.push("childb_exit".into()); + } + fn childb_entry(&mut self) { + self.log.push("childb_entry".into()); + } + fn done_entry(&mut self) { + self.log.push("done_entry".into()); + } } #[test] @@ -1100,17 +1333,19 @@ T83 { mod t8_4 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T84 { - context: TestCtx; - events: Ev; - default(Red); - state Red { on(after Duration::from_secs(5)) => Green; } - state Green { on(after Duration::from_secs(5)) => Red; } - } - } + T84 { + context: TestCtx; + events: Ev; + default(Red); + state Red { on(after Duration::from_secs(5)) => Green; } + state Green { on(after Duration::from_secs(5)) => Red; } + } + } impl T84Actions for T84ActionContext<'_> {} @@ -1231,25 +1466,31 @@ mod t8_4b { mod t8_5 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T85 { - context: TestCtx; - events: Ev; - default(A); - state A { - default(B); - on(after Duration::from_secs(2)) => ping; - state B { on(after Duration::from_secs(5)) => C; } - state C { entry: c_entry; } + T85 { + context: TestCtx; + events: Ev; + default(A); + state A { + default(B); + on(after Duration::from_secs(2)) => ping; + state B { on(after Duration::from_secs(5)) => C; } + state C { entry: c_entry; } + } + } } - } - } impl T85Actions for T85ActionContext<'_> { - fn ping(&mut self) { self.log.push("ping".into()); } - fn c_entry(&mut self) { self.log.push("c_entry".into()); } + fn ping(&mut self) { + self.log.push("ping".into()); + } + fn c_entry(&mut self) { + self.log.push("c_entry".into()); + } } #[test] @@ -1263,7 +1504,12 @@ T85 { assert_eq!(m.current_state(), T85State::C); // Verify A's timer does not re-fire m.step(Duration::from_secs(10)); - let count = m.context().log.iter().filter(|s| s.as_str() == "ping").count(); + let count = m + .context() + .log + .iter() + .filter(|s| s.as_str() == "ping") + .count(); assert_eq!(count, 1); } } @@ -1275,18 +1521,22 @@ mod t10_2 { pub enum NoEvents {} statechart! { -TimerOnly { - context: TestCtx; - events: NoEvents; - default(A); - state A { on(after Duration::from_secs(1)) => B; entry: a_e; } - state B { on(after Duration::from_secs(1)) => A; entry: b_e; } - } - } + TimerOnly { + context: TestCtx; + events: NoEvents; + default(A); + state A { on(after Duration::from_secs(1)) => B; entry: a_e; } + state B { on(after Duration::from_secs(1)) => A; entry: b_e; } + } + } impl TimerOnlyActions for TimerOnlyActionContext<'_> { - fn a_e(&mut self) { self.log.push("a".into()); } - fn b_e(&mut self) { self.log.push("b".into()); } + fn a_e(&mut self) { + self.log.push("a".into()); + } + fn b_e(&mut self) { + self.log.push("b".into()); + } } #[test] @@ -1303,41 +1553,55 @@ TimerOnly { mod t10_3 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -Deep { - context: TestCtx; - events: Ev; - default(A); - entry: root_e; - state A { - default(B); - entry: a_e; - state B { - default(C); - entry: b_e; - state C { - default(D); - entry: c_e; - state D { - default(E); - entry: d_e; - state E { entry: e_e; } + Deep { + context: TestCtx; + events: Ev; + default(A); + entry: root_e; + state A { + default(B); + entry: a_e; + state B { + default(C); + entry: b_e; + state C { + default(D); + entry: c_e; + state D { + default(E); + entry: d_e; + state E { entry: e_e; } + } } } } } - } - } + } impl DeepActions for DeepActionContext<'_> { - fn root_e(&mut self) { self.log.push("root".into()); } - fn a_e(&mut self) { self.log.push("a".into()); } - fn b_e(&mut self) { self.log.push("b".into()); } - fn c_e(&mut self) { self.log.push("c".into()); } - fn d_e(&mut self) { self.log.push("d".into()); } - fn e_e(&mut self) { self.log.push("e".into()); } + fn root_e(&mut self) { + self.log.push("root".into()); + } + fn a_e(&mut self) { + self.log.push("a".into()); + } + fn b_e(&mut self) { + self.log.push("b".into()); + } + fn c_e(&mut self) { + self.log.push("c".into()); + } + fn d_e(&mut self) { + self.log.push("d".into()); + } + fn e_e(&mut self) { + self.log.push("e".into()); + } } #[test] @@ -1353,26 +1617,38 @@ Deep { mod t10_4 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo, Bar, Baz } + pub enum Ev { + Foo, + Bar, + Baz, + } statechart! { -T104 { - context: TestCtx; - events: Ev; - default(A); - state A { - on(Foo) => emit_bar; - on(Bar) => emit_baz; - on(Baz) => B; + T104 { + context: TestCtx; + events: Ev; + default(A); + state A { + on(Foo) => emit_bar; + on(Bar) => emit_baz; + on(Baz) => B; + } + state B { entry: b_entry; } + } } - state B { entry: b_entry; } - } - } impl T104Actions for T104ActionContext<'_> { - fn emit_bar(&mut self) { self.emit(Ev::Bar).unwrap(); self.log.push("bar".into()); } - fn emit_baz(&mut self) { self.emit(Ev::Baz).unwrap(); self.log.push("baz".into()); } - fn b_entry(&mut self) { self.log.push("b".into()); } + fn emit_bar(&mut self) { + self.emit(Ev::Bar).unwrap(); + self.log.push("bar".into()); + } + fn emit_baz(&mut self) { + self.emit(Ev::Baz).unwrap(); + self.log.push("baz".into()); + } + fn b_entry(&mut self) { + self.log.push("b".into()); + } } #[test] @@ -1380,7 +1656,9 @@ T104 { let mut m = T104::new(TestCtx::default()); m.step(Duration::ZERO); m.send(Ev::Foo).unwrap(); - for _ in 0..5 { m.step(Duration::ZERO); } + for _ in 0..5 { + m.step(Duration::ZERO); + } assert_eq!(m.current_state(), T104State::B); assert_eq!(m.context().logs(), ["bar", "baz", "b"]); } @@ -1390,18 +1668,21 @@ T104 { mod t10_5 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Halt, Cleanup } + pub enum Ev { + Halt, + Cleanup, + } statechart! { -T105 { - context: TestCtx; - events: Ev; - default(A); - terminate(Halt); - on(Cleanup) => do_cleanup; - state A { exit: a_exit; } - } - } + T105 { + context: TestCtx; + events: Ev; + default(A); + terminate(Halt); + on(Cleanup) => do_cleanup; + state A { exit: a_exit; } + } + } impl T105Actions for T105ActionContext<'_> { fn a_exit(&mut self) { @@ -1409,7 +1690,9 @@ T105 { // emit should be a no-op / ignored after termination begins let _ = self.emit(Ev::Cleanup); } - fn do_cleanup(&mut self) { self.log.push("do_cleanup".into()); } + fn do_cleanup(&mut self) { + self.log.push("do_cleanup".into()); + } } #[test] @@ -1420,7 +1703,9 @@ T105 { m.step(Duration::ZERO); assert!(m.is_terminated()); // Keep stepping; do_cleanup should NOT run - for _ in 0..3 { m.step(Duration::ZERO); } + for _ in 0..3 { + m.step(Duration::ZERO); + } assert!(!m.context().logs().contains(&"do_cleanup")); } } @@ -1429,31 +1714,43 @@ T105 { mod t10_6 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T106 { - context: TestCtx; - events: Ev; - default(Deep1); - entry: root_entry; - exit: root_exit; - on(after Duration::from_secs(60)) => FirstState; - state Deep1 { - default(Deep2); - exit: d1_exit; - state Deep2 { exit: d2_exit; } + T106 { + context: TestCtx; + events: Ev; + default(Deep1); + entry: root_entry; + exit: root_exit; + on(after Duration::from_secs(60)) => FirstState; + state Deep1 { + default(Deep2); + exit: d1_exit; + state Deep2 { exit: d2_exit; } + } + state FirstState { entry: first_entry; } + } } - state FirstState { entry: first_entry; } - } - } impl T106Actions for T106ActionContext<'_> { - fn root_entry(&mut self) { self.log.push("root_entry".into()); } - fn root_exit(&mut self) { self.log.push("root_exit".into()); } - fn d1_exit(&mut self) { self.log.push("d1_exit".into()); } - fn d2_exit(&mut self) { self.log.push("d2_exit".into()); } - fn first_entry(&mut self) { self.log.push("first_entry".into()); } + fn root_entry(&mut self) { + self.log.push("root_entry".into()); + } + fn root_exit(&mut self) { + self.log.push("root_exit".into()); + } + fn d1_exit(&mut self) { + self.log.push("d1_exit".into()); + } + fn d2_exit(&mut self) { + self.log.push("d2_exit".into()); + } + fn first_entry(&mut self) { + self.log.push("first_entry".into()); + } } #[test] @@ -1474,20 +1771,24 @@ T106 { mod t10_7 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Halt } + pub enum Ev { + Halt, + } statechart! { -T107 { - context: TestCtx; - events: Ev; - default(A); - terminate(Halt); - state A { entry: a_e; } - } - } + T107 { + context: TestCtx; + events: Ev; + default(A); + terminate(Halt); + state A { entry: a_e; } + } + } impl T107Actions for T107ActionContext<'_> { - fn a_e(&mut self) { self.log.push("hello".into()); } + fn a_e(&mut self) { + self.log.push("hello".into()); + } } #[test] @@ -1506,20 +1807,24 @@ T107 { mod t10_1 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Go } + pub enum Ev { + Go, + } statechart! { -T101 { - context: TestCtx; - events: Ev; - default(A); - state A { entry: shared_setup; on(Go) => B; } - state B { entry: shared_setup; } - } - } + T101 { + context: TestCtx; + events: Ev; + default(A); + state A { entry: shared_setup; on(Go) => B; } + state B { entry: shared_setup; } + } + } impl T101Actions for T101ActionContext<'_> { - fn shared_setup(&mut self) { self.log.push("shared".into()); } + fn shared_setup(&mut self) { + self.log.push("shared".into()); + } } #[test] @@ -1536,20 +1841,24 @@ T101 { mod t8_1 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { _U } + pub enum Ev { + _U, + } statechart! { -T81 { - context: TestCtx; - events: Ev; - default(Red); - state Red { on(after Duration::from_secs(5)) => Green; } - state Green { entry: green_on; } - } - } + T81 { + context: TestCtx; + events: Ev; + default(Red); + state Red { on(after Duration::from_secs(5)) => Green; } + state Green { entry: green_on; } + } + } impl T81Actions for T81ActionContext<'_> { - fn green_on(&mut self) { self.log.push("green_on".into()); } + fn green_on(&mut self) { + self.log.push("green_on".into()); + } } #[test] @@ -1567,25 +1876,31 @@ T81 { mod t8_2 { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Interrupt } + pub enum Ev { + Interrupt, + } statechart! { -T82 { - context: TestCtx; - events: Ev; - default(Red); - state Red { - on(after Duration::from_secs(5)) => Green; - on(Interrupt) => Yellow; + T82 { + context: TestCtx; + events: Ev; + default(Red); + state Red { + on(after Duration::from_secs(5)) => Green; + on(Interrupt) => Yellow; + } + state Green { entry: green_on; } + state Yellow { entry: yellow_on; } + } } - state Green { entry: green_on; } - state Yellow { entry: yellow_on; } - } - } impl T82Actions for T82ActionContext<'_> { - fn green_on(&mut self) { self.log.push("green_on".into()); } - fn yellow_on(&mut self) { self.log.push("yellow_on".into()); } + fn green_on(&mut self) { + self.log.push("green_on".into()); + } + fn yellow_on(&mut self) { + self.log.push("yellow_on".into()); + } } #[test] @@ -1606,27 +1921,32 @@ T82 { mod b1_emit_or_panic { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo, Bar } + pub enum Ev { + Foo, + Bar, + } statechart! { -B1M { - context: TestCtx; - events: Ev; - default(A); - state A { - on(Foo) => emit_bar; - on(Bar) => B; + B1M { + context: TestCtx; + events: Ev; + default(A); + state A { + on(Foo) => emit_bar; + on(Bar) => B; + } + state B { entry: b_entry; } + } } - state B { entry: b_entry; } - } - } impl B1MActions for B1MActionContext<'_> { fn emit_bar(&mut self) { self.log.push("emit_bar".into()); self.emit_or_panic(Ev::Bar); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } } #[test] @@ -1645,19 +1965,23 @@ B1M { mod b2_has_pending { use super::*; #[derive(Debug, Clone)] - pub enum Ev { Foo } + pub enum Ev { + Foo, + } statechart! { -B2M { - context: TestCtx; - events: Ev; - default(A); - state A { on(Foo) => noop; } - } - } + B2M { + context: TestCtx; + events: Ev; + default(A); + state A { on(Foo) => noop; } + } + } impl B2MActions for B2MActionContext<'_> { - fn noop(&mut self) { self.log.push("noop".into()); } + fn noop(&mut self) { + self.log.push("noop".into()); + } } #[test] @@ -1677,17 +2001,21 @@ mod b5_no_events { use super::*; statechart! { -B5M { - context: TestCtx; - default(A); - state A { on(after Duration::from_millis(100)) => B; exit: a_exit; } - state B { entry: b_entry; } - } - } + B5M { + context: TestCtx; + default(A); + state A { on(after Duration::from_millis(100)) => B; exit: a_exit; } + state B { entry: b_entry; } + } + } impl B5MActions for B5MActionContext<'_> { - fn a_exit(&mut self) { self.log.push("a_exit".into()); } - fn b_entry(&mut self) { self.log.push("b_entry".into()); } + fn a_exit(&mut self) { + self.log.push("a_exit".into()); + } + fn b_entry(&mut self) { + self.log.push("b_entry".into()); + } } #[test] diff --git a/hsmc/tests/during_concurrent.rs b/hsmc/tests/during_concurrent.rs index 807d2f3..270cad2 100644 --- a/hsmc/tests/during_concurrent.rs +++ b/hsmc/tests/during_concurrent.rs @@ -79,6 +79,10 @@ async fn both_durings_compile_and_fast_fires() { // Fast (5ms period) wins its race consistently against slow (15ms). // This documents the starvation property: in select-drop semantics, // the faster during starves the slower one. - assert!(ctx.seen_fast >= 4, "expected fast ≥4, got {}", ctx.seen_fast); + assert!( + ctx.seen_fast >= 4, + "expected fast ≥4, got {}", + ctx.seen_fast + ); assert_eq!(ctx.fast_field, ctx.seen_fast); } diff --git a/hsmc/tests/tokio_nested_alternation.rs b/hsmc/tests/tokio_nested_alternation.rs index 9462d43..d6ace0c 100644 --- a/hsmc/tests/tokio_nested_alternation.rs +++ b/hsmc/tests/tokio_nested_alternation.rs @@ -89,9 +89,9 @@ async fn nested_alternation_survives_round_trip() { // Driver: exercise the full scenario, then halt. tokio::spawn(async move { // Let LM alternate with INFO for three cycles. - tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO - tokio::time::sleep(Duration::from_secs(5)).await; // INFO→LM - tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO + tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO + tokio::time::sleep(Duration::from_secs(5)).await; // INFO→LM + tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO // Jump out to Listening. The machine will now tick every 1s // with a 20ms-await tick handler — the firmware's actual shape. @@ -104,8 +104,8 @@ async fn nested_alternation_survives_round_trip() { tokio::time::sleep(Duration::from_millis(50)).await; // Regression: alternation must continue after re-entry. - tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO - tokio::time::sleep(Duration::from_secs(5)).await; // INFO→LM + tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO + tokio::time::sleep(Duration::from_secs(5)).await; // INFO→LM // Second round-trip to be sure it wasn't a one-off. let _ = sender.send(Ev::Go); @@ -113,8 +113,8 @@ async fn nested_alternation_survives_round_trip() { let _ = sender.send(Ev::Back); tokio::time::sleep(Duration::from_millis(50)).await; - tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO - tokio::time::sleep(Duration::from_secs(5)).await; // INFO→LM + tokio::time::sleep(Duration::from_secs(5)).await; // LM→INFO + tokio::time::sleep(Duration::from_secs(5)).await; // INFO→LM let _ = sender.send(Ev::Halt); }); @@ -131,10 +131,10 @@ async fn nested_alternation_survives_round_trip() { &log[..], &[ "LM", "INFO", "LM", "INFO", // fresh-boot alternation ×3 - "LISTEN", // Go #1 - "LM", "INFO", "LM", // Back #1 + two 5s ticks - "LISTEN", // Go #2 - "LM", "INFO", "LM", // Back #2 + two 5s ticks + "LISTEN", // Go #1 + "LM", "INFO", "LM", // Back #1 + two 5s ticks + "LISTEN", // Go #2 + "LM", "INFO", "LM", // Back #2 + two 5s ticks ][..], "log did not match expected sequence: {:?}", &log[..] diff --git a/hsmc/tests/tokio_repeat_and_payload.rs b/hsmc/tests/tokio_repeat_and_payload.rs index e8d3b74..8ba0ec5 100644 --- a/hsmc/tests/tokio_repeat_and_payload.rs +++ b/hsmc/tests/tokio_repeat_and_payload.rs @@ -74,7 +74,7 @@ async fn repeating_timer_fires_many_times() { // 10ms timer running for ~120ms should fire at least 5 times. We give // loose bounds to tolerate scheduler jitter under `cargo test`. assert!( - ticks >= 5 && ticks <= 30, + (5..=30).contains(&ticks), "expected 5..=30 ticks, got {}", ticks ); @@ -108,8 +108,5 @@ async fn struct_variant_payload_binding_dispatches() { }); let _ = tokio::time::timeout(Duration::from_secs(2), m.run()).await; let ctx = m.into_context(); - assert_eq!( - *ctx.last_cfg.lock().unwrap(), - Some((915_000_000, 125_000)) - ); + assert_eq!(*ctx.last_cfg.lock().unwrap(), Some((915_000_000, 125_000))); } diff --git a/hsmc/tests/tokio_run.rs b/hsmc/tests/tokio_run.rs index 50cbf5c..e194dea 100644 --- a/hsmc/tests/tokio_run.rs +++ b/hsmc/tests/tokio_run.rs @@ -4,10 +4,14 @@ use hsmc::{statechart, Duration}; #[derive(Default)] -pub struct Ctx { pub log: Vec } +pub struct Ctx { + pub log: Vec, +} #[derive(Debug, Clone)] -pub enum Ev { Halt } +pub enum Ev { + Halt, +} statechart! { TokM {