├── .gitignore ├── .editorconfig ├── typos.toml ├── rust-toolchain.toml ├── .cargo └── config.toml ├── traversable ├── src │ ├── impls │ │ ├── mod.rs │ │ ├── stacksafe_1.rs │ │ └── ordered_float_5.rs │ ├── combinator.rs │ ├── function.rs │ └── lib.rs ├── tests │ ├── test_visitor.rs │ ├── test_visitor_mut.rs │ ├── test_ordered_float_5.rs │ └── test_combinator.rs └── Cargo.toml ├── rustfmt.toml ├── licenserc.toml ├── xtask ├── Cargo.toml └── src │ └── main.rs ├── traversable-derive ├── README.md ├── Cargo.toml ├── LICENSE └── src │ └── lib.rs ├── Cargo.toml ├── .github ├── semantic.yml └── workflows │ └── ci.yml ├── taplo.toml ├── README.md ├── LICENSE └── Cargo.lock /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | indent_style = space 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | 9 | [*.toml] 10 | indent_size = tab 11 | tab_width = 2 12 | -------------------------------------------------------------------------------- /typos.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [default.extend-words] 16 | 17 | [files] 18 | extend-exclude = [] 19 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [toolchain] 16 | channel = "stable" 17 | components = ["cargo", "rustfmt", "clippy", "rust-analyzer"] 18 | -------------------------------------------------------------------------------- /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [alias] 16 | x = "run --package x --" 17 | 18 | [env] 19 | CARGO_WORKSPACE_DIR = { value = "", relative = true } 20 | -------------------------------------------------------------------------------- /traversable/src/impls/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #[cfg(feature = "ordered-float-5")] 16 | mod ordered_float_5; 17 | #[cfg(feature = "stacksafe-1")] 18 | mod stacksafe_1; 19 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | comment_width = 120 16 | format_code_in_doc_comments = true 17 | group_imports = "StdExternalCrate" 18 | imports_granularity = "Item" 19 | wrap_comments = true 20 | -------------------------------------------------------------------------------- /licenserc.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | headerPath = "Apache-2.0.txt" 16 | 17 | includes = ['**/*.proto', '**/*.rs', '**/*.yml', '**/*.yaml', '**/*.toml'] 18 | 19 | [properties] 20 | copyrightOwner = "FastLabs Developers" 21 | inceptionYear = 2025 22 | -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "x" 17 | publish = false 18 | 19 | edition.workspace = true 20 | homepage.workspace = true 21 | license.workspace = true 22 | readme.workspace = true 23 | repository.workspace = true 24 | rust-version.workspace = true 25 | 26 | [package.metadata.release] 27 | release = false 28 | 29 | [dependencies] 30 | clap = { version = "4.5.23", features = ["derive"] } 31 | which = { version = "8.0.0" } 32 | 33 | [lints] 34 | workspace = true 35 | -------------------------------------------------------------------------------- /traversable-derive/README.md: -------------------------------------------------------------------------------- 1 | # traversable-derive 2 | 3 | [![Crates.io][crates-badge]][crates-url] 4 | [![Documentation][docs-badge]][docs-url] 5 | [![MSRV 1.85][msrv-badge]](https://www.whatrustisit.com) 6 | [![Apache 2.0 licensed][license-badge]][license-url] 7 | [![Build Status][actions-badge]][actions-url] 8 | 9 | [crates-badge]: https://img.shields.io/crates/v/traversable-derive.svg 10 | [crates-url]: https://crates.io/crates/traversable-derive 11 | [docs-badge]: https://docs.rs/traversable-derive/badge.svg 12 | [msrv-badge]: https://img.shields.io/badge/MSRV-1.85-green?logo=rust 13 | [docs-url]: https://docs.rs/traversable-derive 14 | [license-badge]: https://img.shields.io/crates/l/traversable-derive 15 | [license-url]: LICENSE 16 | [actions-badge]: https://github.com/fast/traversable/workflows/CI/badge.svg 17 | [actions-url]:https://github.com/fast/traversable/actions?query=workflow%3ACI 18 | 19 | This is an implementation crate for the [`traversable`](https://crates.io/crates/traversable) library. 20 | 21 | Please refer to the main [`traversable`](https://crates.io/crates/traversable) crate for documentation and usage examples. 22 | 23 | This crate contains procedural macros that derive `Traversable` and `TraversableMut` implementations. 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [workspace] 16 | members = ["traversable", "traversable-derive", "xtask"] 17 | resolver = "2" 18 | 19 | [workspace.package] 20 | edition = "2024" 21 | homepage = "https://github.com/fast/traversable" 22 | license = "Apache-2.0" 23 | readme = "README.md" 24 | repository = "https://github.com/fast/traversable" 25 | rust-version = "1.85.0" 26 | 27 | [workspace.dependencies] 28 | traversable-derive = { version = "=0.1.0", path = "traversable-derive" } 29 | 30 | [workspace.lints.rust] 31 | unknown_lints = "deny" 32 | 33 | [workspace.lints.clippy] 34 | dbg_macro = "deny" 35 | 36 | [workspace.metadata.release] 37 | sign-tag = true 38 | -------------------------------------------------------------------------------- /.github/semantic.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # The pull request's title should be fulfilled the following pattern: 16 | # 17 | # [optional scope]: 18 | # 19 | # ... where valid types and scopes can be found below; for example: 20 | # 21 | # build(maven): One level down for native profile 22 | # 23 | # More about configurations on https://github.com/Ezard/semantic-prs#configuration 24 | 25 | enabled: true 26 | 27 | titleOnly: true 28 | 29 | types: 30 | - feat 31 | - fix 32 | - docs 33 | - style 34 | - refactor 35 | - perf 36 | - test 37 | - build 38 | - ci 39 | - chore 40 | - revert 41 | 42 | targetUrl: https://github.com/fast/traversable/blob/main/.github/semantic.yml 43 | -------------------------------------------------------------------------------- /traversable-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "traversable-derive" 17 | version = "0.1.0" 18 | 19 | description = "Procedural macro to derive Traversable and TraversableMut" 20 | documentation = "https://docs.rs/traversable-derive" 21 | keywords = ["visitor", "traverse", "traversable"] 22 | readme = "README.md" 23 | 24 | edition.workspace = true 25 | homepage.workspace = true 26 | license.workspace = true 27 | repository.workspace = true 28 | rust-version.workspace = true 29 | 30 | [lib] 31 | proc-macro = true 32 | 33 | [dependencies] 34 | proc-macro2 = { version = "1.0.101" } 35 | quote = { version = "1.0.41" } 36 | syn = { version = "2.0.106", features = ["extra-traits"] } 37 | 38 | [lints] 39 | workspace = true 40 | -------------------------------------------------------------------------------- /traversable/src/impls/stacksafe_1.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use core::ops::ControlFlow; 16 | 17 | use stacksafe_1::StackSafe; 18 | use stacksafe_1::stacksafe; 19 | 20 | use crate::Traversable; 21 | use crate::TraversableMut; 22 | 23 | impl Traversable for StackSafe { 24 | #[stacksafe(crate = stacksafe_1)] 25 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 26 | (**self).traverse(visitor) 27 | } 28 | } 29 | 30 | impl TraversableMut for StackSafe { 31 | #[stacksafe(crate = stacksafe_1)] 32 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 33 | (**self).traverse_mut(visitor) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /traversable/src/impls/ordered_float_5.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use core::ops::ControlFlow; 16 | 17 | use ordered_float_5::OrderedFloat; 18 | 19 | use crate::Traversable; 20 | use crate::TraversableMut; 21 | use crate::Visitor; 22 | use crate::VisitorMut; 23 | 24 | impl Traversable for OrderedFloat { 25 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 26 | visitor.enter(self)?; 27 | visitor.leave(self)?; 28 | ControlFlow::Continue(()) 29 | } 30 | } 31 | 32 | impl TraversableMut for OrderedFloat { 33 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 34 | visitor.enter_mut(self)?; 35 | visitor.leave_mut(self)?; 36 | ControlFlow::Continue(()) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /traversable/tests/test_visitor.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg(feature = "traverse-trivial")] 16 | 17 | use core::ops::ControlFlow; 18 | 19 | use traversable::Traversable; 20 | use traversable::TraversableMut; 21 | use traversable::function::visitor_enter; 22 | use traversable::function::visitor_leave_mut; 23 | 24 | #[test] 25 | fn test_visitor() { 26 | let mut visitor = visitor_enter::(|item| { 27 | assert_eq!(*item, 42); 28 | ControlFlow::Continue(()) 29 | }); 30 | 31 | let result = 42i32.traverse(&mut visitor); 32 | assert!(result.is_continue()); 33 | } 34 | 35 | #[test] 36 | fn test_visitor_mut() { 37 | let mut visitor = visitor_leave_mut::(|item| { 38 | *item += 1; 39 | ControlFlow::Continue(()) 40 | }); 41 | 42 | let mut data = 42i32; 43 | let result = data.traverse_mut(&mut visitor); 44 | assert!(result.is_continue()); 45 | assert_eq!(data, 43); 46 | } 47 | -------------------------------------------------------------------------------- /traversable/tests/test_visitor_mut.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg(all(feature = "std", feature = "derive"))] 16 | 17 | use std::any::Any; 18 | use std::ops::ControlFlow; 19 | 20 | use traversable::TraversableMut; 21 | use traversable::VisitorMut; 22 | 23 | #[derive(TraversableMut)] 24 | struct Chain { 25 | next: Option>, 26 | } 27 | 28 | impl Chain { 29 | fn depth(&self) -> usize { 30 | if let Some(child) = &self.next { 31 | 1 + child.depth() 32 | } else { 33 | 0 34 | } 35 | } 36 | } 37 | 38 | struct ChainCutter { 39 | cut_at_depth: usize, 40 | } 41 | 42 | impl VisitorMut for ChainCutter { 43 | type Break = (); 44 | 45 | fn enter_mut(&mut self, this: &mut dyn Any) -> ControlFlow { 46 | if let Some(item) = this.downcast_mut::() { 47 | if self.cut_at_depth == 0 { 48 | item.next = None; 49 | } else { 50 | self.cut_at_depth -= 1; 51 | } 52 | } 53 | 54 | ControlFlow::Continue(()) 55 | } 56 | } 57 | 58 | #[test] 59 | fn test() { 60 | let mut chain = Chain { 61 | next: Some(Box::new(Chain { 62 | next: Some(Box::new(Chain { next: None })), 63 | })), 64 | }; 65 | assert_eq!(chain.depth(), 2); 66 | 67 | let mut cutter = ChainCutter { cut_at_depth: 1 }; 68 | let result = chain.traverse_mut(&mut cutter); 69 | assert!(result.is_continue()); 70 | assert_eq!(chain.depth(), 1); 71 | } 72 | -------------------------------------------------------------------------------- /taplo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | include = ["Cargo.toml", "**/*.toml"] 16 | 17 | [formatting] 18 | # Align consecutive entries vertically. 19 | align_entries = false 20 | # Append trailing commas for multi-line arrays. 21 | array_trailing_comma = true 22 | # Expand arrays to multiple lines that exceed the maximum column width. 23 | array_auto_expand = true 24 | # Collapse arrays that don't exceed the maximum column width and don't contain comments. 25 | array_auto_collapse = true 26 | # Omit white space padding from single-line arrays 27 | compact_arrays = true 28 | # Omit white space padding from the start and end of inline tables. 29 | compact_inline_tables = false 30 | # Maximum column width in characters, affects array expansion and collapse, this doesn't take whitespace into account. 31 | # Note that this is not set in stone, and works on a best-effort basis. 32 | column_width = 80 33 | # Indent based on tables and arrays of tables and their subtables, subtables out of order are not indented. 34 | indent_tables = false 35 | # The substring that is used for indentation, should be tabs or spaces (but technically can be anything). 36 | indent_string = ' ' 37 | # Add trailing newline at the end of the file if not present. 38 | trailing_newline = true 39 | # Alphabetically reorder keys that are not separated by empty lines. 40 | reorder_keys = true 41 | # Maximum amount of allowed consecutive blank lines. This does not affect the whitespace at the end of the document, as it is always stripped. 42 | allowed_blank_lines = 1 43 | # Use CRLF for line endings. 44 | crlf = false 45 | -------------------------------------------------------------------------------- /traversable/Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | [package] 16 | name = "traversable" 17 | version = "0.2.0" 18 | 19 | description = "Visitor Pattern over Traversable data structures" 20 | documentation = "https://docs.rs/traversable" 21 | keywords = ["visitor", "traverse", "traversable"] 22 | 23 | edition.workspace = true 24 | homepage.workspace = true 25 | license.workspace = true 26 | readme.workspace = true 27 | repository.workspace = true 28 | rust-version.workspace = true 29 | 30 | [features] 31 | default = [] 32 | derive = ["dep:traversable-derive"] 33 | 34 | # Implement Traversal for standard library types. 35 | std = [] 36 | 37 | # Visit all trivial types. 38 | # 39 | # By default, a.k.a., without this feature, Traversal implements no-ops for trivial types. 40 | # Because in many cases, users want to visit only non-trivial types, and no ops can be 41 | # applied when traversing trivial types like integers, floats, booleans, and unit. 42 | traverse-trivial = [] 43 | 44 | # Visit all primary standard library types. 45 | # 46 | # By default, a.k.a., without this feature, Traversal implements no-ops for primary standard 47 | # library types. Currently, primary standard library types include only String. 48 | # 49 | # Containers like Vec, Option, Result, HashMap, etc., are not considered primary standard 50 | # library types, because they are generic over their contained types, and thus can be 51 | # traversed via their contained types. 52 | traverse-std = [] 53 | 54 | # Implement Traversal for third-party library types. 55 | ordered-float-5 = ["dep:ordered-float-5"] 56 | stacksafe-1 = ["dep:stacksafe-1"] 57 | 58 | [dependencies] 59 | traversable-derive = { workspace = true, optional = true } 60 | 61 | # Optional dependencies for third-party library support 62 | ordered-float-5 = { version = "5.1", default-features = false, optional = true, package = "ordered-float" } 63 | stacksafe-1 = { version = "1", default-features = false, optional = true, package = "stacksafe" } 64 | 65 | [lints] 66 | workspace = true 67 | -------------------------------------------------------------------------------- /traversable/tests/test_ordered_float_5.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg(all(feature = "derive", feature = "ordered-float-5"))] 16 | 17 | use std::any::Any; 18 | use std::ops::ControlFlow; 19 | 20 | use ordered_float_5::OrderedFloat; 21 | use traversable::Traversable as _; 22 | use traversable::TraversableMut as _; 23 | use traversable::Visitor; 24 | use traversable::VisitorMut; 25 | use traversable_derive::Traversable; 26 | use traversable_derive::TraversableMut; 27 | 28 | #[test] 29 | fn test_ordered_float() { 30 | #[derive(Debug, Clone, PartialEq, Eq, Traversable, TraversableMut)] 31 | pub enum Literal { 32 | Null, 33 | Float(OrderedFloat), 34 | } 35 | 36 | struct FloatExpr(bool); 37 | 38 | impl Visitor for FloatExpr { 39 | type Break = (); 40 | 41 | fn enter(&mut self, this: &dyn Any) -> ControlFlow { 42 | if let Some(Literal::Float(_)) = this.downcast_ref::() { 43 | self.0 = true; 44 | } 45 | ControlFlow::Continue(()) 46 | } 47 | } 48 | 49 | impl VisitorMut for FloatExpr { 50 | type Break = (); 51 | 52 | fn enter_mut(&mut self, this: &mut dyn Any) -> ControlFlow { 53 | if let Some(Literal::Float(_)) = this.downcast_ref::() { 54 | self.0 = true; 55 | } 56 | ControlFlow::Continue(()) 57 | } 58 | } 59 | 60 | assert!({ 61 | let mut visitor = FloatExpr(false); 62 | let _ = Literal::Null.traverse(&mut visitor); 63 | !visitor.0 64 | }); 65 | 66 | assert!({ 67 | let mut visitor = FloatExpr(false); 68 | let _ = Literal::Null.traverse_mut(&mut visitor); 69 | !visitor.0 70 | }); 71 | 72 | assert!({ 73 | let mut visitor = FloatExpr(false); 74 | let _ = Literal::Float(OrderedFloat(0.0)).traverse(&mut visitor); 75 | visitor.0 76 | }); 77 | 78 | assert!({ 79 | let mut visitor = FloatExpr(false); 80 | let _ = Literal::Float(OrderedFloat(0.0)).traverse_mut(&mut visitor); 81 | visitor.0 82 | }); 83 | } 84 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2025 FastLabs Developers 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | name: CI 16 | on: 17 | pull_request: 18 | branches: [ main ] 19 | push: 20 | branches: [ main ] 21 | 22 | # Concurrency strategy: 23 | # github.workflow: distinguish this workflow from others 24 | # github.event_name: distinguish `push` event from `pull_request` event 25 | # github.event.number: set to the number of the pull request if `pull_request` event 26 | # github.run_id: otherwise, it's a `push` event, only cancel if we rerun the workflow 27 | # 28 | # Reference: 29 | # https://docs.github.com/en/actions/using-jobs/using-concurrency 30 | # https://docs.github.com/en/actions/learn-github-actions/contexts#github-context 31 | concurrency: 32 | group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.run_id }} 33 | cancel-in-progress: true 34 | 35 | jobs: 36 | check: 37 | name: Check 38 | runs-on: ubuntu-22.04 39 | steps: 40 | - uses: actions/checkout@v4 41 | - name: Install toolchain 42 | uses: dtolnay/rust-toolchain@nightly 43 | with: 44 | components: rustfmt,clippy 45 | - uses: Swatinem/rust-cache@v2 46 | - uses: taiki-e/install-action@v2 47 | with: 48 | tool: typos-cli,taplo-cli,hawkeye 49 | - run: cargo +nightly x lint 50 | 51 | test: 52 | name: Run tests 53 | strategy: 54 | matrix: 55 | os: [ ubuntu-22.04, macos-14, windows-2022 ] 56 | rust-version: [ "1.85.0", "stable" ] 57 | runs-on: ${{ matrix.os }} 58 | steps: 59 | - uses: actions/checkout@v4 60 | - uses: Swatinem/rust-cache@v2 61 | - name: Delete rust-toolchain.toml 62 | run: rm rust-toolchain.toml 63 | - name: Install toolchain 64 | uses: dtolnay/rust-toolchain@master 65 | with: 66 | toolchain: ${{ matrix.rust-version }} 67 | - name: Run unit tests 68 | run: cargo x test --no-capture 69 | shell: bash 70 | 71 | required: 72 | name: Required 73 | runs-on: ubuntu-22.04 74 | if: ${{ always() }} 75 | needs: 76 | - check 77 | - test 78 | steps: 79 | - name: Guardian 80 | run: | 81 | if [[ ! ( \ 82 | "${{ needs.check.result }}" == "success" \ 83 | && "${{ needs.test.result }}" == "success" \ 84 | ) ]]; then 85 | echo "Required jobs haven't been completed successfully." 86 | exit -1 87 | fi 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Visitor Pattern over Traversable Data Structures in Rust 2 | 3 | [![Crates.io][crates-badge]][crates-url] 4 | [![Documentation][docs-badge]][docs-url] 5 | [![MSRV 1.85][msrv-badge]](https://www.whatrustisit.com) 6 | [![Apache 2.0 licensed][license-badge]][license-url] 7 | [![Build Status][actions-badge]][actions-url] 8 | 9 | [crates-badge]: https://img.shields.io/crates/v/traversable.svg 10 | [crates-url]: https://crates.io/crates/traversable 11 | [docs-badge]: https://docs.rs/traversable/badge.svg 12 | [msrv-badge]: https://img.shields.io/badge/MSRV-1.85-green?logo=rust 13 | [docs-url]: https://docs.rs/traversable 14 | [license-badge]: https://img.shields.io/crates/l/traversable 15 | [license-url]: LICENSE 16 | [actions-badge]: https://github.com/fast/traversable/workflows/CI/badge.svg 17 | [actions-url]:https://github.com/fast/traversable/actions?query=workflow%3ACI 18 | 19 | ## Overview 20 | 21 | This crate provides traits and proc macros to implement the visitor pattern for arbitrary data structures. This pattern is particularly useful when dealing with complex nested data structures, abstract trees and hierarchies of all kinds. 22 | 23 | ## Quick Start 24 | 25 | Add `traversable` to your `Cargo.toml` with the `derive` feature: 26 | 27 | ```toml 28 | [dependencies] 29 | traversable = { version = "0.2", features = ["derive", "std"] } 30 | ``` 31 | 32 | Define your data structures and derive `Traversable`: 33 | 34 | ```rust 35 | use std::any::Any; 36 | use std::ops::ControlFlow; 37 | 38 | use traversable::Traversable; 39 | use traversable::Visitor; 40 | 41 | #[derive(Traversable)] 42 | struct Directory { 43 | name: String, 44 | files: Vec, 45 | #[traverse(skip)] 46 | cache_id: u64, 47 | } 48 | 49 | #[derive(Traversable)] 50 | struct File { 51 | name: String, 52 | size: u64, 53 | } 54 | 55 | struct FileCounter { 56 | count: usize, 57 | total_size: u64, 58 | } 59 | 60 | impl Visitor for FileCounter { 61 | type Break = (); 62 | 63 | fn enter(&mut self, node: &dyn Any) -> ControlFlow { 64 | if let Some(file) = node.downcast_ref::() { 65 | self.count += 1; 66 | self.total_size += file.size; 67 | } 68 | ControlFlow::Continue(()) 69 | } 70 | } 71 | 72 | fn main() { 73 | let root = Directory { 74 | name: "root".to_string(), 75 | files: vec![ 76 | File { name: "a.txt".to_string(), size: 100 }, 77 | File { name: "b.rs".to_string(), size: 200 }, 78 | ], 79 | cache_id: 12345, 80 | }; 81 | 82 | let mut counter = FileCounter { count: 0, total_size: 0 }; 83 | root.traverse(&mut counter); 84 | 85 | assert_eq!(counter.count, 2); 86 | assert_eq!(counter.total_size, 300); 87 | } 88 | ``` 89 | 90 | ## Attributes 91 | 92 | The derive macro supports the following attributes on fields and variants: 93 | 94 | * `#[traverse(skip)]`: Skips traversing into the annotated field or variant. 95 | * `#[traverse(with = "function_name")]`: Uses a custom function to traverse the field. 96 | 97 | ## Minimum Rust version policy 98 | 99 | This crate is built against the latest stable release, and its minimum supported rustc version is 1.85.0. 100 | 101 | The policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if Traversable 1.0 requires Rust 1.60.0, then Traversable 1.0.z for all values of z will also require Rust 1.60.0 or newer. However, Traversable 1.y for y > 0 may require a newer minimum version of Rust. 102 | 103 | ## License 104 | 105 | This project is licensed under [Apache License, Version 2.0](LICENSE). 106 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::process::Command as StdCommand; 16 | 17 | use clap::Parser; 18 | use clap::Subcommand; 19 | 20 | #[derive(Parser)] 21 | struct Command { 22 | #[clap(subcommand)] 23 | sub: SubCommand, 24 | } 25 | 26 | impl Command { 27 | fn run(self) { 28 | match self.sub { 29 | SubCommand::Build(cmd) => cmd.run(), 30 | SubCommand::Lint(cmd) => cmd.run(), 31 | SubCommand::Test(cmd) => cmd.run(), 32 | } 33 | } 34 | } 35 | 36 | #[derive(Subcommand)] 37 | enum SubCommand { 38 | #[clap(about = "Compile workspace packages.")] 39 | Build(CommandBuild), 40 | #[clap(about = "Run format and clippy checks.")] 41 | Lint(CommandLint), 42 | #[clap(about = "Run unit tests.")] 43 | Test(CommandTest), 44 | } 45 | 46 | #[derive(Parser)] 47 | struct CommandBuild { 48 | #[arg(long, help = "Assert that `Cargo.lock` will remain unchanged.")] 49 | locked: bool, 50 | } 51 | 52 | impl CommandBuild { 53 | fn run(self) { 54 | run_command(make_build_cmd(self.locked)); 55 | } 56 | } 57 | 58 | #[derive(Parser)] 59 | struct CommandTest { 60 | #[arg(long, help = "Run tests serially and do not capture output.")] 61 | no_capture: bool, 62 | } 63 | 64 | impl CommandTest { 65 | fn run(self) { 66 | let features = ["std", "derive", "traverse-trivial", "traverse-std"]; 67 | 68 | for i in 0..(1 << features.len()) { 69 | let mut selected_features = vec![]; 70 | for (k, feature) in features.iter().enumerate() { 71 | if (i & (1 << k)) != 0 { 72 | selected_features.push(*feature); 73 | } 74 | } 75 | run_command(make_test_cmd(self.no_capture, &selected_features)); 76 | } 77 | } 78 | } 79 | 80 | #[derive(Parser)] 81 | #[clap(name = "lint")] 82 | struct CommandLint { 83 | #[arg(long, help = "Automatically apply lint suggestions.")] 84 | fix: bool, 85 | } 86 | 87 | impl CommandLint { 88 | fn run(self) { 89 | run_command(make_clippy_cmd(self.fix)); 90 | run_command(make_format_cmd(self.fix)); 91 | run_command(make_taplo_cmd(self.fix)); 92 | run_command(make_typos_cmd()); 93 | run_command(make_hawkeye_cmd(self.fix)); 94 | } 95 | } 96 | 97 | fn find_command(cmd: &str) -> StdCommand { 98 | match which::which(cmd) { 99 | Ok(exe) => { 100 | let mut cmd = StdCommand::new(exe); 101 | cmd.current_dir(env!("CARGO_WORKSPACE_DIR")); 102 | cmd 103 | } 104 | Err(err) => { 105 | panic!("{cmd} not found: {err}"); 106 | } 107 | } 108 | } 109 | 110 | fn ensure_installed(bin: &str, crate_name: &str) { 111 | if which::which(bin).is_err() { 112 | let mut cmd = find_command("cargo"); 113 | cmd.args(["install", crate_name]); 114 | run_command(cmd); 115 | } 116 | } 117 | 118 | fn run_command(mut cmd: StdCommand) { 119 | println!("{cmd:?}"); 120 | let status = cmd.status().expect("failed to execute process"); 121 | assert!(status.success(), "command failed: {status}"); 122 | } 123 | 124 | fn make_build_cmd(locked: bool) -> StdCommand { 125 | let mut cmd = find_command("cargo"); 126 | cmd.args([ 127 | "build", 128 | "--workspace", 129 | "--all-features", 130 | "--tests", 131 | "--examples", 132 | "--benches", 133 | "--bins", 134 | ]); 135 | if locked { 136 | cmd.arg("--locked"); 137 | } 138 | cmd 139 | } 140 | 141 | fn make_test_cmd(no_capture: bool, features: &[&str]) -> StdCommand { 142 | let mut cmd = find_command("cargo"); 143 | cmd.args(["test", "--workspace"]); 144 | if !features.is_empty() { 145 | cmd.args(["--features", features.join(",").as_str()]); 146 | } 147 | if no_capture { 148 | cmd.args(["--", "--nocapture"]); 149 | } 150 | cmd 151 | } 152 | 153 | fn make_format_cmd(fix: bool) -> StdCommand { 154 | let mut cmd = find_command("cargo"); 155 | cmd.args(["fmt", "--all"]); 156 | if !fix { 157 | cmd.arg("--check"); 158 | } 159 | cmd 160 | } 161 | 162 | fn make_clippy_cmd(fix: bool) -> StdCommand { 163 | let mut cmd = find_command("cargo"); 164 | cmd.args([ 165 | "clippy", 166 | "--tests", 167 | "--all-features", 168 | "--all-targets", 169 | "--workspace", 170 | ]); 171 | if fix { 172 | cmd.args(["--allow-staged", "--allow-dirty", "--fix"]); 173 | } else { 174 | cmd.args(["--", "-D", "warnings"]); 175 | } 176 | cmd 177 | } 178 | 179 | fn make_hawkeye_cmd(fix: bool) -> StdCommand { 180 | ensure_installed("hawkeye", "hawkeye"); 181 | let mut cmd = find_command("hawkeye"); 182 | if fix { 183 | cmd.args(["format", "--fail-if-updated=false"]); 184 | } else { 185 | cmd.args(["check"]); 186 | } 187 | cmd 188 | } 189 | 190 | fn make_typos_cmd() -> StdCommand { 191 | ensure_installed("typos", "typos-cli"); 192 | find_command("typos") 193 | } 194 | 195 | fn make_taplo_cmd(fix: bool) -> StdCommand { 196 | ensure_installed("taplo", "taplo-cli"); 197 | let mut cmd = find_command("taplo"); 198 | if fix { 199 | cmd.args(["format"]); 200 | } else { 201 | cmd.args(["format", "--check"]); 202 | } 203 | cmd 204 | } 205 | 206 | fn main() { 207 | let cmd = Command::parse(); 208 | cmd.run() 209 | } 210 | -------------------------------------------------------------------------------- /traversable/tests/test_combinator.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![cfg(all(feature = "std", feature = "derive"))] 16 | 17 | use std::any::Any; 18 | use std::cell::RefCell; 19 | use std::ops::ControlFlow; 20 | use std::rc::Rc; 21 | 22 | use traversable::Traversable; 23 | use traversable::TraversableMut; 24 | use traversable::Visitor; 25 | use traversable::VisitorMut; 26 | use traversable::combinator::VisitorExt; 27 | use traversable::combinator::VisitorMutExt; 28 | 29 | #[derive(Traversable, TraversableMut)] 30 | struct Data { 31 | val: i32, 32 | child: Option>, 33 | } 34 | 35 | #[derive(Clone)] 36 | struct RecordVisitor { 37 | log: Rc>>, 38 | name: String, 39 | break_on: Option, 40 | } 41 | 42 | impl Visitor for RecordVisitor { 43 | type Break = i32; 44 | 45 | fn enter(&mut self, this: &dyn Any) -> ControlFlow { 46 | if let Some(d) = this.downcast_ref::() { 47 | self.log 48 | .borrow_mut() 49 | .push(format!("{}: enter {}", self.name, d.val)); 50 | if Some(d.val) == self.break_on { 51 | return ControlFlow::Break(d.val); 52 | } 53 | } 54 | ControlFlow::Continue(()) 55 | } 56 | 57 | fn leave(&mut self, this: &dyn Any) -> ControlFlow { 58 | if let Some(d) = this.downcast_ref::() { 59 | self.log 60 | .borrow_mut() 61 | .push(format!("{}: leave {}", self.name, d.val)); 62 | } 63 | ControlFlow::Continue(()) 64 | } 65 | } 66 | 67 | #[test] 68 | fn test_visitor_or() { 69 | let data = Data { 70 | val: 1, 71 | child: Some(Box::new(Data { 72 | val: 2, 73 | child: None, 74 | })), 75 | }; 76 | 77 | let log = Rc::new(RefCell::new(Vec::new())); 78 | let v1 = RecordVisitor { 79 | log: log.clone(), 80 | name: "v1".to_string(), 81 | break_on: None, 82 | }; 83 | let v2 = RecordVisitor { 84 | log: log.clone(), 85 | name: "v2".to_string(), 86 | break_on: None, 87 | }; 88 | 89 | let mut combined = v1.chain(v2); 90 | let result = data.traverse(&mut combined); 91 | assert!(result.is_continue()); 92 | 93 | let expected = vec![ 94 | "v1: enter 1", 95 | "v2: enter 1", 96 | "v1: enter 2", 97 | "v2: enter 2", 98 | "v1: leave 2", 99 | "v2: leave 2", 100 | "v1: leave 1", 101 | "v2: leave 1", 102 | ]; 103 | assert_eq!(*log.borrow(), expected); 104 | } 105 | 106 | #[test] 107 | fn test_visitor_or_break_v1() { 108 | let data = Data { 109 | val: 1, 110 | child: Some(Box::new(Data { 111 | val: 2, 112 | child: None, 113 | })), 114 | }; 115 | 116 | let log = Rc::new(RefCell::new(Vec::new())); 117 | // v1 breaks on 2 118 | let v1 = RecordVisitor { 119 | log: log.clone(), 120 | name: "v1".to_string(), 121 | break_on: Some(2), 122 | }; 123 | let v2 = RecordVisitor { 124 | log: log.clone(), 125 | name: "v2".to_string(), 126 | break_on: None, 127 | }; 128 | 129 | let mut combined = v1.chain(v2); 130 | let result = data.traverse(&mut combined); 131 | assert_eq!(result, ControlFlow::Break(2)); 132 | 133 | let expected = vec![ 134 | "v1: enter 1", 135 | "v2: enter 1", 136 | "v1: enter 2", // v1 breaks here, v2 not called for 2, and traversal stops 137 | ]; 138 | assert_eq!(*log.borrow(), expected); 139 | } 140 | 141 | #[test] 142 | fn test_visitor_or_break_v2() { 143 | let data = Data { 144 | val: 1, 145 | child: Some(Box::new(Data { 146 | val: 2, 147 | child: None, 148 | })), 149 | }; 150 | 151 | let log = Rc::new(RefCell::new(Vec::new())); 152 | // v2 breaks on 2 153 | let v1 = RecordVisitor { 154 | log: log.clone(), 155 | name: "v1".to_string(), 156 | break_on: None, 157 | }; 158 | let v2 = RecordVisitor { 159 | log: log.clone(), 160 | name: "v2".to_string(), 161 | break_on: Some(2), 162 | }; 163 | 164 | let mut combined = v1.chain(v2); 165 | let result = data.traverse(&mut combined); 166 | assert_eq!(result, ControlFlow::Break(2)); 167 | 168 | let expected = vec![ 169 | "v1: enter 1", 170 | "v2: enter 1", 171 | "v1: enter 2", 172 | "v2: enter 2", // v2 breaks here 173 | ]; 174 | assert_eq!(*log.borrow(), expected); 175 | } 176 | 177 | struct MutVisitor { 178 | val_multiplier: i32, 179 | } 180 | 181 | impl VisitorMut for MutVisitor { 182 | type Break = (); 183 | fn enter_mut(&mut self, this: &mut dyn Any) -> ControlFlow<()> { 184 | if let Some(d) = this.downcast_mut::() { 185 | d.val *= self.val_multiplier; 186 | } 187 | ControlFlow::Continue(()) 188 | } 189 | } 190 | 191 | #[test] 192 | fn test_visitor_mut_or() { 193 | let mut data = Data { 194 | val: 1, 195 | child: Some(Box::new(Data { 196 | val: 2, 197 | child: None, 198 | })), 199 | }; 200 | 201 | let v1 = MutVisitor { val_multiplier: 2 }; 202 | let v2 = MutVisitor { val_multiplier: 3 }; 203 | 204 | let mut combined = v1.chain(v2); 205 | let result = data.traverse_mut(&mut combined); 206 | assert!(result.is_continue()); 207 | 208 | // 1 * 2 * 3 = 6 209 | assert_eq!(data.val, 6); 210 | // 2 * 2 * 3 = 12 211 | assert_eq!(data.child.unwrap().val, 12); 212 | } 213 | -------------------------------------------------------------------------------- /traversable/src/combinator.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! Combinators for Visitors. 16 | 17 | use core::ops::ControlFlow; 18 | 19 | use crate::Visitor; 20 | use crate::VisitorMut; 21 | 22 | /// Extension trait for [`Visitor`]s. 23 | pub trait VisitorExt: Visitor { 24 | /// Combines two visitors into one that runs them in sequence. 25 | /// 26 | /// If the first visitor returns [`ControlFlow::Break`], the combined visitor returns that break 27 | /// immediately. Otherwise, it runs the second visitor. 28 | /// 29 | /// # Examples 30 | /// 31 | /// ``` 32 | /// # #[cfg(not(feature = "derive"))] 33 | /// # fn main() {} 34 | /// # 35 | /// # #[cfg(feature = "derive")] 36 | /// # fn main() { 37 | /// use core::ops::ControlFlow; 38 | /// 39 | /// use traversable::Traversable; 40 | /// use traversable::Visitor; 41 | /// use traversable::combinator::VisitorExt; 42 | /// use traversable::function::visitor_enter; 43 | /// 44 | /// #[derive(Traversable)] 45 | /// struct Foo(i32); 46 | /// 47 | /// #[derive(Traversable)] 48 | /// struct Bar(i32); 49 | /// 50 | /// #[derive(Traversable)] 51 | /// struct Data { 52 | /// foo: Foo, 53 | /// bar: Bar, 54 | /// } 55 | /// 56 | /// let data = Data { 57 | /// foo: Foo(1), 58 | /// bar: Bar(2), 59 | /// }; 60 | /// 61 | /// let v1 = visitor_enter(|foo: &Foo| { 62 | /// println!("Visiting Foo: {}", foo.0); 63 | /// ControlFlow::<()>::Continue(()) 64 | /// }); 65 | /// 66 | /// let v2 = visitor_enter(|bar: &Bar| { 67 | /// println!("Visiting Bar: {}", bar.0); 68 | /// ControlFlow::<()>::Continue(()) 69 | /// }); 70 | /// 71 | /// // v1 runs first, then v2. 72 | /// let mut combined = v1.chain(v2); 73 | /// data.traverse(&mut combined); 74 | /// # } 75 | /// ``` 76 | fn chain(self, other: V) -> Chain 77 | where 78 | Self: Sized, 79 | V: Visitor, 80 | { 81 | Chain { 82 | visitor1: self, 83 | visitor2: other, 84 | } 85 | } 86 | } 87 | 88 | impl VisitorExt for V {} 89 | 90 | /// Extension trait for [`VisitorMut`]s. 91 | pub trait VisitorMutExt: VisitorMut { 92 | /// Combines two mutable visitors into one that runs them in sequence. 93 | /// 94 | /// If the first visitor returns [`ControlFlow::Break`], the combined visitor returns that break 95 | /// immediately. Otherwise, it runs the second visitor. 96 | /// 97 | /// # Examples 98 | /// 99 | /// ``` 100 | /// # #[cfg(not(feature = "derive"))] 101 | /// # fn main() {} 102 | /// # 103 | /// # #[cfg(feature = "derive")] 104 | /// # fn main() { 105 | /// use core::ops::ControlFlow; 106 | /// 107 | /// use traversable::TraversableMut; 108 | /// use traversable::VisitorMut; 109 | /// use traversable::combinator::VisitorMutExt; 110 | /// use traversable::function::visitor_enter_mut; 111 | /// 112 | /// #[derive(TraversableMut)] 113 | /// struct Foo(i32); 114 | /// 115 | /// #[derive(TraversableMut)] 116 | /// struct Bar(i32); 117 | /// 118 | /// #[derive(TraversableMut)] 119 | /// struct Data { 120 | /// foo: Foo, 121 | /// bar: Bar, 122 | /// } 123 | /// 124 | /// let mut data = Data { 125 | /// foo: Foo(1), 126 | /// bar: Bar(2), 127 | /// }; 128 | /// 129 | /// let v1 = visitor_enter_mut(|foo: &mut Foo| { 130 | /// foo.0 += 1; 131 | /// ControlFlow::<()>::Continue(()) 132 | /// }); 133 | /// 134 | /// let v2 = visitor_enter_mut(|bar: &mut Bar| { 135 | /// bar.0 *= 2; 136 | /// ControlFlow::<()>::Continue(()) 137 | /// }); 138 | /// 139 | /// let mut combined = v1.chain(v2); 140 | /// data.traverse_mut(&mut combined); 141 | /// 142 | /// assert_eq!(data.foo.0, 2); 143 | /// assert_eq!(data.bar.0, 4); 144 | /// # } 145 | /// ``` 146 | fn chain(self, other: V) -> Chain 147 | where 148 | Self: Sized, 149 | V: VisitorMut, 150 | { 151 | Chain { 152 | visitor1: self, 153 | visitor2: other, 154 | } 155 | } 156 | } 157 | 158 | impl VisitorMutExt for V {} 159 | 160 | /// A visitor that runs two visitors in sequence. 161 | /// 162 | /// This struct is created by [`VisitorExt::chain`] or [`VisitorMutExt::chain`]. 163 | pub struct Chain { 164 | visitor1: V1, 165 | visitor2: V2, 166 | } 167 | 168 | impl Visitor for Chain 169 | where 170 | V1: Visitor, 171 | V2: Visitor, 172 | { 173 | type Break = V1::Break; 174 | 175 | fn enter(&mut self, this: &dyn core::any::Any) -> ControlFlow { 176 | self.visitor1.enter(this)?; 177 | self.visitor2.enter(this) 178 | } 179 | 180 | fn leave(&mut self, this: &dyn core::any::Any) -> ControlFlow { 181 | self.visitor1.leave(this)?; 182 | self.visitor2.leave(this) 183 | } 184 | } 185 | 186 | impl VisitorMut for Chain 187 | where 188 | V1: VisitorMut, 189 | V2: VisitorMut, 190 | { 191 | type Break = V1::Break; 192 | 193 | fn enter_mut(&mut self, this: &mut dyn core::any::Any) -> ControlFlow { 194 | self.visitor1.enter_mut(this)?; 195 | self.visitor2.enter_mut(this) 196 | } 197 | 198 | fn leave_mut(&mut self, this: &mut dyn core::any::Any) -> ControlFlow { 199 | self.visitor1.leave_mut(this)?; 200 | self.visitor2.leave_mut(this) 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /traversable/src/function.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! Visitors from functions or closures. 16 | 17 | use core::any::Any; 18 | use core::marker::PhantomData; 19 | use core::ops::ControlFlow; 20 | 21 | use crate::Visitor; 22 | use crate::VisitorMut; 23 | 24 | /// Type returned by `visitor` factories. 25 | pub struct FnVisitor { 26 | enter: F1, 27 | leave: F2, 28 | marker_type: PhantomData, 29 | marker_break: PhantomData, 30 | } 31 | 32 | impl Visitor for FnVisitor 33 | where 34 | T: Any, 35 | F1: FnMut(&T) -> ControlFlow, 36 | F2: FnMut(&T) -> ControlFlow, 37 | { 38 | type Break = B; 39 | 40 | fn enter(&mut self, this: &dyn Any) -> ControlFlow { 41 | if let Some(item) = this.downcast_ref::() { 42 | (self.enter)(item)?; 43 | } 44 | ControlFlow::Continue(()) 45 | } 46 | 47 | fn leave(&mut self, this: &dyn Any) -> ControlFlow { 48 | if let Some(item) = this.downcast_ref::() { 49 | (self.leave)(item)?; 50 | } 51 | ControlFlow::Continue(()) 52 | } 53 | } 54 | 55 | impl VisitorMut for FnVisitor 56 | where 57 | T: Any, 58 | F1: FnMut(&mut T) -> ControlFlow, 59 | F2: FnMut(&mut T) -> ControlFlow, 60 | { 61 | type Break = B; 62 | 63 | fn enter_mut(&mut self, this: &mut dyn Any) -> ControlFlow { 64 | if let Some(item) = this.downcast_mut::() { 65 | (self.enter)(item)?; 66 | } 67 | ControlFlow::Continue(()) 68 | } 69 | 70 | fn leave_mut(&mut self, this: &mut dyn Any) -> ControlFlow { 71 | if let Some(item) = this.downcast_mut::() { 72 | (self.leave)(item)?; 73 | } 74 | ControlFlow::Continue(()) 75 | } 76 | } 77 | 78 | type DefaultVisitFn = fn(&T) -> ControlFlow; 79 | type DefaultVisitFnMut = fn(&mut T) -> ControlFlow; 80 | 81 | /// Create a visitor that only visits items of a specific type from `enter` and `leave` closures. 82 | /// 83 | /// This is a convenience function for creating simple visitors without defining 84 | /// a new struct and implementing the [`Visitor`] trait manually. 85 | /// 86 | /// # Example 87 | /// 88 | /// ```rust 89 | /// # #[cfg(not(feature = "derive"))] 90 | /// # fn main() {} 91 | /// # 92 | /// # #[cfg(feature = "derive")] 93 | /// # fn main() { 94 | /// use core::ops::ControlFlow; 95 | /// 96 | /// use traversable::Traversable; 97 | /// use traversable::Visitor; 98 | /// use traversable::function::visitor; 99 | /// 100 | /// #[derive(Traversable)] 101 | /// struct Item { 102 | /// value: i32, 103 | /// } 104 | /// 105 | /// let item = Item { value: 10 }; 106 | /// let mut total_value = 0; 107 | /// 108 | /// let mut visitor = visitor::( 109 | /// |node: &Item| { 110 | /// // enter closure 111 | /// total_value += node.value; 112 | /// ControlFlow::Continue(()) 113 | /// }, 114 | /// |_node: &Item| { 115 | /// // leave closure 116 | /// ControlFlow::Continue(()) 117 | /// }, 118 | /// ); 119 | /// 120 | /// item.traverse(&mut visitor); 121 | /// assert_eq!(total_value, 10); 122 | /// # } 123 | /// ``` 124 | pub fn visitor(enter: F1, leave: F2) -> FnVisitor 125 | where 126 | T: Any, 127 | F1: FnMut(&T) -> ControlFlow, 128 | F2: FnMut(&T) -> ControlFlow, 129 | { 130 | FnVisitor { 131 | enter, 132 | leave, 133 | marker_type: PhantomData, 134 | marker_break: PhantomData, 135 | } 136 | } 137 | 138 | /// Similar to [`visitor`], but the closure will only be called on entering. 139 | /// 140 | /// # Example 141 | /// 142 | /// ```rust 143 | /// # #[cfg(not(feature = "derive"))] 144 | /// # fn main() {} 145 | /// # 146 | /// # #[cfg(feature = "derive")] 147 | /// # fn main() { 148 | /// use core::ops::ControlFlow; 149 | /// 150 | /// use traversable::Traversable; 151 | /// use traversable::Visitor; 152 | /// use traversable::function::visitor_enter; 153 | /// 154 | /// #[derive(Traversable)] 155 | /// struct Item { 156 | /// value: i32, 157 | /// } 158 | /// 159 | /// let item = Item { value: 20 }; 160 | /// let mut count = 0; 161 | /// 162 | /// let mut visitor = visitor_enter::(|node: &Item| { 163 | /// // enter closure 164 | /// count += 1; 165 | /// ControlFlow::Continue(()) 166 | /// }); 167 | /// 168 | /// item.traverse(&mut visitor); 169 | /// assert_eq!(count, 1); 170 | /// # } 171 | /// ``` 172 | pub fn visitor_enter(enter: F) -> FnVisitor> 173 | where 174 | T: Any, 175 | F: FnMut(&T) -> ControlFlow, 176 | { 177 | FnVisitor { 178 | enter, 179 | leave: |_| ControlFlow::Continue(()), 180 | marker_type: PhantomData, 181 | marker_break: PhantomData, 182 | } 183 | } 184 | 185 | /// Similar to [`visitor`], but the closure will only be called on leaving. 186 | /// 187 | /// # Example 188 | /// 189 | /// ```rust 190 | /// # #[cfg(not(feature = "derive"))] 191 | /// # fn main() {} 192 | /// # 193 | /// # #[cfg(feature = "derive")] 194 | /// # fn main() { 195 | /// use core::ops::ControlFlow; 196 | /// 197 | /// use traversable::Traversable; 198 | /// use traversable::Visitor; 199 | /// use traversable::function::visitor_leave; 200 | /// 201 | /// #[derive(Traversable)] 202 | /// struct Item { 203 | /// value: i32, 204 | /// } 205 | /// 206 | /// let item = Item { value: 30 }; 207 | /// let mut visited_leave = false; 208 | /// 209 | /// let mut visitor = visitor_leave::(|node: &Item| { 210 | /// // leave closure 211 | /// visited_leave = true; 212 | /// ControlFlow::Continue(()) 213 | /// }); 214 | /// 215 | /// item.traverse(&mut visitor); 216 | /// assert!(visited_leave); 217 | /// # } 218 | /// ``` 219 | pub fn visitor_leave(leave: F) -> FnVisitor, F> 220 | where 221 | T: Any, 222 | F: FnMut(&T) -> ControlFlow, 223 | { 224 | FnVisitor { 225 | enter: |_| ControlFlow::Continue(()), 226 | leave, 227 | marker_type: PhantomData, 228 | marker_break: PhantomData, 229 | } 230 | } 231 | 232 | /// Create a visitor that only visits mutable items of a specific type from `enter` and `leave` 233 | /// closures. 234 | /// 235 | /// This is a convenience function for creating simple mutable visitors without defining 236 | /// a new struct and implementing the [`VisitorMut`] trait manually. 237 | /// 238 | /// # Example 239 | /// 240 | /// ```rust 241 | /// # #[cfg(not(feature = "derive"))] 242 | /// # fn main() {} 243 | /// # 244 | /// # #[cfg(feature = "derive")] 245 | /// # fn main() { 246 | /// use core::ops::ControlFlow; 247 | /// 248 | /// use traversable::TraversableMut; 249 | /// use traversable::VisitorMut; 250 | /// use traversable::function::visitor_mut; 251 | /// 252 | /// #[derive(TraversableMut)] 253 | /// struct Item { 254 | /// value: i32, 255 | /// } 256 | /// 257 | /// let mut item = Item { value: 10 }; 258 | /// 259 | /// let mut visitor = visitor_mut::( 260 | /// |node: &mut Item| { 261 | /// // enter_mut closure 262 | /// node.value += 1; 263 | /// ControlFlow::Continue(()) 264 | /// }, 265 | /// |_node: &mut Item| { 266 | /// // leave_mut closure 267 | /// ControlFlow::Continue(()) 268 | /// }, 269 | /// ); 270 | /// 271 | /// item.traverse_mut(&mut visitor); 272 | /// assert_eq!(item.value, 11); 273 | /// # } 274 | /// ``` 275 | pub fn visitor_mut(enter: F1, leave: F2) -> FnVisitor 276 | where 277 | T: Any, 278 | F1: FnMut(&mut T) -> ControlFlow, 279 | F2: FnMut(&mut T) -> ControlFlow, 280 | { 281 | FnVisitor { 282 | enter, 283 | leave, 284 | marker_type: PhantomData, 285 | marker_break: PhantomData, 286 | } 287 | } 288 | 289 | /// Similar to [`visitor_mut`], but the closure will only be called on entering. 290 | /// 291 | /// # Example 292 | /// 293 | /// ```rust 294 | /// # #[cfg(not(feature = "derive"))] 295 | /// # fn main() {} 296 | /// # 297 | /// # #[cfg(feature = "derive")] 298 | /// # fn main() { 299 | /// use core::ops::ControlFlow; 300 | /// 301 | /// use traversable::TraversableMut; 302 | /// use traversable::VisitorMut; 303 | /// use traversable::function::visitor_enter_mut; 304 | /// 305 | /// #[derive(TraversableMut)] 306 | /// struct Item { 307 | /// value: i32, 308 | /// } 309 | /// 310 | /// let mut item = Item { value: 20 }; 311 | /// let mut count = 0; 312 | /// 313 | /// let mut visitor = visitor_enter_mut::(|node: &mut Item| { 314 | /// // enter_mut closure 315 | /// count += 1; 316 | /// ControlFlow::Continue(()) 317 | /// }); 318 | /// 319 | /// item.traverse_mut(&mut visitor); 320 | /// assert_eq!(count, 1); 321 | /// # } 322 | /// ``` 323 | pub fn visitor_enter_mut(enter: F) -> FnVisitor> 324 | where 325 | T: Any, 326 | F: FnMut(&mut T) -> ControlFlow, 327 | { 328 | FnVisitor { 329 | enter, 330 | leave: |_| ControlFlow::Continue(()), 331 | marker_type: PhantomData, 332 | marker_break: PhantomData, 333 | } 334 | } 335 | 336 | /// Similar to [`visitor_mut`], but the closure will only be called on leaving. 337 | /// 338 | /// # Example 339 | /// 340 | /// ```rust 341 | /// # #[cfg(not(feature = "derive"))] 342 | /// # fn main() {} 343 | /// # 344 | /// # #[cfg(feature = "derive")] 345 | /// # fn main() { 346 | /// use core::ops::ControlFlow; 347 | /// 348 | /// use traversable::TraversableMut; 349 | /// use traversable::VisitorMut; 350 | /// use traversable::function::visitor_leave_mut; 351 | /// 352 | /// #[derive(TraversableMut)] 353 | /// struct Item { 354 | /// value: i32, 355 | /// } 356 | /// 357 | /// let mut item = Item { value: 30 }; 358 | /// let mut visited_leave = false; 359 | /// 360 | /// let mut visitor = visitor_leave_mut::(|node: &mut Item| { 361 | /// // leave_mut closure 362 | /// visited_leave = true; 363 | /// ControlFlow::Continue(()) 364 | /// }); 365 | /// 366 | /// item.traverse_mut(&mut visitor); 367 | /// assert!(visited_leave); 368 | /// # } 369 | /// ``` 370 | pub fn visitor_leave_mut(leave: F) -> FnVisitor, F> 371 | where 372 | T: Any, 373 | F: FnMut(&mut T) -> ControlFlow, 374 | { 375 | FnVisitor { 376 | enter: |_| ControlFlow::Continue(()), 377 | leave, 378 | marker_type: PhantomData, 379 | marker_break: PhantomData, 380 | } 381 | } 382 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /traversable-derive/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "anstream" 7 | version = "0.6.18" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" 10 | dependencies = [ 11 | "anstyle", 12 | "anstyle-parse", 13 | "anstyle-query", 14 | "anstyle-wincon", 15 | "colorchoice", 16 | "is_terminal_polyfill", 17 | "utf8parse", 18 | ] 19 | 20 | [[package]] 21 | name = "anstyle" 22 | version = "1.0.10" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" 25 | 26 | [[package]] 27 | name = "anstyle-parse" 28 | version = "0.2.6" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" 31 | dependencies = [ 32 | "utf8parse", 33 | ] 34 | 35 | [[package]] 36 | name = "anstyle-query" 37 | version = "1.1.2" 38 | source = "registry+https://github.com/rust-lang/crates.io-index" 39 | checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" 40 | dependencies = [ 41 | "windows-sys", 42 | ] 43 | 44 | [[package]] 45 | name = "anstyle-wincon" 46 | version = "3.0.6" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" 49 | dependencies = [ 50 | "anstyle", 51 | "windows-sys", 52 | ] 53 | 54 | [[package]] 55 | name = "autocfg" 56 | version = "1.5.0" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" 59 | 60 | [[package]] 61 | name = "bitflags" 62 | version = "2.6.0" 63 | source = "registry+https://github.com/rust-lang/crates.io-index" 64 | checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" 65 | 66 | [[package]] 67 | name = "cc" 68 | version = "1.2.43" 69 | source = "registry+https://github.com/rust-lang/crates.io-index" 70 | checksum = "739eb0f94557554b3ca9a86d2d37bebd49c5e6d0c1d2bda35ba5bdac830befc2" 71 | dependencies = [ 72 | "find-msvc-tools", 73 | "shlex", 74 | ] 75 | 76 | [[package]] 77 | name = "cfg-if" 78 | version = "1.0.4" 79 | source = "registry+https://github.com/rust-lang/crates.io-index" 80 | checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" 81 | 82 | [[package]] 83 | name = "clap" 84 | version = "4.5.23" 85 | source = "registry+https://github.com/rust-lang/crates.io-index" 86 | checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" 87 | dependencies = [ 88 | "clap_builder", 89 | "clap_derive", 90 | ] 91 | 92 | [[package]] 93 | name = "clap_builder" 94 | version = "4.5.23" 95 | source = "registry+https://github.com/rust-lang/crates.io-index" 96 | checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" 97 | dependencies = [ 98 | "anstream", 99 | "anstyle", 100 | "clap_lex", 101 | "strsim", 102 | ] 103 | 104 | [[package]] 105 | name = "clap_derive" 106 | version = "4.5.18" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" 109 | dependencies = [ 110 | "heck", 111 | "proc-macro2", 112 | "quote", 113 | "syn", 114 | ] 115 | 116 | [[package]] 117 | name = "clap_lex" 118 | version = "0.7.4" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" 121 | 122 | [[package]] 123 | name = "colorchoice" 124 | version = "1.0.3" 125 | source = "registry+https://github.com/rust-lang/crates.io-index" 126 | checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" 127 | 128 | [[package]] 129 | name = "env_home" 130 | version = "0.1.0" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" 133 | 134 | [[package]] 135 | name = "errno" 136 | version = "0.3.10" 137 | source = "registry+https://github.com/rust-lang/crates.io-index" 138 | checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" 139 | dependencies = [ 140 | "libc", 141 | "windows-sys", 142 | ] 143 | 144 | [[package]] 145 | name = "find-msvc-tools" 146 | version = "0.1.4" 147 | source = "registry+https://github.com/rust-lang/crates.io-index" 148 | checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" 149 | 150 | [[package]] 151 | name = "heck" 152 | version = "0.5.0" 153 | source = "registry+https://github.com/rust-lang/crates.io-index" 154 | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" 155 | 156 | [[package]] 157 | name = "is_terminal_polyfill" 158 | version = "1.70.1" 159 | source = "registry+https://github.com/rust-lang/crates.io-index" 160 | checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" 161 | 162 | [[package]] 163 | name = "libc" 164 | version = "0.2.177" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" 167 | 168 | [[package]] 169 | name = "linux-raw-sys" 170 | version = "0.11.0" 171 | source = "registry+https://github.com/rust-lang/crates.io-index" 172 | checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" 173 | 174 | [[package]] 175 | name = "num-traits" 176 | version = "0.2.19" 177 | source = "registry+https://github.com/rust-lang/crates.io-index" 178 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 179 | dependencies = [ 180 | "autocfg", 181 | ] 182 | 183 | [[package]] 184 | name = "ordered-float" 185 | version = "5.1.0" 186 | source = "registry+https://github.com/rust-lang/crates.io-index" 187 | checksum = "7f4779c6901a562440c3786d08192c6fbda7c1c2060edd10006b05ee35d10f2d" 188 | dependencies = [ 189 | "num-traits", 190 | ] 191 | 192 | [[package]] 193 | name = "proc-macro-error-attr2" 194 | version = "2.0.0" 195 | source = "registry+https://github.com/rust-lang/crates.io-index" 196 | checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" 197 | dependencies = [ 198 | "proc-macro2", 199 | "quote", 200 | ] 201 | 202 | [[package]] 203 | name = "proc-macro-error2" 204 | version = "2.0.1" 205 | source = "registry+https://github.com/rust-lang/crates.io-index" 206 | checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" 207 | dependencies = [ 208 | "proc-macro-error-attr2", 209 | "proc-macro2", 210 | "quote", 211 | "syn", 212 | ] 213 | 214 | [[package]] 215 | name = "proc-macro2" 216 | version = "1.0.101" 217 | source = "registry+https://github.com/rust-lang/crates.io-index" 218 | checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" 219 | dependencies = [ 220 | "unicode-ident", 221 | ] 222 | 223 | [[package]] 224 | name = "psm" 225 | version = "0.1.27" 226 | source = "registry+https://github.com/rust-lang/crates.io-index" 227 | checksum = "e66fcd288453b748497d8fb18bccc83a16b0518e3906d4b8df0a8d42d93dbb1c" 228 | dependencies = [ 229 | "cc", 230 | ] 231 | 232 | [[package]] 233 | name = "quote" 234 | version = "1.0.41" 235 | source = "registry+https://github.com/rust-lang/crates.io-index" 236 | checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" 237 | dependencies = [ 238 | "proc-macro2", 239 | ] 240 | 241 | [[package]] 242 | name = "rustix" 243 | version = "1.1.2" 244 | source = "registry+https://github.com/rust-lang/crates.io-index" 245 | checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" 246 | dependencies = [ 247 | "bitflags", 248 | "errno", 249 | "libc", 250 | "linux-raw-sys", 251 | "windows-sys", 252 | ] 253 | 254 | [[package]] 255 | name = "shlex" 256 | version = "1.3.0" 257 | source = "registry+https://github.com/rust-lang/crates.io-index" 258 | checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" 259 | 260 | [[package]] 261 | name = "stacker" 262 | version = "0.1.22" 263 | source = "registry+https://github.com/rust-lang/crates.io-index" 264 | checksum = "e1f8b29fb42aafcea4edeeb6b2f2d7ecd0d969c48b4cf0d2e64aafc471dd6e59" 265 | dependencies = [ 266 | "cc", 267 | "cfg-if", 268 | "libc", 269 | "psm", 270 | "windows-sys", 271 | ] 272 | 273 | [[package]] 274 | name = "stacksafe" 275 | version = "1.0.0" 276 | source = "registry+https://github.com/rust-lang/crates.io-index" 277 | checksum = "e5481855df765c006135651b88e666edd4f08e176183052d2cb8628450873acb" 278 | dependencies = [ 279 | "stacker", 280 | "stacksafe-macro", 281 | ] 282 | 283 | [[package]] 284 | name = "stacksafe-macro" 285 | version = "1.0.0" 286 | source = "registry+https://github.com/rust-lang/crates.io-index" 287 | checksum = "4825bd5b513e9bc047a10ffc1680d1203ef548bdccd633d633a15630f01d126f" 288 | dependencies = [ 289 | "proc-macro-error2", 290 | "quote", 291 | "syn", 292 | ] 293 | 294 | [[package]] 295 | name = "strsim" 296 | version = "0.11.1" 297 | source = "registry+https://github.com/rust-lang/crates.io-index" 298 | checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" 299 | 300 | [[package]] 301 | name = "syn" 302 | version = "2.0.106" 303 | source = "registry+https://github.com/rust-lang/crates.io-index" 304 | checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" 305 | dependencies = [ 306 | "proc-macro2", 307 | "quote", 308 | "unicode-ident", 309 | ] 310 | 311 | [[package]] 312 | name = "traversable" 313 | version = "0.2.0" 314 | dependencies = [ 315 | "ordered-float", 316 | "stacksafe", 317 | "traversable-derive", 318 | ] 319 | 320 | [[package]] 321 | name = "traversable-derive" 322 | version = "0.1.0" 323 | dependencies = [ 324 | "proc-macro2", 325 | "quote", 326 | "syn", 327 | ] 328 | 329 | [[package]] 330 | name = "unicode-ident" 331 | version = "1.0.14" 332 | source = "registry+https://github.com/rust-lang/crates.io-index" 333 | checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" 334 | 335 | [[package]] 336 | name = "utf8parse" 337 | version = "0.2.2" 338 | source = "registry+https://github.com/rust-lang/crates.io-index" 339 | checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" 340 | 341 | [[package]] 342 | name = "which" 343 | version = "8.0.0" 344 | source = "registry+https://github.com/rust-lang/crates.io-index" 345 | checksum = "d3fabb953106c3c8eea8306e4393700d7657561cb43122571b172bbfb7c7ba1d" 346 | dependencies = [ 347 | "env_home", 348 | "rustix", 349 | "winsafe", 350 | ] 351 | 352 | [[package]] 353 | name = "windows-sys" 354 | version = "0.59.0" 355 | source = "registry+https://github.com/rust-lang/crates.io-index" 356 | checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" 357 | dependencies = [ 358 | "windows-targets", 359 | ] 360 | 361 | [[package]] 362 | name = "windows-targets" 363 | version = "0.52.6" 364 | source = "registry+https://github.com/rust-lang/crates.io-index" 365 | checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" 366 | dependencies = [ 367 | "windows_aarch64_gnullvm", 368 | "windows_aarch64_msvc", 369 | "windows_i686_gnu", 370 | "windows_i686_gnullvm", 371 | "windows_i686_msvc", 372 | "windows_x86_64_gnu", 373 | "windows_x86_64_gnullvm", 374 | "windows_x86_64_msvc", 375 | ] 376 | 377 | [[package]] 378 | name = "windows_aarch64_gnullvm" 379 | version = "0.52.6" 380 | source = "registry+https://github.com/rust-lang/crates.io-index" 381 | checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" 382 | 383 | [[package]] 384 | name = "windows_aarch64_msvc" 385 | version = "0.52.6" 386 | source = "registry+https://github.com/rust-lang/crates.io-index" 387 | checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" 388 | 389 | [[package]] 390 | name = "windows_i686_gnu" 391 | version = "0.52.6" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" 394 | 395 | [[package]] 396 | name = "windows_i686_gnullvm" 397 | version = "0.52.6" 398 | source = "registry+https://github.com/rust-lang/crates.io-index" 399 | checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" 400 | 401 | [[package]] 402 | name = "windows_i686_msvc" 403 | version = "0.52.6" 404 | source = "registry+https://github.com/rust-lang/crates.io-index" 405 | checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" 406 | 407 | [[package]] 408 | name = "windows_x86_64_gnu" 409 | version = "0.52.6" 410 | source = "registry+https://github.com/rust-lang/crates.io-index" 411 | checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" 412 | 413 | [[package]] 414 | name = "windows_x86_64_gnullvm" 415 | version = "0.52.6" 416 | source = "registry+https://github.com/rust-lang/crates.io-index" 417 | checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" 418 | 419 | [[package]] 420 | name = "windows_x86_64_msvc" 421 | version = "0.52.6" 422 | source = "registry+https://github.com/rust-lang/crates.io-index" 423 | checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" 424 | 425 | [[package]] 426 | name = "winsafe" 427 | version = "0.0.19" 428 | source = "registry+https://github.com/rust-lang/crates.io-index" 429 | checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" 430 | 431 | [[package]] 432 | name = "x" 433 | version = "0.0.0" 434 | dependencies = [ 435 | "clap", 436 | "which", 437 | ] 438 | -------------------------------------------------------------------------------- /traversable-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::HashMap; 16 | use std::collections::hash_map::Entry; 17 | use std::iter::IntoIterator; 18 | 19 | use proc_macro2::Span; 20 | use proc_macro2::TokenStream; 21 | use quote::ToTokens; 22 | use quote::quote; 23 | use syn::Attribute; 24 | use syn::Data; 25 | use syn::DataEnum; 26 | use syn::DataStruct; 27 | use syn::DeriveInput; 28 | use syn::Error; 29 | use syn::Expr; 30 | use syn::Field; 31 | use syn::Fields; 32 | use syn::Ident; 33 | use syn::Lit; 34 | use syn::LitStr; 35 | use syn::Member; 36 | use syn::Meta; 37 | use syn::MetaList; 38 | use syn::Path; 39 | use syn::Result; 40 | use syn::Token; 41 | use syn::Variant; 42 | use syn::parse_macro_input; 43 | use syn::parse_quote; 44 | use syn::punctuated::Punctuated; 45 | use syn::spanned::Spanned; 46 | use syn::token::Mut; 47 | 48 | #[proc_macro_derive(Traversable, attributes(traverse))] 49 | pub fn derive_traversable(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 50 | expand_with(input, |stream| impl_traversable(stream, false)) 51 | } 52 | 53 | #[proc_macro_derive(TraversableMut, attributes(traverse))] 54 | pub fn derive_traversable_mut(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 55 | expand_with(input, |stream| impl_traversable(stream, true)) 56 | } 57 | 58 | fn expand_with( 59 | input: proc_macro::TokenStream, 60 | handler: impl Fn(DeriveInput) -> Result, 61 | ) -> proc_macro::TokenStream { 62 | let input = parse_macro_input!(input as DeriveInput); 63 | handler(input) 64 | .unwrap_or_else(|error| error.to_compile_error()) 65 | .into() 66 | } 67 | 68 | fn extract_meta(attrs: Vec, attr_name: &str) -> Result> { 69 | let macro_attrs = attrs 70 | .into_iter() 71 | .filter(|attr| attr.path().is_ident(attr_name)) 72 | .collect::>(); 73 | 74 | if let Some(second) = macro_attrs.get(2) { 75 | return Err(Error::new_spanned(second, "duplicate attribute")); 76 | } 77 | 78 | macro_attrs 79 | .first() 80 | .map(|attr| Ok(attr.meta.clone())) 81 | .transpose() 82 | } 83 | 84 | #[derive(Default)] 85 | struct Params(HashMap); 86 | 87 | impl Params { 88 | fn from_attrs(attrs: Vec, attr_name: &str) -> Result { 89 | Ok(extract_meta(attrs, attr_name)? 90 | .map(|meta| { 91 | if let Meta::List(meta_list) = meta { 92 | Self::from_meta_list(meta_list) 93 | } else { 94 | Err(Error::new_spanned(meta, "invalid attribute")) 95 | } 96 | }) 97 | .transpose()? 98 | .unwrap_or_default()) 99 | } 100 | 101 | fn from_meta_list(meta_list: MetaList) -> Result { 102 | let mut params = HashMap::new(); 103 | let nested = meta_list.parse_args_with(Punctuated::::parse_terminated)?; 104 | for meta in nested { 105 | let path = meta.path(); 106 | let entry = params.entry(path.clone()); 107 | if matches!(entry, Entry::Occupied(_)) { 108 | return Err(Error::new_spanned(path, "duplicate parameter")); 109 | } 110 | entry.or_insert(meta); 111 | } 112 | Ok(Self(params)) 113 | } 114 | 115 | fn validate(&self, allowed_params: &[&str]) -> Result<()> { 116 | for path in self.0.keys() { 117 | if !allowed_params 118 | .iter() 119 | .any(|allowed_param| path.is_ident(allowed_param)) 120 | { 121 | return Err(Error::new_spanned( 122 | path, 123 | format!( 124 | "unknown parameter, supported: {}", 125 | allowed_params.join(", ") 126 | ), 127 | )); 128 | } 129 | } 130 | Ok(()) 131 | } 132 | 133 | fn param(&mut self, name: &str) -> Result> { 134 | self.0 135 | .remove(&Ident::new(name, Span::call_site()).into()) 136 | .map(Param::from_meta) 137 | .transpose() 138 | } 139 | } 140 | 141 | impl Iterator for Params { 142 | type Item = Result; 143 | fn next(&mut self) -> Option { 144 | self.0 145 | .keys() 146 | .next() 147 | .cloned() 148 | .map(|path| Param::from_meta(self.0.remove(&path).unwrap())) 149 | } 150 | } 151 | 152 | enum Param { 153 | Unit(Span), 154 | StringLiteral(Span, LitStr), 155 | NestedParams(Span), 156 | } 157 | 158 | impl Param { 159 | fn from_meta(meta: Meta) -> Result { 160 | let span = meta.span(); 161 | match meta { 162 | Meta::Path(_) => Ok(Param::Unit(span)), 163 | Meta::List(_) => Ok(Param::NestedParams(span)), 164 | Meta::NameValue(name_value) => { 165 | if let Expr::Lit(expr_lit) = &name_value.value { 166 | if let Lit::Str(lit_str) = &expr_lit.lit { 167 | Ok(Param::StringLiteral(span, lit_str.clone())) 168 | } else { 169 | Err(Error::new_spanned(name_value, "invalid parameter")) 170 | } 171 | } else { 172 | Err(Error::new_spanned(name_value, "invalid parameter")) 173 | } 174 | } 175 | } 176 | } 177 | 178 | fn span(&self) -> Span { 179 | match self { 180 | Self::Unit(span) | Self::StringLiteral(span, _) | Self::NestedParams(span) => *span, 181 | } 182 | } 183 | 184 | fn unit(self) -> Result<()> { 185 | if let Self::Unit(_) = self { 186 | Ok(()) 187 | } else { 188 | Err(Error::new(self.span(), "invalid parameter")) 189 | } 190 | } 191 | 192 | fn string_literal(self) -> Result { 193 | if let Self::StringLiteral(_, lit_str) = self { 194 | Ok(lit_str) 195 | } else { 196 | Err(Error::new(self.span(), "invalid parameter")) 197 | } 198 | } 199 | } 200 | 201 | #[inline(always)] 202 | fn resolve_crate_name() -> Path { 203 | parse_quote!(::traversable) 204 | } 205 | 206 | fn impl_traversable(input: DeriveInput, mutable: bool) -> Result { 207 | let mut params = Params::from_attrs(input.attrs, "traverse")?; 208 | params.validate(&["skip"])?; 209 | 210 | let skip_visit_self = params 211 | .param("skip")? 212 | .map(Param::unit) 213 | .transpose()? 214 | .is_some(); 215 | 216 | let name = input.ident; 217 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 218 | 219 | let visitor = Ident::new( 220 | if mutable { "VisitorMut" } else { "Visitor" }, 221 | Span::call_site(), 222 | ); 223 | 224 | let enter_method = Ident::new( 225 | if mutable { "enter_mut" } else { "enter" }, 226 | Span::call_site(), 227 | ); 228 | 229 | let leave_method = Ident::new( 230 | if mutable { "leave_mut" } else { "leave" }, 231 | Span::call_site(), 232 | ); 233 | 234 | let crate_name = resolve_crate_name(); 235 | 236 | let enter_self = if skip_visit_self { 237 | None 238 | } else { 239 | Some(quote! { 240 | #crate_name::#visitor::#enter_method(visitor, self)?; 241 | }) 242 | }; 243 | 244 | let leave_self = if skip_visit_self { 245 | None 246 | } else { 247 | Some(quote! { 248 | #crate_name::#visitor::#leave_method(visitor, self)?; 249 | }) 250 | }; 251 | 252 | let traverse_fields = match input.data { 253 | Data::Struct(struct_) => traverse_struct(struct_, mutable), 254 | Data::Enum(enum_) => traverse_enum(enum_, mutable), 255 | Data::Union(union_) => { 256 | return Err(Error::new_spanned( 257 | union_.union_token, 258 | "unions are not supported", 259 | )); 260 | } 261 | }?; 262 | 263 | let impl_trait = Ident::new( 264 | if mutable { 265 | "TraversableMut" 266 | } else { 267 | "Traversable" 268 | }, 269 | Span::call_site(), 270 | ); 271 | 272 | let method = Ident::new( 273 | if mutable { "traverse_mut" } else { "traverse" }, 274 | Span::call_site(), 275 | ); 276 | 277 | let mut_modifier = if mutable { 278 | Some(Mut(Span::call_site())) 279 | } else { 280 | None 281 | }; 282 | 283 | Ok(quote! { 284 | impl #impl_generics #crate_name::#impl_trait for #name #ty_generics #where_clause { 285 | fn #method( 286 | & #mut_modifier self, 287 | visitor: &mut V 288 | ) -> ::core::ops::ControlFlow { 289 | #enter_self 290 | #traverse_fields 291 | #leave_self 292 | ::core::ops::ControlFlow::Continue(()) 293 | } 294 | } 295 | }) 296 | } 297 | 298 | fn traverse_struct(s: DataStruct, mutable: bool) -> Result { 299 | s.fields 300 | .into_iter() 301 | .enumerate() 302 | .map(|(index, field)| { 303 | let member = field.ident.as_ref().map_or_else( 304 | || Member::Unnamed(index.into()), 305 | |ident| Member::Named(ident.clone()), 306 | ); 307 | let mut_modifier = if mutable { 308 | Some(Mut(Span::call_site())) 309 | } else { 310 | None 311 | }; 312 | traverse_field("e! { & #mut_modifier self.#member }, field, mutable) 313 | }) 314 | .collect() 315 | } 316 | 317 | fn traverse_enum(e: DataEnum, mutable: bool) -> Result { 318 | let variants = e 319 | .variants 320 | .into_iter() 321 | .map(|x| traverse_variant(x, mutable)) 322 | .collect::>()?; 323 | Ok(quote! { 324 | match self { 325 | #variants 326 | _ => {} 327 | } 328 | }) 329 | } 330 | 331 | fn traverse_variant(v: Variant, mutable: bool) -> Result { 332 | let mut params = Params::from_attrs(v.attrs, "traverse")?; 333 | params.validate(&["skip"])?; 334 | if params.param("skip")?.map(Param::unit).is_some() { 335 | return Ok(TokenStream::new()); 336 | } 337 | let name = v.ident; 338 | let destructuring = destructure_fields(v.fields.clone())?; 339 | let fields = v 340 | .fields 341 | .into_iter() 342 | .enumerate() 343 | .map(|(index, field)| { 344 | traverse_field( 345 | &field 346 | .ident 347 | .clone() 348 | .unwrap_or_else(|| Ident::new(&format!("i{}", index), Span::call_site())) 349 | .to_token_stream(), 350 | field, 351 | mutable, 352 | ) 353 | }) 354 | .collect::>()?; 355 | Ok(quote! { 356 | Self::#name #destructuring => { 357 | #fields 358 | } 359 | }) 360 | } 361 | 362 | fn destructure_fields(fields: Fields) -> Result { 363 | Ok(match fields { 364 | Fields::Named(fields) => { 365 | let field_list = fields 366 | .named 367 | .into_iter() 368 | .map(|field| { 369 | let mut params = Params::from_attrs(field.attrs, "traverse")?; 370 | let field_name = field.ident.unwrap(); 371 | Ok(if params.param("skip")?.map(Param::unit).is_some() { 372 | quote! { #field_name: _ } 373 | } else { 374 | field_name.into_token_stream() 375 | }) 376 | }) 377 | .collect::>>()?; 378 | quote! { 379 | { #( #field_list ),* } 380 | } 381 | } 382 | Fields::Unnamed(fields) => { 383 | let field_list = fields 384 | .unnamed 385 | .into_iter() 386 | .enumerate() 387 | .map(|(index, field)| { 388 | let mut params = Params::from_attrs(field.attrs, "traverse")?; 389 | Ok(if params.param("skip")?.map(Param::unit).is_some() { 390 | quote! { _ } 391 | } else { 392 | Ident::new(&format!("i{index}",), Span::call_site()).into_token_stream() 393 | }) 394 | }) 395 | .collect::>>()?; 396 | quote! { 397 | ( #( #field_list ),* ) 398 | } 399 | } 400 | Fields::Unit => TokenStream::new(), 401 | }) 402 | } 403 | 404 | fn traverse_field(value: &TokenStream, field: Field, mutable: bool) -> Result { 405 | let mut params = Params::from_attrs(field.attrs, "traverse")?; 406 | params.validate(&["skip", "with"])?; 407 | 408 | if params.param("skip")?.map(Param::unit).is_some() { 409 | return Ok(TokenStream::new()); 410 | } 411 | 412 | let crate_name = resolve_crate_name(); 413 | 414 | match params.param("with")? { 415 | None => Ok(if mutable { 416 | quote! { #crate_name::TraversableMut::traverse_mut(#value, visitor)?; } 417 | } else { 418 | quote! { #crate_name::Traversable::traverse(#value, visitor)?; } 419 | }), 420 | Some(traverse_fn) => { 421 | let traverse_fn = traverse_fn.string_literal()?.parse::()?; 422 | Ok(quote! { 423 | #traverse_fn(#value, visitor)?; 424 | }) 425 | } 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /traversable/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2025 FastLabs Developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! # Traversable 16 | //! 17 | //! A visitor pattern implementation for traversing data structures. 18 | //! 19 | //! This crate provides [`Traversable`] and [`TraversableMut`] traits for types that can be 20 | //! traversed, as well as [`Visitor`] and [`VisitorMut`] traits for types that perform the 21 | //! traversal. 22 | //! 23 | //! It is designed to be flexible and efficient, allowing for deep traversal of complex data 24 | //! structures. 25 | //! 26 | //! ## Quick Start 27 | //! 28 | //! Add `traversable` to your `Cargo.toml` with the `derive` feature: 29 | //! 30 | //! ```toml 31 | //! [dependencies] 32 | //! traversable = { version = "0.2", features = ["derive", "std"] } 33 | //! ``` 34 | //! 35 | //! Define your data structures and derive [`Traversable`]: 36 | //! 37 | //! ```rust 38 | //! # #[cfg(not(all(feature = "derive", feature = "std")))] 39 | //! # fn main() {} 40 | //! # 41 | //! # #[cfg(all(feature = "derive", feature = "std"))] 42 | //! # fn main() { 43 | //! use std::any::Any; 44 | //! use std::ops::ControlFlow; 45 | //! 46 | //! use traversable::Traversable; 47 | //! use traversable::Visitor; 48 | //! 49 | //! #[derive(Traversable)] 50 | //! struct Directory { 51 | //! name: String, 52 | //! files: Vec, 53 | //! #[traverse(skip)] 54 | //! cache_id: u64, 55 | //! } 56 | //! 57 | //! #[derive(Traversable)] 58 | //! struct File { 59 | //! name: String, 60 | //! size: u64, 61 | //! } 62 | //! 63 | //! struct FileCounter { 64 | //! count: usize, 65 | //! total_size: u64, 66 | //! } 67 | //! 68 | //! impl Visitor for FileCounter { 69 | //! type Break = (); 70 | //! 71 | //! fn enter(&mut self, node: &dyn Any) -> ControlFlow { 72 | //! if let Some(file) = node.downcast_ref::() { 73 | //! self.count += 1; 74 | //! self.total_size += file.size; 75 | //! } 76 | //! ControlFlow::Continue(()) 77 | //! } 78 | //! } 79 | //! 80 | //! let root = Directory { 81 | //! name: "root".to_string(), 82 | //! files: vec![ 83 | //! File { 84 | //! name: "a.txt".to_string(), 85 | //! size: 100, 86 | //! }, 87 | //! File { 88 | //! name: "b.rs".to_string(), 89 | //! size: 200, 90 | //! }, 91 | //! ], 92 | //! cache_id: 12345, 93 | //! }; 94 | //! 95 | //! let mut counter = FileCounter { 96 | //! count: 0, 97 | //! total_size: 0, 98 | //! }; 99 | //! root.traverse(&mut counter); 100 | //! 101 | //! assert_eq!(counter.count, 2); 102 | //! assert_eq!(counter.total_size, 300); 103 | //! # } 104 | //! ``` 105 | //! 106 | //! ## Attributes 107 | //! 108 | //! The derive macro supports the following attributes on fields and variants: 109 | //! 110 | //! * `#[traverse(skip)]`: Skips traversing into the annotated field or variant. 111 | //! * `#[traverse(with = "function_name")]`: Uses a custom function to traverse the field. 112 | //! 113 | //! ## Features 114 | //! 115 | //! * `derive`: Enables procedural macros `#[derive(Traversable)]` and `#[derive(TraversableMut)]`. 116 | //! * `std`: Enables support for standard library types (e.g., `Vec`, `HashMap`, `Box`). 117 | //! * `traverse-trivial`: Enables traversal for primitive types (`u8`, `i32`, `bool`, etc.). By 118 | //! default, these are ignored. 119 | //! * `traverse-std`: Enables traversal for "primary" std types like `String`. By default, these are 120 | //! ignored. Note that container types like `Vec` are always traversed if the `std` feature is 121 | //! enabled. 122 | 123 | #![cfg_attr(docsrs, feature(doc_cfg))] 124 | #![deny(missing_docs)] 125 | #![no_std] 126 | 127 | #[cfg(feature = "std")] 128 | extern crate std; 129 | 130 | use core::ops::ControlFlow; 131 | 132 | #[cfg(feature = "derive")] 133 | /// See [`Traversable`]. 134 | pub use traversable_derive::Traversable; 135 | #[cfg(feature = "derive")] 136 | /// See [`TraversableMut`]. 137 | pub use traversable_derive::TraversableMut; 138 | 139 | pub mod combinator; 140 | pub mod function; 141 | 142 | /// Implementations for third-party library types. 143 | mod impls; 144 | 145 | /// A visitor that can be used to traverse a data structure. 146 | /// 147 | /// Implement this trait to define custom logic that executes when 148 | /// [`Traversable`] items are visited. You can implement `enter` and `leave` 149 | /// methods to perform actions before and after processing a node, respectively. 150 | /// 151 | /// For an example of implementing `Visitor`, see the `FileCounter` struct 152 | /// in the [crate-level documentation](self). 153 | /// 154 | /// You can also use [`visitor`] to create a visitor from closures. 155 | /// 156 | /// [`visitor`]: function::visitor 157 | pub trait Visitor { 158 | /// The type that can be used to break traversal early. 159 | type Break; 160 | 161 | /// Called when the visitor is entering a node. 162 | /// 163 | /// Default implementation does nothing and continues traversal. 164 | fn enter(&mut self, this: &dyn core::any::Any) -> ControlFlow { 165 | let _ = this; 166 | ControlFlow::Continue(()) 167 | } 168 | 169 | /// Called when the visitor is leaving a node. 170 | /// 171 | /// Default implementation does nothing and continues traversal. 172 | fn leave(&mut self, this: &dyn core::any::Any) -> ControlFlow { 173 | let _ = this; 174 | ControlFlow::Continue(()) 175 | } 176 | } 177 | 178 | /// A visitor that can be used to traverse a mutable data structure. 179 | /// 180 | /// Implement this trait to define custom logic that executes when 181 | /// [`TraversableMut`] items are visited. You can implement `enter_mut` and `leave_mut` 182 | /// methods to perform actions before and after processing a mutable node, respectively. 183 | /// 184 | /// # Example 185 | /// 186 | /// ```rust 187 | /// # #[cfg(not(feature = "derive"))] 188 | /// # fn main() {} 189 | /// # 190 | /// # #[cfg(feature = "derive")] 191 | /// # fn main() { 192 | /// use core::any::Any; 193 | /// use core::ops::ControlFlow; 194 | /// 195 | /// use traversable::TraversableMut; 196 | /// use traversable::VisitorMut; 197 | /// #[derive(TraversableMut)] 198 | /// struct Node { 199 | /// value: i32, 200 | /// #[traverse(skip)] 201 | /// id: u32, 202 | /// } 203 | /// 204 | /// struct Incrementer; 205 | /// 206 | /// impl VisitorMut for Incrementer { 207 | /// type Break = (); 208 | /// 209 | /// fn enter_mut(&mut self, node: &mut dyn Any) -> ControlFlow { 210 | /// if let Some(n) = node.downcast_mut::() { 211 | /// n.value += 1; 212 | /// } 213 | /// ControlFlow::Continue(()) 214 | /// } 215 | /// } 216 | /// 217 | /// let mut node = Node { value: 10, id: 1 }; 218 | /// node.traverse_mut(&mut Incrementer); 219 | /// assert_eq!(node.value, 11); 220 | /// # } 221 | /// ``` 222 | /// 223 | /// You can also use [`visitor_mut`] to create a mutable visitor from closures. 224 | /// 225 | /// [`visitor_mut`]: function::visitor_mut 226 | pub trait VisitorMut { 227 | /// The type that can be used to break traversal early. 228 | type Break; 229 | 230 | /// Called when the visitor is entering a mutable node. 231 | /// 232 | /// Default implementation does nothing and continues traversal. 233 | fn enter_mut(&mut self, this: &mut dyn core::any::Any) -> ControlFlow { 234 | let _ = this; 235 | ControlFlow::Continue(()) 236 | } 237 | 238 | /// Called when the visitor is leaving a mutable node. 239 | /// 240 | /// Default implementation does nothing and continues traversal. 241 | fn leave_mut(&mut self, this: &mut dyn core::any::Any) -> ControlFlow { 242 | let _ = this; 243 | ControlFlow::Continue(()) 244 | } 245 | } 246 | 247 | /// A trait for types that can be traversed by a visitor. 248 | /// 249 | /// This trait is the core of the traversable pattern. It allows a [`Visitor`] to 250 | /// walk through a data structure. 251 | /// 252 | /// # Deriving `Traversable` 253 | /// 254 | /// The easiest way to implement `Traversable` is to use the `derive` macro. 255 | /// 256 | /// ```rust 257 | /// # #[cfg(not(feature = "derive"))] 258 | /// # fn main() {} 259 | /// # 260 | /// # #[cfg(feature = "derive")] 261 | /// # fn main() { 262 | /// use traversable::Traversable; 263 | /// 264 | /// #[derive(Traversable)] 265 | /// struct MyStruct { 266 | /// data: u64, 267 | /// #[traverse(skip)] 268 | /// hidden: String, 269 | /// } 270 | /// # } 271 | /// ``` 272 | /// 273 | /// # Attributes 274 | /// 275 | /// The derive macro supports the following attributes: 276 | /// 277 | /// * `#[traverse(skip)]`: Skips traversing into the annotated field or variant. 278 | /// * `#[traverse(with = "function_name")]`: Uses a custom function to traverse the field. 279 | /// 280 | /// ## Custom Traversal Function 281 | /// 282 | /// When using `#[traverse(with = "path::to::func")]`, the function must have the signature: 283 | /// 284 | /// ```rust,ignore 285 | /// fn func(item: &ItemType, visitor: &mut V) -> ControlFlow 286 | /// ``` 287 | /// 288 | /// Example: 289 | /// 290 | /// ```rust 291 | /// # #[cfg(not(feature = "derive"))] 292 | /// # fn main() {} 293 | /// # 294 | /// # #[cfg(feature = "derive")] 295 | /// # fn main() { 296 | /// use core::ops::ControlFlow; 297 | /// 298 | /// use traversable::Traversable; 299 | /// use traversable::Visitor; 300 | /// 301 | /// fn traverse_string_len(s: &String, visitor: &mut V) -> ControlFlow { 302 | /// s.len().traverse(visitor) 303 | /// } 304 | /// 305 | /// #[derive(Traversable)] 306 | /// struct User { 307 | /// #[traverse(with = "traverse_string_len")] 308 | /// name: String, 309 | /// } 310 | /// # } 311 | /// ``` 312 | pub trait Traversable: core::any::Any { 313 | /// Traverse the data structure with the given visitor. 314 | fn traverse(&self, visitor: &mut V) -> ControlFlow; 315 | } 316 | 317 | /// A trait for types that can be traversed mutably by a visitor. 318 | /// 319 | /// This trait allows a [`VisitorMut`] to walk through a data structure and possibly 320 | /// mutate it. 321 | /// 322 | /// # Deriving `TraversableMut` 323 | /// 324 | /// The easiest way to implement `TraversableMut` is to use the `derive` macro. 325 | /// 326 | /// ```rust 327 | /// # #[cfg(not(feature = "derive"))] 328 | /// # fn main() {} 329 | /// # 330 | /// # #[cfg(feature = "derive")] 331 | /// # fn main() { 332 | /// use traversable::TraversableMut; 333 | /// 334 | /// #[derive(TraversableMut)] 335 | /// struct MyStruct { 336 | /// data: u64, 337 | /// #[traverse(skip)] 338 | /// readonly: String, 339 | /// } 340 | /// # } 341 | /// ``` 342 | /// 343 | /// # Attributes 344 | /// 345 | /// The derive macro supports the following attributes: 346 | /// 347 | /// * `#[traverse(skip)]`: Skips traversing into the annotated field or variant. 348 | /// * `#[traverse(with = "function_name")]`: Uses a custom function to traverse the field. 349 | /// 350 | /// ## Custom Traversal Function 351 | /// 352 | /// When using `#[traverse(with = "path::to::func")]`, the function must have the signature: 353 | /// 354 | /// ```rust,ignore 355 | /// fn func(item: &mut ItemType, visitor: &mut V) -> ControlFlow 356 | /// ``` 357 | /// 358 | /// Example: 359 | /// 360 | /// ```rust 361 | /// # #[cfg(not(feature = "derive"))] 362 | /// # fn main() {} 363 | /// # 364 | /// # #[cfg(feature = "derive")] 365 | /// # fn main() { 366 | /// use core::ops::ControlFlow; 367 | /// 368 | /// use traversable::TraversableMut; 369 | /// use traversable::VisitorMut; 370 | /// 371 | /// fn traverse_string_chars( 372 | /// s: &mut String, 373 | /// visitor: &mut V, 374 | /// ) -> ControlFlow { 375 | /// // custom traversal logic 376 | /// ControlFlow::Continue(()) 377 | /// } 378 | /// 379 | /// #[derive(TraversableMut)] 380 | /// struct User { 381 | /// #[traverse(with = "traverse_string_chars")] 382 | /// name: String, 383 | /// } 384 | /// # } 385 | /// ``` 386 | pub trait TraversableMut: core::any::Any { 387 | /// Traverse the mutable data structure with the given visitor. 388 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow; 389 | } 390 | 391 | #[allow(unused_macros)] 392 | macro_rules! blank_traverse_impl { 393 | ( $type:ty ) => { 394 | impl Traversable for $type { 395 | #[inline] 396 | fn traverse(&self, _visitor: &mut V) -> ControlFlow { 397 | ControlFlow::Continue(()) 398 | } 399 | } 400 | 401 | impl TraversableMut for $type { 402 | #[inline] 403 | fn traverse_mut(&mut self, _visitor: &mut V) -> ControlFlow { 404 | ControlFlow::Continue(()) 405 | } 406 | } 407 | }; 408 | } 409 | 410 | #[allow(unused_macros)] 411 | macro_rules! trivial_traverse_impl { 412 | ( $type:ty ) => { 413 | impl Traversable for $type { 414 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 415 | visitor.enter(self)?; 416 | visitor.leave(self)?; 417 | ControlFlow::Continue(()) 418 | } 419 | } 420 | 421 | impl TraversableMut for $type { 422 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 423 | visitor.enter_mut(self)?; 424 | visitor.leave_mut(self)?; 425 | ControlFlow::Continue(()) 426 | } 427 | } 428 | }; 429 | } 430 | 431 | mod impl_trivial { 432 | use super::*; 433 | 434 | #[cfg(not(feature = "traverse-trivial"))] 435 | macro_rules! trivial_impl { 436 | ( $type:ty ) => { 437 | blank_traverse_impl!($type); 438 | }; 439 | } 440 | 441 | #[cfg(feature = "traverse-trivial")] 442 | macro_rules! trivial_impl { 443 | ( $type:ty ) => { 444 | trivial_traverse_impl!($type); 445 | }; 446 | } 447 | 448 | trivial_impl!(()); 449 | 450 | trivial_impl!(u8); 451 | trivial_impl!(u16); 452 | trivial_impl!(u32); 453 | trivial_impl!(u64); 454 | trivial_impl!(u128); 455 | trivial_impl!(usize); 456 | 457 | trivial_impl!(i8); 458 | trivial_impl!(i16); 459 | trivial_impl!(i32); 460 | trivial_impl!(i64); 461 | trivial_impl!(i128); 462 | trivial_impl!(isize); 463 | 464 | trivial_impl!(f32); 465 | trivial_impl!(f64); 466 | 467 | trivial_impl!(char); 468 | trivial_impl!(bool); 469 | } 470 | 471 | mod impl_tuple { 472 | use super::*; 473 | 474 | macro_rules! tuple_impl { 475 | ( $( $( $type:ident ),+ => $( $field:tt ),+ )+ ) => { 476 | $( 477 | impl<$( $type ),+> Traversable for ($($type,)+) 478 | where 479 | $( 480 | $type: Traversable 481 | ),+ 482 | { 483 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 484 | $( 485 | self.$field.traverse(visitor)?; 486 | )+ 487 | ControlFlow::Continue(()) 488 | } 489 | } 490 | 491 | impl<$( $type ),+> TraversableMut for ($($type,)+) 492 | where 493 | $( 494 | $type: TraversableMut 495 | ),+ 496 | { 497 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 498 | $( 499 | self.$field.traverse_mut(visitor)?; 500 | )+ 501 | ControlFlow::Continue(()) 502 | } 503 | } 504 | )+ 505 | }; 506 | } 507 | 508 | tuple_impl! { 509 | T0 => 0 510 | T0, T1 => 0, 1 511 | T0, T1, T2 => 0, 1, 2 512 | T0, T1, T2, T3 => 0, 1, 2, 3 513 | T0, T1, T2, T3, T4 => 0, 1, 2, 3, 4 514 | T0, T1, T2, T3, T4, T5 => 0, 1, 2, 3, 4, 5 515 | T0, T1, T2, T3, T4, T5, T6 => 0, 1, 2, 3, 4, 5, 6 516 | T0, T1, T2, T3, T4, T5, T6, T7 => 0, 1, 2, 3, 4, 5, 6, 7 517 | T0, T1, T2, T3, T4, T5, T6, T7, T8 => 0, 1, 2, 3, 4, 5, 6, 7, 8 518 | T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 519 | T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10 => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 520 | T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11 => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 521 | } 522 | } 523 | 524 | #[cfg(feature = "std")] 525 | mod impl_std_primary { 526 | use std::string::String; 527 | 528 | use super::*; 529 | 530 | #[cfg(not(feature = "traverse-std"))] 531 | macro_rules! std_primary_impl { 532 | ( $type:ty ) => { 533 | blank_traverse_impl!($type); 534 | }; 535 | } 536 | 537 | #[cfg(feature = "traverse-std")] 538 | macro_rules! std_primary_impl { 539 | ( $type:ty ) => { 540 | trivial_traverse_impl!($type); 541 | }; 542 | } 543 | 544 | std_primary_impl!(String); 545 | } 546 | 547 | #[cfg(feature = "std")] 548 | mod impl_std_container { 549 | use std::boxed::Box; 550 | use std::cell::Cell; 551 | use std::sync::Arc; 552 | use std::sync::Mutex; 553 | use std::sync::RwLock; 554 | 555 | use super::*; 556 | 557 | // Helper traits to the generic `IntoIterator` Traversable impl 558 | trait DerefAndTraverse { 559 | fn deref_and_traverse(self, visitor: &mut V) -> ControlFlow; 560 | } 561 | 562 | trait DerefAndTraverseMut { 563 | fn deref_and_traverse_mut(self, visitor: &mut V) -> ControlFlow; 564 | } 565 | 566 | // Most collections iterate over item references, this is the trait impl that handles that case 567 | impl DerefAndTraverse for &T { 568 | fn deref_and_traverse(self, visitor: &mut V) -> ControlFlow { 569 | self.traverse(visitor) 570 | } 571 | } 572 | 573 | impl DerefAndTraverseMut for &mut T { 574 | fn deref_and_traverse_mut(self, visitor: &mut V) -> ControlFlow { 575 | self.traverse_mut(visitor) 576 | } 577 | } 578 | 579 | // Map-like collections iterate over item references pairs 580 | impl DerefAndTraverse for (&TK, &TV) { 581 | fn deref_and_traverse(self, visitor: &mut V) -> ControlFlow { 582 | self.0.traverse(visitor)?; 583 | self.1.traverse(visitor)?; 584 | ControlFlow::Continue(()) 585 | } 586 | } 587 | 588 | // Map-like collections have mutable iterators that allow mutating only the value, not the key 589 | impl DerefAndTraverseMut for (TK, &mut TV) { 590 | fn deref_and_traverse_mut(self, visitor: &mut V) -> ControlFlow { 591 | self.1.traverse_mut(visitor) 592 | } 593 | } 594 | 595 | // Implement Traversal for container types in standard library. 596 | macro_rules! impl_drive_for_into_iterator { 597 | ( $type:ty ; $($generics:tt)+ ) => { 598 | impl< $($generics)+ > Traversable for $type 599 | where 600 | $type: 'static, 601 | for<'a> &'a $type: IntoIterator, 602 | for<'a> <&'a $type as IntoIterator>::Item: DerefAndTraverse, 603 | { 604 | #[allow(for_loops_over_fallibles)] 605 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 606 | for item in self { 607 | item.deref_and_traverse(visitor)?; 608 | } 609 | ControlFlow::Continue(()) 610 | } 611 | } 612 | 613 | impl< $($generics)+ > TraversableMut for $type 614 | where 615 | $type: 'static, 616 | for<'a> &'a mut $type: IntoIterator, 617 | for<'a> <&'a mut $type as IntoIterator>::Item: DerefAndTraverseMut, 618 | { 619 | #[allow(for_loops_over_fallibles)] 620 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 621 | for item in self { 622 | item.deref_and_traverse_mut(visitor)?; 623 | } 624 | ControlFlow::Continue(()) 625 | } 626 | } 627 | }; 628 | } 629 | 630 | impl_drive_for_into_iterator! { [T] ; T } 631 | impl_drive_for_into_iterator! { [T; N] ; T, const N: usize } 632 | impl_drive_for_into_iterator! { std::vec::Vec ; T } 633 | impl_drive_for_into_iterator! { std::collections::BTreeSet ; T } 634 | impl_drive_for_into_iterator! { std::collections::BinaryHeap ; T } 635 | impl_drive_for_into_iterator! { std::collections::HashSet ; T } 636 | impl_drive_for_into_iterator! { std::collections::LinkedList ; T } 637 | impl_drive_for_into_iterator! { std::collections::VecDeque ; T } 638 | impl_drive_for_into_iterator! { std::collections::BTreeMap ; T, U } 639 | impl_drive_for_into_iterator! { std::collections::HashMap ; T, U } 640 | impl_drive_for_into_iterator! { Option ; T } 641 | impl_drive_for_into_iterator! { Result ; T, U } 642 | 643 | impl Traversable for Box { 644 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 645 | (**self).traverse(visitor) 646 | } 647 | } 648 | 649 | impl TraversableMut for Box { 650 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 651 | (**self).traverse_mut(visitor) 652 | } 653 | } 654 | 655 | impl Traversable for Arc { 656 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 657 | (**self).traverse(visitor) 658 | } 659 | } 660 | 661 | impl Traversable for Mutex 662 | where 663 | T: Traversable, 664 | { 665 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 666 | let lock = self.lock().unwrap(); 667 | lock.traverse(visitor) 668 | } 669 | } 670 | 671 | impl Traversable for RwLock 672 | where 673 | T: Traversable, 674 | { 675 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 676 | let lock = self.read().unwrap(); 677 | lock.traverse(visitor) 678 | } 679 | } 680 | 681 | impl TraversableMut for Arc> 682 | where 683 | T: TraversableMut, 684 | { 685 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 686 | let mut lock = self.lock().unwrap(); 687 | lock.traverse_mut(visitor) 688 | } 689 | } 690 | 691 | impl TraversableMut for Arc> 692 | where 693 | T: TraversableMut, 694 | { 695 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 696 | let mut lock = self.write().unwrap(); 697 | lock.traverse_mut(visitor) 698 | } 699 | } 700 | 701 | impl Traversable for Cell 702 | where 703 | T: Traversable + Copy, 704 | { 705 | fn traverse(&self, visitor: &mut V) -> ControlFlow { 706 | self.get().traverse(visitor) 707 | } 708 | } 709 | 710 | impl TraversableMut for Cell 711 | where 712 | T: TraversableMut, 713 | { 714 | fn traverse_mut(&mut self, visitor: &mut V) -> ControlFlow { 715 | self.get_mut().traverse_mut(visitor) 716 | } 717 | } 718 | } 719 | --------------------------------------------------------------------------------