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.
This commit is contained in:
swaits committed 2026-04-22 09:13:04 -06:00
1 parent 0341cf9379
commit bc7e17e58e
22 files changed
+1483 -286

No files matched your search

+43
View File
@@ -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).
+3
View File
@@ -6,3 +6,6 @@ members = ["hsmc", "hsmc-macros"]
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
authors = ["Stephen Waits <steve@waits.net>"]
repository = "https://github.com/swaits/hsmc"
homepage = "https://github.com/swaits/hsmc"
+201
View File
@@ -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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Stephen Waits <steve@waits.net>
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.
+6
View File
@@ -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
+201
View File
@@ -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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Stephen Waits <steve@waits.net>
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.
+110 -36
View File
@@ -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<TokenStream> {
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<TokenStream> {
}
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,36 +414,64 @@ pub fn generate(ir: &Ir) -> TokenStream {
.map(|s| s.name.clone())
.collect();
let entries_of_arms: Vec<_> = ir.states.iter().map(|s| {
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| {
})
.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();
})
.collect();
let parent_table = ir.states.iter().map(|s| match s.parent {
let parent_table = ir
.states
.iter()
.map(|s| match s.parent {
Some(p) => quote! { Some(#p) },
None => quote! { None },
}).collect::<Vec<_>>();
let depth_table = ir.states.iter().map(|s| {
})
.collect::<Vec<_>>();
let depth_table = ir
.states
.iter()
.map(|s| {
let d = s.depth;
quote! { #d }
}).collect::<Vec<_>>();
let default_child_table = ir.states.iter().map(|s| match s.default_child {
})
.collect::<Vec<_>>();
let default_child_table = ir
.states
.iter()
.map(|s| match s.default_child {
Some(c) => quote! { Some(#c) },
None => quote! { None },
}).collect::<Vec<_>>();
let state_id_to_variant_arms = ir.states.iter().filter(|s| s.parent.is_some()).map(|s| {
})
.collect::<Vec<_>>();
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::<Vec<_>>();
})
.collect::<Vec<_>>();
// Trait methods, possibly with typed params for payload-bearing actions.
let action_methods_sync = ir.actions.iter().map(|a| {
let action_methods_sync = ir
.actions
.iter()
.map(|a| {
let name = &a.name;
let params = a.params.iter().map(|f| {
let n = &f.name;
@@ -449,8 +479,12 @@ pub fn generate(ir: &Ir) -> TokenStream {
quote! { #n: #t }
});
quote! { fn #name(&mut self, #(#params),*); }
}).collect::<Vec<_>>();
let action_methods_async = ir.actions.iter().map(|a| {
})
.collect::<Vec<_>>();
let action_methods_async = ir
.actions
.iter()
.map(|a| {
let name = &a.name;
let params = a.params.iter().map(|f| {
let n = &f.name;
@@ -460,14 +494,19 @@ pub fn generate(ir: &Ir) -> TokenStream {
quote! {
fn #name(&mut self, #(#params),*) -> impl ::core::future::Future<Output = ()>;
}
}).collect::<Vec<_>>();
})
.collect::<Vec<_>>();
// 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 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() {
@@ -502,8 +541,13 @@ pub fn generate(ir: &Ir) -> TokenStream {
}
}
}
}).collect::<Vec<_>>();
let run_action_arms_async = ir.actions.iter().enumerate().map(|(i, a)| {
})
.collect::<Vec<_>>();
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() {
@@ -538,18 +582,33 @@ pub fn generate(ir: &Ir) -> TokenStream {
}
}
}
}).collect::<Vec<_>>();
let duration_expr_arms = ir.duration_triggers.iter().enumerate().map(|(i, d)| {
})
.collect::<Vec<_>>();
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::<Vec<_>>();
let duration_repeat_arms = ir.duration_triggers.iter().enumerate().map(|(i, d)| {
})
.collect::<Vec<_>>();
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::<Vec<_>>();
let event_variant_arms = ir.event_variants.iter().enumerate().map(|(i, v)| {
})
.collect::<Vec<_>>();
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 {
@@ -558,11 +617,18 @@ pub fn generate(ir: &Ir) -> TokenStream {
VariantKind::Struct => quote! { #ev_ty::#name { .. } },
};
quote! { #pat => #i, }
}).collect::<Vec<_>>();
let state_handler_arms = ir.states.iter().map(|s| {
})
.collect::<Vec<_>>();
let state_handler_arms = ir
.states
.iter()
.map(|s| {
use std::collections::BTreeMap;
#[derive(Default)]
struct Group { action_ids: Vec<u16>, transition_target: Option<u16> }
struct Group {
action_ids: Vec<u16>,
transition_target: Option<u16>,
}
let mut groups: BTreeMap<(u8, u16), Group> = BTreeMap::new();
let mut handlers = s.handlers.iter().collect::<Vec<_>>();
handlers.sort_by_key(|h| h.decl_index);
@@ -579,7 +645,9 @@ pub fn generate(ir: &Ir) -> TokenStream {
}
}
let sid = s.id;
let inner_arms = groups.iter().map(|((kind, tid), g)| {
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 });
@@ -594,7 +662,8 @@ pub fn generate(ir: &Ir) -> TokenStream {
return Some((actions, target));
}
}
}).collect::<Vec<_>>();
})
.collect::<Vec<_>>();
quote! {
#sid => {
match (trigger_kind, trigger_id) {
@@ -603,12 +672,17 @@ pub fn generate(ir: &Ir) -> TokenStream {
}
}
}
}).collect::<Vec<_>>();
let owned_timers_arms = ir.states.iter().map(|s| {
})
.collect::<Vec<_>>();
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::<Vec<_>>();
})
.collect::<Vec<_>>();
let terminate_match = if let Some(tev) = &ir.terminate_event {
// Use the kind recorded for this variant (unit/tuple/struct).
let kind = ir
+19 -22
View File
@@ -143,7 +143,13 @@ pub fn build_ir(input: StatechartInput) -> syn::Result<Ir> {
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<u16> {
fn intern_event(ir: &mut Ir, i: &Ident, payload: Option<&EventPayload>) -> syn::Result<u16> {
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);
}
}
+3 -3
View File
@@ -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]
+23 -5
View File
@@ -176,7 +176,10 @@ fn parse_body(input: ParseStream, is_root: bool) -> syn::Result<StateBody> {
let ty: Type = input.parse()?;
input.parse::<Token![;]>()?;
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<StateBody> {
let ty: Type = input.parse()?;
input.parse::<Token![;]>()?;
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<StateBody> {
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<Trigger>
}
}
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 {
+26 -7
View File
@@ -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()) {
+8 -4
View File
@@ -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"]
+201
View File
@@ -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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Stephen Waits <steve@waits.net>
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.
+12
View File
@@ -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<u8, 64>,
}
impl Default for Ctx {
fn default() -> Self {
Self::new()
}
}
impl Ctx {
pub fn new() -> Self {
Self {
+4 -1
View File
@@ -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::<N>` overrides the default queue size (8). We
// pick 16 to comfortably hold the burst of events below.
+25 -6
View File
@@ -118,7 +118,9 @@ pub mod __private {
impl<E, const N: usize> EventQueue<E, N> {
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<E, const N: usize> Default for EventQueue<E, N> {
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<const N: usize> Default for TimerTable<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> TimerTable<N> {
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<core::time::Duration> {
self.entries.iter().map(|e| e.remaining_ns).min().map(|ns| {
+522 -194
View File
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -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);
}
+2 -5
View File
@@ -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)));
}
+6 -2
View File
@@ -4,10 +4,14 @@
use hsmc::{statechart, Duration};
#[derive(Default)]
pub struct Ctx { pub log: Vec<String> }
pub struct Ctx {
pub log: Vec<String>,
}
#[derive(Debug, Clone)]
pub enum Ev { Halt }
pub enum Ev {
Halt,
}
statechart! {
TokM {