diff --git a/README.md b/README.md index 9cfdfa223..0617cb30c 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,17 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +`rfl::cli::usage` generates the help text from the same struct, for instance for `--help`: + +```cpp +if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + // Usage: ./app -o|--output-dir= -v|--verbose[=] --count= + // + // Arguments: ... +} +``` + Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details. ### Error messages @@ -671,6 +682,7 @@ In addition, it supports the following custom containers: - `rfl::Tuple`: An alternative to `std::tuple` that compiles considerably faster. - `rfl::Validator`: Allows for automatic input validation. - `rfl::Variant`: An alternative to `std::variant` that compiles considerably faster. +- `rfl::json::Raw`: Holds a raw JSON value for passthrough serialization and deserialization (JSON only; [details](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/json/#raw-json-passthrough-rfljsonraw)). #### Custom classes @@ -752,3 +764,5 @@ reflect-cpp includes [YYJSON](https://github.com/ibireme/yyjson), the fastest JS reflect-cpp includes [compile-time-regular-expressions](https://github.com/hanickadot/compile-time-regular-expressions). CTRE is written by Hana Dusíková and released under the Apache-2.0 License with LLVM exceptions. reflect-cpp includes [enchantum](https://github.com/ZXShady/enchantum/tree/main). enchantum is written by ZXShady and also released under the MIT License. + +See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for full third-party license texts, SPDX identifiers, and CMake/feature inclusion conditions. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 000000000..d8639fbb8 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,322 @@ +# Third-Party Notices + +`reflect-cpp` itself is licensed under the MIT License (see [LICENSE](LICENSE)). + +For out-of-the-box builds (`REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, the default), +this repository vendors the third-party components listed below under +`include/rfl/thirdparty/` and `src/yyjson.c`. When all bundled dependencies are +used, the composite SPDX license expression is: + +`MIT AND Apache-2.0 WITH LLVM-exception` + +Passing `-DREFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF` disables all bundled +components in CMake, resolving `ctre` and `enchantum` unconditionally via +`find_package` and resolving `yyjson` via `find_package` only when JSON, Avro, +CBOR, or UBJSON is enabled (`CMakeLists.txt`). Note that `REFLECTCPP_INSTALL=ON` +installs the entire `include/` tree, including `include/rfl/thirdparty/`. + +## Vendored Components + +| Component | Vendored Path(s) | Version | Upstream URL | SPDX License | CMake / Feature Condition | +|---|---|---|---|---|---| +| **yyjson** | `include/rfl/thirdparty/yyjson.h`, `src/yyjson.c` | `0.12.0` | | `MIT` | Compiled only when `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON` **and** at least one of `REFLECTCPP_JSON=ON` (default), `REFLECTCPP_AVRO=ON`, `REFLECTCPP_CBOR=ON`, or `REFLECTCPP_UBJSON=ON` is enabled (`_REFLECTCPP_NEEDS_JSON_IMPL` in `CMakeLists.txt`). Not compiled when all four options are `OFF`. | +| **CTRE** (compile-time-regular-expressions) | `include/rfl/thirdparty/ctre.hpp` | `3.10.0` | | `Apache-2.0 WITH LLVM-exception` | Header-only; included by `include/rfl/PatternValidator.hpp`, which is unconditionally included by `include/rfl.hpp` (and transitively every format umbrella header `include/rfl/.hpp` and `reflectcpp`'s precompiled header). With `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, CMake adds `include/rfl/thirdparty` to `BUILD_INTERFACE` include directories so `__has_include()` resolves to the bundled header; installed/non-CMake builds fall back to `thirdparty/ctre.hpp` when no external `` is on the include path. | +| **enchantum** | `include/rfl/thirdparty/enchantum/` | Vendored from upstream `main` in reflect-cpp PR #441 (`750e67d6`, 2025-05-30; minor unused-include cleanup in PR #519 / `732e9fe8`; no embedded version macro; external installs require `>= 0.5.0` in `vcpkg.json`) | | `MIT` | Header-only; included by `include/rfl/internal/enums/cpp20/enchantum.hpp` for C++20 enum reflection when `REFLECTCPP_USE_CPP26_REFLECTION=OFF` (default). With `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=ON`, CMake adds `include/rfl/thirdparty` to `BUILD_INTERFACE` include directories so `__has_include()` resolves to the bundled copy (installed/non-CMake builds fall back to `thirdparty/enchantum/enchantum.hpp` when no external copy is on the include path). Not included by C++ headers when `REFLECTCPP_USE_CPP26_REFLECTION=ON` (CMake still runs `find_package(enchantum)` if `REFLECTCPP_USE_BUNDLED_DEPENDENCIES=OFF`). | + +--- + +## yyjson + +- **Upstream:** +- **Author:** YaoYuan +- **Version:** `0.12.0` (`YYJSON_VERSION_STRING` in `include/rfl/thirdparty/yyjson.h`) +- **SPDX License:** `MIT` +- **Source of notice:** Verbatim from `include/rfl/thirdparty/yyjson.h` and `src/yyjson.c` + +```text + Copyright (c) 2020 YaoYuan + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +``` + +--- + +## CTRE (compile-time-regular-expressions) + +- **Upstream:** +- **Author:** Hana Dusíková +- **Version:** `3.10.0` +- **SPDX License:** `Apache-2.0 WITH LLVM-exception` +- **Source of notice:** Verbatim from `include/rfl/thirdparty/ctre.hpp` + +```text + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. +``` + +--- + +## enchantum + +- **Upstream:** +- **Author:** ZXShady +- **SPDX License:** `MIT` +- **Source of notice:** Verbatim from upstream + (the 22 vendored header files under `include/rfl/thirdparty/enchantum/` do + not carry inline copyright or license headers). + +```text +MIT License + +Copyright (c) 2025 ZXShady + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/docs/content/enums.md b/docs/content/enums.md index 5ab5561af..4d972f20a 100644 --- a/docs/content/enums.md +++ b/docs/content/enums.md @@ -215,3 +215,26 @@ constexpr auto enumerator_array = rfl::get_enumerator_array(); In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, there is also `rfl::get_underlying_enumerators()` and `rfl::get_underlying_enumerator_array()`. + +## Custom wire names (`rfl::EnumNames` and `rfl::TransformEnumNames`) + +To customize serialized enum wire names across JSON, CLI, Generic, XML, YAML, and JSON Schema without duplicating enumerators as `rfl::Literal<...>`, specialize `rfl::EnumNames` and/or pass a `rfl::TransformEnumNames<...>` processor (`rfl::EnumSnakeCaseToKebabCase`, `rfl::EnumSnakeCaseToCamelCase`, `rfl::EnumSnakeCaseToPascalCase`, `rfl::EnumCamelCaseToSnakeCase`, `rfl::EnumToLowerCase`, `rfl::EnumToUpperCase`): + +```cpp +enum class OptimizationLevel { no_opt, size_opt, speed_opt, cxx_standard }; + +template <> +struct rfl::EnumNames { + static constexpr rfl::EnumNameTransform transform = + rfl::EnumNameTransform::snake_to_kebab; + static constexpr std::array, 1> + overrides = {{ + {OptimizationLevel::cxx_standard, "c++20"}, + }}; +}; +``` + +- `overrides` (either a static contiguous range or a static `overrides()` returning a borrowed contiguous range such as `std::span>`) takes precedence over `transform`, and also supports enumerators outside the default reflected range. +- `transform` can be either a `rfl::EnumNameTransform` constant or a static callable `transform(std::string_view)` returning `std::string` or `std::string_view`. +- If `rfl::EnumNames` only defines `overrides` (without `transform`), non-overridden enumerators still receive any `rfl::TransformEnumNames<...>` processor passed to `read`, `write`, or `to_schema`. +- Use `rfl::get_enum_wire_names()` to inspect resolved `(wire_name, enumerator)` pairs. diff --git a/docs/content/json_schema.md b/docs/content/json_schema.md index ad97d630b..21f3f034b 100644 --- a/docs/content/json_schema.md +++ b/docs/content/json_schema.md @@ -74,6 +74,31 @@ This will result in the following JSON schema: You can insert this into the tools mentioned above and see the generated code. +## Variants and tagged unions + +`rfl::TaggedUnion` becomes `oneOf`: every alternative has a different tag, so a value +matches exactly one of them. + +`rfl::Variant` and `std::variant` become `anyOf`, because their alternatives can overlap: +`1` is both an `integer` and a `number`, and `{"width": 1, "height": 2}` matches both +`Square` and `Rectangle` from the example in [variants](../variants_and_tagged_unions). +`oneOf` would reject such values, even though reflect-cpp reads them without problems. + +If you know that the alternatives of your variants never overlap, you can pass +`rfl::VariantsAsOneOf` to get `oneOf` for `rfl::Variant` and `std::variant` as well: + +```cpp +const std::string json_schema = + rfl::json::to_schema, rfl::VariantsAsOneOf>(); +``` + +Warning: `oneOf` rejects values that match more than one alternative, so with this +processor the schema rejects `1` for `rfl::Variant`. Structs can overlap +as well, for instance when additional properties are allowed (see `rfl::NoExtraFields`). + +`std::optional` and `rfl::Generic` stay `anyOf` either way. `std::optional` is not +a variant, and the alternatives of `rfl::Generic` overlap (`1` is both an `integer` and a `number`). + ## Adding descriptions JSON schemata also often contain descriptions. reflect-cpp supports this as well. diff --git a/docs/content/processors.md b/docs/content/processors.md index a431bb4e6..366043c02 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -45,6 +45,7 @@ reflect-cpp currently supports the following processors: - `rfl::NoFieldNames` - `rfl::NoOptionals` - `rfl::UnderlyingEnums` +- `rfl::VariantsAsOneOf` - `rfl::SnakeCaseToCamelCase` - `rfl::SnakeCaseToPascalCase` @@ -492,6 +493,19 @@ The resulting JSON string looks like this: {"radius":2.0,"color":1} ``` +### `rfl::VariantsAsOneOf` + +By default, the JSON schema describes `rfl::Variant` and `std::variant` as `anyOf`. +By passing the processor `rfl::VariantsAsOneOf` to `rfl::json::to_schema`, they +become `oneOf`: + +```cpp +rfl::json::to_schema, rfl::VariantsAsOneOf>(); +``` + +It only changes the schema, not reading or writing. Please refer to +the [JSON schema documentation](../json_schema) for details. + ### `rfl::SnakeCaseToCamelCase` Please refer to the example above. @@ -549,6 +563,42 @@ The resulting JSON string looks like this: {"type":"Person","firstName":"Homer","lastName":"Simpson","age":45} ``` +## `rfl::TransformEnumNames` (`EnumSnakeCaseToKebabCase`, etc.) + +Applies a whole-enum wire-name casing transform to enum fields during reading, +writing, and JSON Schema generation. Resolved wire-name tables are cached once +per `(EnumType, EnumNameTransform)` pair. + +Built-in aliases: +- `rfl::EnumSnakeCaseToKebabCase` +- `rfl::EnumSnakeCaseToCamelCase` +- `rfl::EnumSnakeCaseToPascalCase` +- `rfl::EnumCamelCaseToSnakeCase` +- `rfl::EnumToLowerCase` +- `rfl::EnumToUpperCase` + +```cpp +enum class CostModel { t_count, two_qubit_gate_count, gate_count }; +struct Config { CostModel cost_model; }; + +const auto json_str = rfl::json::write( + Config{.cost_model = CostModel::two_qubit_gate_count}); +// {"cost_model":"two-qubit-gate-count"} +``` + +## `rfl::IntegerBounds` + +Opt-in schema processor that emits C++ integer width `minimum` and `maximum` +keywords in JSON Schema for signed and unsigned integer types (`int8_t`–`int64_t`, +`uint8_t`–`uint64_t`, etc.), excluding `bool`, character types (`char`, `wchar_t`, +`char8_t`, `char16_t`, `char32_t`), and `rfl::UnderlyingEnums`. + +```cpp +struct NetConfig { uint16_t port; }; +const auto schema = rfl::json::to_schema(); +// "port": {"type":"integer","minimum":0,"maximum":65535} +``` + ## Writing your own processors In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called `process` taking a named tuple as an input and then returning a modified named tuple. The `process` method should accept the type of the original struct as a template parameter. diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 00b4002cc..433cecb03 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -195,6 +195,80 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +## Usage / help + +`rfl::cli::usage(program_name, detailed = false)` generates the +help text from the same struct, and with the same processors, as +`rfl::cli::read()`. So the names always match what the parser +accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths. +It returns an `rfl::Result`. + +```cpp +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional> + input_file; + rfl::Short<"p", rfl::Description<"Port to listen on", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", std::vector> tags; + Database database; +}; +``` + +`rfl::cli::usage("app", true).value()` is the usage line, where +optional arguments are in brackets, and one line per argument, with its +description and whether it is required. `rfl::cli::usage("app")` +gives only the usage line. + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Required. + --database.host= Required. + --database.port= Required. +``` + +Fields wrapped in `rfl::DefaultVal` are optional, and so are all fields if you +pass `rfl::DefaultIfMissing` (to both `read` and `usage`). The parser takes +the defaults of `rfl::DefaultVal` fields from a default-constructed struct. If +a struct with `rfl::DefaultVal` cannot be default-constructed (for instance +because a validator rejects another field's default value), it cannot be read, +and `usage` returns the error, as it does for two fields with the same short +name. + +Each argument is shown as the option table that `read` parses with (see +[Architecture](#architecture)) reads it: a `bool`, also inside a nested +struct, is a flag whose value can be left out (`--verbose[=]`), and +every other option takes a value (`--port=`). + +`rfl::Positional` and `rfl::Short` are found through the other wrappers, as +the parser does (see [Combining wrappers](#combining-wrappers)), so +`rfl::Description<"...", rfl::Positional>` is listed as a +positional argument. + +`read` does not handle `--help`: check `argv` for it and print `usage` +yourself: + +```cpp +int main(int argc, char* argv[]) { + if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + return 0; + } + const auto config = rfl::cli::read(argc, argv).value(); +} +``` + ## Supported types | Type | CLI format | Notes | @@ -239,6 +313,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` - `include/rfl/cli/options.hpp` — the internal option table: the long, short and positional options of a struct - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` +- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` and the internal option table - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor - `include/rfl/Positional.hpp` — `Positional` wrapper diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..b1bd26bdc 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -78,6 +78,60 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::json::write(person, std::cout) << std::endl; ``` +## Read and write flags + +`rfl::json` provides `inline constexpr` flag constants (combinable with `|`) so you do not need to reference underlying `YYJSON_*` constants directly. + +### Read flags (`rfl::json::read` and `rfl::json::load`) + +| Flag | Description | +| --- | --- | +| `rfl::json::allow_comments` | Allow C-style single-line (`//`) and multi-line (`/* */`) comments | +| `rfl::json::allow_trailing_commas` | Allow a single trailing comma at the end of an object or array | +| `rfl::json::jsonc` | Shorthand for `allow_comments \| allow_trailing_commas` (JSONC) | +| `rfl::json::allow_bom` | Allow and skip a leading UTF-8 BOM *(requires yyjson >= 0.11.0)* | +| `rfl::json::stop_when_done` | Stop after the first JSON value and ignore trailing content | +| `rfl::json::read_allow_inf_and_nan` | Allow `Inf`, `Infinity`, and `NaN` numbers and literals | +| `rfl::json::read_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences in string values | +| `rfl::json::allow_ext_number` | Allow hex numbers, leading/trailing decimal points, and leading `+` *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_escape` | Allow extended string escape sequences *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_whitespace` | Allow extended whitespace characters *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_single_quoted_str` | Allow single-quoted strings *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_unquoted_key` | Allow unquoted object keys *(requires yyjson >= 0.12.0)* | +| `rfl::json::json5` | Allow JSON5 syntax *(requires yyjson >= 0.12.0)* | + +Example reading JSONC: + +```cpp +const auto result = rfl::json::read( + jsonc_string, rfl::json::allow_comments | rfl::json::allow_trailing_commas); + +// Or using the convenience alias: +const auto result2 = rfl::json::read(jsonc_string, rfl::json::jsonc); +``` + +### Write flags (`rfl::json::write`, `rfl::json::save`, and `rfl::json::to_schema`) + +| Flag | Description | +| --- | --- | +| `rfl::json::pretty` | Pretty-print with 4-space indentation | +| `rfl::json::pretty_two_spaces` | Pretty-print with 2-space indentation (overrides `pretty`) *(requires yyjson >= 0.7.0)* | +| `rfl::json::newline_at_end` | Append a trailing `\n` to the output *(requires yyjson >= 0.9.0)* | +| `rfl::json::escape_unicode` | Escape non-ASCII characters as `\uXXXX` for ASCII-only output | +| `rfl::json::escape_slashes` | Escape `/` as `\/` | +| `rfl::json::write_allow_inf_and_nan` | Write `Inf`/`NaN` as `Infinity`/`NaN` literals (non-standard) | +| `rfl::json::inf_and_nan_as_null` | Write `Inf`/`NaN` as `null` (overrides `write_allow_inf_and_nan`) | +| `rfl::json::write_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences when encoding strings | + +Example combining write flags: + +```cpp +const std::string json_string = rfl::json::write( + person, rfl::json::pretty_two_spaces | rfl::json::newline_at_end); +``` + +> Note: `read_allow_inf_and_nan` / `write_allow_inf_and_nan` and `read_allow_invalid_unicode` / `write_allow_invalid_unicode` are prefixed with `read_` / `write_` because the underlying read and write flag bit values differ. Low-level/unsafe read flags (`YYJSON_READ_INSITU`, `YYJSON_READ_NUMBER_AS_RAW`, `YYJSON_READ_BIGNUM_AS_RAW`) are intentionally not exposed as `rfl::json` aliases (`YYJSON_READ_INSITU` is rejected at runtime). + ## Custom constructors One of the great things about C++ is that it gives you control over @@ -118,3 +172,34 @@ rfl::Result Person::from_json_obj(const JSONVar& _obj) { This will force the compiler to only compile the JSON parsing when the source file is compiled. +## Raw JSON Passthrough (`rfl::json::Raw`) + +Use `rfl::json::Raw` when a struct contains a JSON subtree that you want to +pass through without converting into intermediate C++ types: + +```cpp +struct Envelope { + int id; + rfl::json::Raw payload; +}; + +const auto env = rfl::json::read( + R"({"id":1,"payload":{"nested":[1,2,3]}})").value(); +const auto out = rfl::json::write(env); +``` + +Construct `rfl::json::Raw` from text using the validating factory +`rfl::json::Raw::from_string(...)` (which returns `rfl::Result` +after checking strict RFC 8259 JSON). When you already hold validated JSON +(such as output from `rfl::json::write`), `rfl::json::Raw::from_trusted_string(...)` +constructs a `Raw` without re-parsing; writing emits the stored JSON text +verbatim via `yyjson_mut_rawncpy`. + +On read, `rfl::json::Raw` captures the parsed `yyjson` subtree via +`yyjson_val_write_opts` with strict RFC 8259 formatting (flag `0`), which +canonicalizes whitespace and rejects non-standard values such as `NaN` or +`Infinity` even when parsed with `YYJSON_READ_ALLOW_INF_AND_NAN`. Pass +`YYJSON_READ_BIGNUM_AS_RAW` to `rfl::json::read` if integers wider than 64 bits +must be preserved verbatim. `rfl::json::Raw` is supported with `rfl::json` +(and `rfl::Generic` conversions / JSON Schema) only. + diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..0ed1b41d2 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -23,6 +23,7 @@ #include "rfl/DefaultVal.hpp" #include "rfl/Description.hpp" #include "rfl/DurationsAsCount.hpp" +#include "rfl/EnumNames.hpp" #include "rfl/EnumNamesOnly.hpp" #include "rfl/ExtraFields.hpp" #include "rfl/FailFast.hpp" @@ -30,6 +31,7 @@ #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" +#include "rfl/IntegerBounds.hpp" #include "rfl/Literal.hpp" #include "rfl/NamedTuple.hpp" #include "rfl/NoExtraFields.hpp" @@ -51,12 +53,15 @@ #include "rfl/SnakeCaseToCamelCase.hpp" #include "rfl/SnakeCaseToKebabCase.hpp" #include "rfl/SnakeCaseToPascalCase.hpp" +#include "rfl/StringLiteral.hpp" #include "rfl/TaggedUnion.hpp" #include "rfl/Timestamp.hpp" #include "rfl/ToAllCaps.hpp" +#include "rfl/TransformEnumNames.hpp" #include "rfl/UnderlyingEnums.hpp" #include "rfl/Validator.hpp" #include "rfl/Variant.hpp" +#include "rfl/VariantsAsOneOf.hpp" #include "rfl/Vectorstring.hpp" #include "rfl/always_false.hpp" #include "rfl/apply.hpp" @@ -92,6 +97,7 @@ #include "rfl/to_named_tuple.hpp" #include "rfl/to_view.hpp" #include "rfl/tuple_cat.hpp" +#include "rfl/type_name.hpp" #include "rfl/type_name_t.hpp" #include "rfl/view_t.hpp" #include "rfl/visit.hpp" diff --git a/include/rfl/AllOf.hpp b/include/rfl/AllOf.hpp index 5b61bb2bf..0e76a6e8e 100644 --- a/include/rfl/AllOf.hpp +++ b/include/rfl/AllOf.hpp @@ -1,6 +1,7 @@ #ifndef RFL_ALLOF_HPP_ #define RFL_ALLOF_HPP_ +#include #include #include @@ -33,14 +34,20 @@ struct AllOf { private: template static rfl::Result validate_impl(T _value) noexcept { - if constexpr (sizeof...(Tail) == 0) { - return Head::validate(std::move(_value)); - } else { + try { auto res = Head::validate(std::move(_value)); if (!res) { return res; } - return validate_impl(std::move(*res)); + if constexpr (sizeof...(Tail) == 0) { + return res; + } else { + return validate_impl(std::move(*res)); + } + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } }; diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index eb6425401..91169998f 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -1,7 +1,7 @@ #ifndef RFL_ANYOF_HPP_ #define RFL_ANYOF_HPP_ -#include +#include #include #include #include @@ -37,13 +37,13 @@ struct AnyOf { /// @param _errors The list of errors from failed validations /// @return A formatted error message static std::string make_error_message(const std::vector& _errors) { - std::stringstream stream; - stream << "Expected at least one of the following validations to pass, but " - "none of them did:"; + std::string msg = + "Expected at least one of the following validations to pass, but " + "none of them did:"; for (size_t i = 0; i < _errors.size(); ++i) { - stream << "\n" << i + 1 << ") " << _errors.at(i).what(); + msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); } - return stream.str(); + return msg; } template diff --git a/include/rfl/EnumNames.hpp b/include/rfl/EnumNames.hpp new file mode 100644 index 000000000..3a7a2d515 --- /dev/null +++ b/include/rfl/EnumNames.hpp @@ -0,0 +1,150 @@ +#ifndef RFL_ENUMNAMES_HPP_ +#define RFL_ENUMNAMES_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Processors.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" + +namespace rfl { + +/// Pair of `(enumerator, wire_name)` for per-enumerator overrides in +/// `rfl::EnumNames`. +template +using EnumOverride = std::pair; + +/// Specialize `rfl::EnumNames` to customize wire names for enum `E` across +/// JSON, CLI, Generic, YAML, XML, and JSON Schema without duplicating +/// enumerators as `rfl::Literal<...>`. +/// +/// Supported members (individually or combined; `overrides` takes precedence): +/// - `static constexpr EnumNameTransform transform = EnumNameTransform::snake_to_kebab;` +/// OR `static std::string transform(std::string_view _raw_name);` +/// (any return type convertible or explicitly constructible into `std::string`, +/// such as `std::string_view`, is accepted) +/// - `static constexpr std::array, N> overrides = {{ ... }};` +/// OR `static std::span> overrides();` +template +struct EnumNames {}; + +namespace internal { + +template +struct is_std_span : std::false_type {}; + +template +struct is_std_span> : std::true_type {}; + +template +concept EnumOverrideContiguousRange = + (std::is_array_v> && + std::same_as< + std::remove_cv_t>>, + EnumOverride>) || + requires(const std::remove_reference_t& _r) { + { _r.data() } -> std::convertible_to*>; + { _r.size() } -> std::convertible_to; + }; + +template +concept BorrowedEnumOverridesResult = + std::is_lvalue_reference_v || + is_std_span>::value; + +template +concept HasEnumOverridesVar = requires { + requires EnumOverrideContiguousRange::overrides), E>; +}; + +template +concept HasAnyEnumOverridesFn = requires { + requires EnumOverrideContiguousRange::overrides()), E>; +}; + +template +concept HasEnumOverridesFn = + HasAnyEnumOverridesFn && + BorrowedEnumOverridesResult::overrides())>; + +template +concept HasEnumTransformConst = requires { + { EnumNames::transform } -> std::convertible_to; +}; + +template +concept HasEnumTransformFn = requires(std::string_view _s) { + requires std::constructible_from::transform(_s))>; +}; + +template +inline constexpr bool has_custom_enum_names_for_transform_v = + HasEnumOverridesVar> || + HasAnyEnumOverridesFn> || + HasEnumTransformConst> || + HasEnumTransformFn> || + (_transform != EnumNameTransform::none); + +template > +inline constexpr bool has_custom_enum_names_v = + has_custom_enum_names_for_transform_v< + E, enum_name_transform_v>; + +template +inline std::span>> +get_enum_overrides() { + using U = std::remove_cvref_t; + static_assert( + !HasAnyEnumOverridesFn || HasEnumOverridesFn, + "rfl::EnumNames::overrides() must return a borrowed contiguous range " + "(for example, std::span> or const auto&)."); + if constexpr (HasEnumOverridesFn) { + auto&& r = EnumNames::overrides(); + return std::span>(std::data(r), std::size(r)); + } else if constexpr (HasEnumOverridesVar) { + return std::span>(std::data(EnumNames::overrides), + std::size(EnumNames::overrides)); + } else { + return {}; + } +} + +template +inline std::string resolve_enum_wire_name_for_transform( + const E _val, const std::string_view _raw_name) { + using U = std::remove_cvref_t; + for (const auto& [e, wire] : get_enum_overrides()) { + if (e == _val) { + return std::string(wire); + } + } + if constexpr (HasEnumTransformFn) { + return std::string(EnumNames::transform(_raw_name)); + } else if constexpr (HasEnumTransformConst) { + return apply_enum_name_transform(_raw_name, EnumNames::transform); + } else if constexpr (_transform != EnumNameTransform::none) { + return apply_enum_name_transform(_raw_name, _transform); + } else { + return std::string(_raw_name); + } +} + +template > +inline std::string resolve_enum_wire_name(const E _val, + const std::string_view _raw_name) { + return resolve_enum_wire_name_for_transform< + E, enum_name_transform_v>(_val, _raw_name); +} + +} // namespace internal +} // namespace rfl + +#endif // RFL_ENUMNAMES_HPP_ diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp index 46f79f65f..d266300c2 100644 --- a/include/rfl/Generic.hpp +++ b/include/rfl/Generic.hpp @@ -196,10 +196,10 @@ class RFL_API Generic { Result to_string() const noexcept; /// Returns the underlying variant. - VariantType& variant() noexcept { return value_; }; + VariantType& variant() noexcept { return value_; } /// Returns the underlying variant. - const VariantType& variant() const noexcept { return value_; }; + const VariantType& variant() const noexcept { return value_; } /// Equality comparison. Two Generics are equal if they hold the same /// alternative and the underlying values compare equal. diff --git a/include/rfl/IntegerBounds.hpp b/include/rfl/IntegerBounds.hpp new file mode 100644 index 000000000..d63b77845 --- /dev/null +++ b/include/rfl/IntegerBounds.hpp @@ -0,0 +1,21 @@ +#ifndef RFL_INTEGERBOUNDS_HPP_ +#define RFL_INTEGERBOUNDS_HPP_ + +#include + +namespace rfl { + +/// Opt-in JSON Schema processor: emit `minimum` and `maximum` bounds matching +/// C++ integer widths (`int8_t`..`int64_t`, `uint8_t`..`uint64_t`, `short`, +/// `int`, `long`, `long long`, and their unsigned counterparts; excludes +/// `bool` and character types whose signedness is platform-dependent). +struct IntegerBounds { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif // RFL_INTEGERBOUNDS_HPP_ diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 4208d7713..e89ae0da5 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -164,12 +165,20 @@ class Literal { return Literal(_v); }; return find_value(_str).transform(to_literal); - }; + } /// The name defined by the Literal (returns the string representation). /// @return The string value of the current literal std::string name() const { return find_name(); } + /// Returns the compile-time string view for a single-value Literal. + /// @return The string_view of the single allowed literal value + static constexpr std::string_view name_view() noexcept + requires(sizeof...(fields_) == 1) + { + return tuple_element_t<0, FieldsType>::name_.string_view(); + } + /// Returns all possible values of the literal as a std::vector. /// @return A vector containing all allowed string values static std::vector names() { diff --git a/include/rfl/MetaField.hpp b/include/rfl/MetaField.hpp index 192c7e6c5..62ac12294 100644 --- a/include/rfl/MetaField.hpp +++ b/include/rfl/MetaField.hpp @@ -21,11 +21,11 @@ class MetaField { /// Returns the name of the field. /// @return The field name as it appears in the struct - const std::string& name() const { return name_; }; + const std::string& name() const { return name_; } /// Returns the type information of the field. /// @return A string describing the field's type - const std::string& type() const { return type_; }; + const std::string& type() const { return type_; } private: /// The name of the field. diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 381fe8811..9123b188d 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -716,7 +716,7 @@ class NamedTuple<> { using Values = rfl::Tuple<>; /// @brief Default constructor for empty NamedTuple. - NamedTuple(){}; + NamedTuple() {} /// @brief Destructor. ~NamedTuple() = default; diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index 8b302cf13..5ef86d7b4 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -1,7 +1,7 @@ #ifndef RFL_ONEOF_HPP_ #define RFL_ONEOF_HPP_ -#include +#include #include #include #include @@ -39,40 +39,32 @@ struct OneOf { /// @param _errors The list of errors from failed validations /// @return A formatted error message indicating the validation failure static std::string make_error_message(const std::vector& _errors) { - std::stringstream stream; - stream << "Expected exactly 1 out of " << sizeof...(Cs) + 1 - << " validations to pass, but " << sizeof...(Cs) + 1 - _errors.size() - << " of them did. The following errors were generated: "; + std::string msg = "Expected exactly 1 out of " + + std::to_string(sizeof...(Cs) + 1) + + " validations to pass, but " + + std::to_string(sizeof...(Cs) + 1 - _errors.size()) + + " of them did. The following errors were generated: "; for (size_t i = 0; i < _errors.size(); ++i) { - stream << "\n" << i + 1 << ") " << _errors.at(i).what(); + msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); } - return stream.str(); + return msg; } template static rfl::Result validate_impl(const T& _value, std::vector _errors) { - return Head::validate(_value) - .and_then([&](auto&&) -> rfl::Result { - if constexpr (sizeof...(Tail) == 0) { - if (_errors.size() == sizeof...(Cs)) { - return _value; - // The AI suggests return std::forward(_result); - // is it correct in this context? - } - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }) - .or_else([&](auto&& _err) -> rfl::Result { - _errors.emplace_back(std::move(_err)); - if constexpr (sizeof...(Tail) == 0) { - return error(make_error_message(_errors)); - } else { - return validate_impl(_value, std::move(_errors)); - } - }); + auto res = Head::validate(_value); + if (!res) { + _errors.emplace_back(std::move(res).error()); + } + if constexpr (sizeof...(Tail) == 0) { + if (_errors.size() == sizeof...(Cs)) { + return _value; + } + return error(make_error_message(_errors)); + } else { + return validate_impl(_value, std::move(_errors)); + } } }; diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index b1dcbc040..a22e569a7 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -1,7 +1,6 @@ #ifndef RFL_PATTERNVALIDATOR_HPP_ #define RFL_PATTERNVALIDATOR_HPP_ -#include #include #include @@ -35,10 +34,8 @@ struct PatternValidator { ctll::construct_from_pointer, _regex.arr_.data()}>(_str)) { return std::move(_str); } else { - std::stringstream stream; - stream << "String '" << _str << "' did not match format '" << _name.str() - << "': '" << _regex.str() << "'."; - return error(stream.str()); + return error("String '" + _str + "' did not match format '" + + _name.str() + "': '" + _regex.str() + "'."); } } diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index 5148b0b00..d3c0e0ec7 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -1,7 +1,7 @@ #ifndef RFL_SIZE_HPP_ #define RFL_SIZE_HPP_ -#include +#include #include #include "Ref.hpp" diff --git a/include/rfl/StringLiteral.hpp b/include/rfl/StringLiteral.hpp new file mode 100644 index 000000000..00f63055f --- /dev/null +++ b/include/rfl/StringLiteral.hpp @@ -0,0 +1,88 @@ +#ifndef RFL_STRINGLITERAL_HPP_ +#define RFL_STRINGLITERAL_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +namespace rfl { + +/// Normal strings cannot be used as template parameters, but this can. +/// Used for compile-time field names, literals, descriptions, and patterns. +template +struct StringLiteral { + static_assert( + N >= 1, + "rfl::StringLiteral requires N >= 1 (including the null terminator)."); + + /// Constrained via template type parameters rather than a requires-fold + /// over decltype of the function parameter pack: the latter crashes + /// clang 21/22 in C++26 mode (llvm/llvm-project#198052, #205000). + template ... Chars> + constexpr StringLiteral(const Chars... _chars) : arr_{_chars..., '\0'} {} + + constexpr StringLiteral(const std::array _arr) : arr_(_arr) {} + + constexpr StringLiteral(const char (&_str)[N]) { + std::copy_n(_str, N, std::data(arr_)); + } + + constexpr StringLiteral(const std::string_view _str) { + std::copy_n(_str.data(), std::min(_str.size(), N - 1), std::data(arr_)); + } + + template + requires(std::is_same_v || std::is_same_v) + explicit constexpr StringLiteral(T _data) { + std::copy_n(_data, N, std::data(arr_)); + } + + /// Returns the value as a string. + std::string str() const { return std::string(string_view()); } + + /// Returns the value as a string_view. + constexpr std::string_view string_view() const noexcept { + return std::string_view(std::data(arr_), N - 1); + } + + static constexpr std::size_t length = N - 1; + + std::array arr_{}; +}; + +template +constexpr inline bool operator==(const StringLiteral& _first, + const StringLiteral& _second) noexcept { + if constexpr (N1 != N2) { + return false; + } else { + return _first.string_view() == _second.string_view(); + } +} + +template +constexpr inline bool operator!=(const StringLiteral& _first, + const StringLiteral& _second) noexcept { + return !(_first == _second); +} + +/// Concatenates two StringLiterals at compile time (or runtime) into a +/// null-terminated StringLiteral of combined length. +template + requires(N1 >= 1 && N2 >= 1) +constexpr inline StringLiteral operator+( + const StringLiteral& _first, + const StringLiteral& _second) noexcept { + std::array arr{}; + std::copy_n(_first.arr_.data(), N1 - 1, arr.data()); + std::copy_n(_second.arr_.data(), N2 - 1, arr.data() + (N1 - 1)); + return StringLiteral(arr); +} + +} // namespace rfl + +#endif diff --git a/include/rfl/Timestamp.hpp b/include/rfl/Timestamp.hpp index a940e0fcb..8129848ae 100644 --- a/include/rfl/Timestamp.hpp +++ b/include/rfl/Timestamp.hpp @@ -73,8 +73,10 @@ class Timestamp { static Result from_string(const char* _str) noexcept { try { return Timestamp(_str); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while parsing timestamp."); } } @@ -82,7 +84,7 @@ class Timestamp { /// This is an alternative to the throwing constructor for error handling without exceptions. /// @param _str The string to parse in the format specified by the template parameter /// @return Result containing the Timestamp if parsing succeeded, or an error otherwise - static Result from_string(const std::string& _str) { + static Result from_string(const std::string& _str) noexcept { return from_string(_str.c_str()); } diff --git a/include/rfl/TransformEnumNames.hpp b/include/rfl/TransformEnumNames.hpp new file mode 100644 index 000000000..7aeb6d397 --- /dev/null +++ b/include/rfl/TransformEnumNames.hpp @@ -0,0 +1,54 @@ +#ifndef RFL_TRANSFORMENUMNAMES_HPP_ +#define RFL_TRANSFORMENUMNAMES_HPP_ + +#include +#include +#include + +#include "common.hpp" + +namespace rfl { + +/// Built-in wire-name transforms applicable to C++ enum enumerator names via +/// `rfl::TransformEnumNames<...>` processors. +enum class EnumNameTransform : std::uint8_t { + none = 0, + snake_to_kebab, + snake_to_camel, + snake_to_pascal, + camel_to_snake, + to_lower, + to_upper, +}; + +/// Applies a built-in ASCII `EnumNameTransform` to an enumerator identifier. +RFL_API std::string apply_enum_name_transform(std::string_view _name, + EnumNameTransform _transform); + +/// Processor that applies a whole-enum wire-name transform across read, write, +/// and schema generation. Resolved wire-name tables are cached once per +/// `(EnumType, EnumNameTransform)` pair. +template +struct TransformEnumNames { + static constexpr EnumNameTransform value = _transform; + + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +using EnumSnakeCaseToKebabCase = + TransformEnumNames; +using EnumSnakeCaseToCamelCase = + TransformEnumNames; +using EnumSnakeCaseToPascalCase = + TransformEnumNames; +using EnumCamelCaseToSnakeCase = + TransformEnumNames; +using EnumToLowerCase = TransformEnumNames; +using EnumToUpperCase = TransformEnumNames; + +} // namespace rfl + +#endif // RFL_TRANSFORMENUMNAMES_HPP_ diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 9be58bf61..4a0cd1243 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -34,8 +34,10 @@ struct Validator { static Result from_value(const T& _value) noexcept { try { return wrap_validated(ValidationType::validate(_value)); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } @@ -46,8 +48,10 @@ struct Validator { static Result from_value(T&& _value) noexcept { try { return wrap_validated(ValidationType::validate(std::move(_value))); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception during validation."); } } diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index 018edca72..046b5a030 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -774,7 +774,7 @@ namespace std { template void swap(rfl::Variant& _lhs, rfl::Variant& _rhs) noexcept { _lhs.swap(_rhs); -}; +} } // namespace std #endif diff --git a/include/rfl/VariantsAsOneOf.hpp b/include/rfl/VariantsAsOneOf.hpp new file mode 100644 index 000000000..0b71c9752 --- /dev/null +++ b/include/rfl/VariantsAsOneOf.hpp @@ -0,0 +1,33 @@ +#ifndef RFL_VARIANTSASONEOF_HPP_ +#define RFL_VARIANTSASONEOF_HPP_ + +#include + +namespace rfl { + +/// A processor that makes the JSON schema describe rfl::Variant and +/// std::variant as oneOf instead of anyOf. +/// This is a marker type (doesn't modify data) that changes the generated +/// schema. It has no effect on reading or writing. +/// By default, untagged variants are described as anyOf, because their +/// alternatives can overlap: 1 matches both alternatives of +/// rfl::Variant, and oneOf would reject it. rfl::TaggedUnion is +/// always described as oneOf, and std::optional and rfl::Generic always as +/// anyOf. +/// Usage: rfl::json::to_schema() +struct VariantsAsOneOf { + public: + /// Identity process function - returns the named tuple unchanged. + /// The actual change happens in the schema generation, not here. + /// @tparam StructType The struct type being processed + /// @param _named_tuple The named tuple representation of the struct + /// @return The same named tuple (unchanged) + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/atomic/is_atomic.hpp b/include/rfl/atomic/is_atomic.hpp index 93312de28..303468e3f 100644 --- a/include/rfl/atomic/is_atomic.hpp +++ b/include/rfl/atomic/is_atomic.hpp @@ -19,7 +19,7 @@ template struct is_atomic { static constexpr bool value = false; using RemoveAtomicT = T; - static void set(RemoveAtomicT&& val, T* _t) { *_t = std::forward(val); }; + static void set(RemoveAtomicT&& val, T* _t) { *_t = std::forward(val); } }; template @@ -28,7 +28,7 @@ struct is_atomic> { using RemoveAtomicT = T; static void set(RemoveAtomicT&& val, std::atomic* _t) { _t->store(std::forward(val), std::memory_order_relaxed); - }; + } }; template <> diff --git a/include/rfl/capnproto/is_named_type.hpp b/include/rfl/capnproto/is_named_type.hpp index cad64d631..a45a4986d 100644 --- a/include/rfl/capnproto/is_named_type.hpp +++ b/include/rfl/capnproto/is_named_type.hpp @@ -1,6 +1,8 @@ #ifndef RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ #define RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ +#include + #include "../parsing/schema/Type.hpp" namespace rfl::capnproto { @@ -8,10 +10,15 @@ namespace rfl::capnproto { inline bool is_named_type(const parsing::schema::Type& _type) { return _type.variant_.visit([&](const auto& _v) -> bool { using T = std::remove_cvref_t; - return std::is_same() || - std::is_same() || - std::is_same() || - std::is_same(); + if constexpr (std::is_same_v || + std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same() || + std::is_same() || + std::is_same(); + } }); } diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 85881e7b9..a35b9e025 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -8,5 +8,6 @@ #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" +#include "cli/usage.hpp" #endif diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp new file mode 100644 index 000000000..4d384ab80 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,451 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../generic/Writer.hpp" +#include "../internal/default_if_missing_v.hpp" +#include "../internal/is_default_val_v.hpp" +#include "../internal/is_extra_fields.hpp" +#include "../internal/is_named_tuple.hpp" +#include "../internal/no_optionals_v.hpp" +#include "../parsing/is_required.hpp" +#include "../parsing/schema/Definition.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/make.hpp" +#include "../to_generic.hpp" +#include "Reader.hpp" +#include "options.hpp" +#include "resolve_args.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Whether a top-level field is required, which the schema cannot tell the +/// way the parser sees it. +struct UsageFieldMeta { + bool required = true; +}; + +/// Everything usage() renders about one argument. +struct UsageArg { + /// The long name, including the path of nested objects ("database.host"). + std::string name; + std::string short_name; + bool positional = false; + /// What the option does with a value, from the parser's option table: + /// flags (`--verbose`) can be given without one. + OptionKind kind = OptionKind::value; + /// Whether the field is a list. + bool is_list = false; + bool required = true; + /// Whether `required` was taken from the parser's compile-time traits, so + /// that the schema must not override it. + bool required_is_known = false; + /// The placeholder for one value: "", "" or "". Lists + /// are rendered from it with the list delimiter. + std::string value = ""; + /// The allowed values of enums and literals. + std::vector choices; + std::string description; +}; + +/// Whether a missing field of type `ValueType` inside root type `U` is filled +/// in by the parser's default-value path. Mirrors +/// `NamedTupleParser::handle_one_missing_field` without invoking `T{}` at +/// runtime (for structs, `schema::make` already constructs `T{}` once if and +/// only if `has_default_val_v` is true). +template +constexpr bool usage_default_val_is_optional() { + if constexpr (!rfl::internal::is_default_val_v) { + return false; + } else if constexpr (rfl::internal::is_named_tuple_v) { + using Inner = typename rfl::internal::default_val_t::Type; + return !std::is_const_v && + std::is_default_constructible_v && + std::is_default_constructible_v; + } else { + return std::is_default_constructible_v; + } +} + +template +void add_usage_field_meta(std::map* _meta) { + using Info = field_info; + using RawValueType = + std::remove_reference_t>; + using ValueType = std::remove_cvref_t; + auto& meta = (*_meta)[std::string(Info::name())]; + // The same condition as in NamedTupleParser::handle_one_missing_field. + // The schema cannot tell on its own, because it marks a DefaultVal field as + // optional even where the parser requires it. + meta.required = + !usage_default_val_is_optional() + && !rfl::internal::is_extra_fields_v + && (rfl::internal::no_optionals_v + || parsing::is_required()); +} + +/// Collects whether each top-level field is required from the same +/// compile-time traits that the parser uses, so the help matches what the +/// parser accepts. Positional, Short and flags come from the parser's option +/// table (make_options). +template +std::map collect_usage_field_meta( + std::index_sequence<_is...>) { + std::map meta; + (add_usage_field_meta(&meta), ...); + return meta; +} + +/// Walks the format-agnostic schema of the struct and collects one UsageArg +/// per command-line argument, in declaration order. +class UsageCollector { + public: + using Type = parsing::schema::Type; + + UsageCollector(const parsing::schema::Definition* _definition, + const std::map* _meta, + const Options* _options, + const bool _optionals_are_required) + : definition_(_definition), + meta_(_meta), + options_(_options), + optionals_are_required_(_optionals_are_required) { + for (const auto& [short_name, path] : _options->short_options) { + short_names_[path] = short_name; + } + } + + /// Collects the arguments. + /// @param _all_optional Whether no argument is required + /// (rfl::DefaultIfMissing). + std::vector collect(const bool _all_optional) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), false); + return std::move(args_); + } + + private: + /// @param _outermost Whether _type is the outermost type of a field. + void add(const Type& _type, UsageArg _arg, const bool _outermost) { + _type.variant_.visit([&](const auto& _t) { + using T = std::remove_cvref_t; + // Description and Deprecated wrap the inner schema node without changing + // how the field is read. Short, Positional and Rename leave no node. + if constexpr (std::is_same_v + || std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _outermost); + + } else if constexpr (std::is_same_v) { + if (!_arg.required_is_known && !optionals_are_required_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + // The schema populates `default_value_` only when the parser recognizes + // the DefaultVal field and default-constructed its enclosing struct. + if (!_arg.required_is_known && _outermost && _t.default_value_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + const auto it = definition_->definitions_.find(_t.name_); + if (it == definition_->definitions_.end() + || !visiting_.insert(_t.name_).second) { + // Unknown or recursive: there is no finite set of paths to list. + add_leaf(std::move(_arg)); + return; + } + add(it->second, std::move(_arg), _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg); + + } else if constexpr (std::is_same_v) { + if (!_arg.name.empty()) { + _arg.name += path_separator; + } + _arg.name += ""; + _arg.short_name.clear(); + _arg.positional = false; + add(*_t.value_type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + _arg.kind = OptionKind::flag; + add_leaf(std::move(_arg)); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg)); + + } else if constexpr (std::is_same_v) { + auto values = std::vector(); + for (const auto& v : _t.values_) { + values.push_back(v.value_); + } + add_choices(values, std::move(_arg)); + + } else if constexpr (std::is_same_v + || std::is_same_v + || std::is_same_v) { + _arg.is_list = true; + add_leaf(std::move(_arg)); + + } else { + add_leaf(std::move(_arg)); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent) { + const bool is_root = _parent.name.empty(); + for (const auto& [name, type] : _object.types_) { + auto arg = UsageArg{}; + arg.name = is_root ? name : _parent.name + path_separator + name; + // Children of an optional object are only needed if it is given. + arg.required = _parent.required; + if (is_root) { + const auto& positionals = options_->positionals; + arg.positional = std::find(positionals.begin(), positionals.end(), + name) != positionals.end(); + const auto short_name = short_names_.find(name); + if (short_name != short_names_.end()) { + arg.short_name = short_name->second; + } + const auto it = meta_->find(name); + if (it != meta_->end()) { + arg.required = arg.required && it->second.required; + arg.required_is_known = true; + } + } + add(type, std::move(arg), true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg) { + _arg.choices = _values; + _arg.value = "<"; + for (size_t i = 0; i < _values.size(); ++i) { + _arg.value += (i == 0 ? "" : "|") + _values[i]; + } + _arg.value += ">"; + add_leaf(std::move(_arg)); + } + + void add_leaf(UsageArg _arg) { + if (_arg.name.empty()) { + return; + } + // How the parser treats the option, from the table that it uses. Keep + // the schema-derived kind (such as OptionKind::flag for nested booleans) + // when the option table only tracks top-level paths. + const auto option = options_->find_long(_arg.name); + if (option.kind != OptionKind::unknown) { + _arg.kind = option.kind; + } + args_.emplace_back(std::move(_arg)); + } + + private: + const parsing::schema::Definition* definition_; + const std::map* meta_; + const Options* options_; + const bool optionals_are_required_; + /// The rfl::Short aliases, by the path of their field. + std::map short_names_; + std::set visiting_; + std::vector args_; +}; + +/// The placeholder for the value of _arg: "", "", or for a list +/// "" with the list delimiter. +inline std::string usage_value_to_string(const UsageArg& _arg) { + if (!_arg.is_list) { + return _arg.value; + } + const auto d = std::string(1, array_delimiter); + return ""; +} + +/// "", "-p|--port=", "--verbose[=]" +inline std::string usage_arg_to_string(const UsageArg& _arg, + const std::string& _short_sep) { + if (_arg.positional) { + return "<" + _arg.name + ">"; + } + auto str = _arg.short_name.empty() ? std::string() + : "-" + _arg.short_name + _short_sep; + str += "--" + _arg.name; + const auto value = usage_value_to_string(_arg); + switch (_arg.kind) { + case OptionKind::flag: + // `--verbose`: the value can be left out. + str += "[=" + value + "]"; + break; + default: + str += "=" + value; + break; + } + return str; +} + +inline bool usage_ends_sentence(const std::string& _str) { + return !_str.empty() + && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); +} + +/// "Port to connect on. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + if (_arg.positional && !_arg.choices.empty()) { + auto choices = std::string("Choices: "); + for (size_t i = 0; i < _arg.choices.size(); ++i) { + choices += (i == 0 ? "" : "|") + _arg.choices[i]; + } + sentences.push_back(std::move(choices)); + } + if (_arg.required) { + sentences.push_back("Required"); + } + auto text = _arg.description; + while (!text.empty() + && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' + || text.back() == '\n')) { + text.pop_back(); + } + for (const auto& s : sentences) { + if (!text.empty()) { + text += usage_ends_sentence(text) ? " " : ". "; + } + text += s; + } + if (!sentences.empty() && !usage_ends_sentence(text)) { + text += "."; + } + return text; +} + +inline std::string format_usage(const std::string& _program_name, + const std::vector& _args, + const bool _detailed) { + auto out = "Usage: " + _program_name; + for (const auto& arg : _args) { + const auto str = usage_arg_to_string(arg, "|"); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; + if (!_detailed || _args.empty()) { + return out; + } + + auto rows = std::vector>(); + size_t width = 0; + for (const auto& arg : _args) { + rows.emplace_back(usage_arg_to_string(arg, ", "), usage_help_text(arg)); + width = std::max(width, rows.back().first.size()); + } + + constexpr size_t indent = 2; + constexpr size_t gap = 2; + const auto continuation = '\n' + std::string(indent + width + gap, ' '); + out += "\nArguments:\n"; + for (const auto& [left, right] : rows) { + out += std::string(indent, ' ') + left; + if (!right.empty()) { + out += std::string(width - left.size() + gap, ' '); + for (size_t i = 0; i < right.size(); ++i) { + const char c = right[i]; + if (c == '\n') { + if (i + 1 < right.size() && right[i + 1] != '\n') { + out += continuation; + } else { + out += '\n'; + } + } else { + out += c; + } + } + } + out += '\n'; + } + return out; +} + +} // namespace internal + +/// Generates the usage line, and optionally a help text with one row per +/// argument, for the struct that `rfl::cli::read()` parses into. +/// It applies the same processors as `read`, so the names always match what +/// the parser accepts (kebab-case, rfl::Rename, rfl::Flatten, nested paths). +/// +/// The help text lists the description (rfl::Description), the allowed +/// values of enums and literals and whether the argument is required. +/// @tparam T The struct type that the arguments are parsed into +/// @tparam Ps The processors passed to `rfl::cli::read` +/// @param _program_name The name shown after "Usage:", usually argv[0] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline, or an error if no read of +/// T can succeed: two fields have the same short name, or T has a bare +/// rfl::DefaultVal and default-constructing it throws. +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using U = internal::unwrapped_option_t; + // The table that read() parses with, so the help shows what the parser + // accepts. + const auto options = internal::make_options(); + return internal::check_short_names(options).and_then( + [&](auto) -> rfl::Result { + try { + std::map meta; + if constexpr (internal::is_option_struct_v) { + using NamedTupleType = + internal::option_fields_t; + meta = internal::collect_usage_field_meta( + std::make_index_sequence{}); + } + // The schema takes the default values from a default-constructed + // T, which can throw. + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, &options, + rfl::internal::no_optionals_v); + const auto args = collector.collect( + rfl::internal::default_if_missing_v); + return internal::format_usage(_program_name, args, _detailed); + } catch (const std::exception& e) { + return error(e.what()); + } + }); +} + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 1233f2f09..258adf8d4 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -1,7 +1,9 @@ #ifndef RFL_COMPARISONS_HPP_ #define RFL_COMPARISONS_HPP_ -#include +#include +#include +#include #include #include "Result.hpp" @@ -9,6 +11,46 @@ namespace rfl { +namespace internal { + +template +std::string format_comparison_value(const T& _val) { + if constexpr (std::is_floating_point_v) { + char buf[64]; + const int n = [&]() { + if constexpr (std::is_same_v) { + return std::snprintf(buf, sizeof(buf), "%Lg", _val); + } else { + return std::snprintf(buf, sizeof(buf), "%g", static_cast(_val)); + } + }(); + if (n <= 0) { + return {}; + } + const auto len = static_cast(n) < sizeof(buf) + ? static_cast(n) + : sizeof(buf) - 1; + return std::string(buf, len); + } else if constexpr (std::is_same_v) { + return std::string(1, _val); + } else if constexpr (std::is_enum_v) { + return std::to_string(static_cast>(_val)); + } else { + // signed char / unsigned char (int8_t / uint8_t) intentionally format as + // decimal integers via std::to_string rather than raw characters. + return std::to_string(_val); + } +} + +template +std::string comparison_error_message(const char* _prefix, const T& _threshold, + const T& _value) { + return std::string(_prefix) + format_comparison_value(_threshold) + + ", but got " + format_comparison_value(_value) + "."; +} + +} // namespace internal + template struct EqualTo { /// @brief Validates that the given value is equal to the threshold. @@ -22,10 +64,8 @@ struct EqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value != threshold) { - std::stringstream stream; - stream << "Value expected to be equal to " << threshold << ", but got " - << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be equal to ", threshold, _value)); } return _value; } @@ -61,10 +101,8 @@ struct Minimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value < threshold) { - std::stringstream stream; - stream << "Value expected to be greater than or equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be greater than or equal to ", threshold, _value)); } return _value; } @@ -100,10 +138,8 @@ struct ExclusiveMinimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value <= threshold) { - std::stringstream stream; - stream << "Value expected to be greater than " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be greater than ", threshold, _value)); } return _value; } @@ -139,10 +175,8 @@ struct Maximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value > threshold) { - std::stringstream stream; - stream << "Value expected to be less than or equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be less than or equal to ", threshold, _value)); } return _value; } @@ -177,10 +211,8 @@ struct ExclusiveMaximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value >= threshold) { - std::stringstream stream; - stream << "Value expected to be less than " << threshold << ", but got " - << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected to be less than ", threshold, _value)); } return _value; } @@ -215,10 +247,8 @@ struct NotEqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value == threshold) { - std::stringstream stream; - stream << "Value expected not to be equal to " << threshold - << ", but got " << _value << "."; - return error(stream.str()); + return error(internal::comparison_error_message( + "Value expected not to be equal to ", threshold, _value)); } return _value; } diff --git a/include/rfl/enums.hpp b/include/rfl/enums.hpp index 7f107916a..46c16df1e 100644 --- a/include/rfl/enums.hpp +++ b/include/rfl/enums.hpp @@ -1,10 +1,19 @@ #ifndef RFL_ENUMS_HPP_ #define RFL_ENUMS_HPP_ -#include +#include +#include #include +#include +#include +#include +#include +#include "EnumNames.hpp" +#include "Processors.hpp" #include "Result.hpp" +#include "TransformEnumNames.hpp" +#include "internal/enum_name_transform_v.hpp" #include "internal/enums/from_string.hpp" #include "internal/enums/get_enum_names.hpp" #include "internal/enums/get_enum_range.hpp" @@ -52,94 +61,262 @@ constexpr auto get_enum_range() { return internal::enums::get_enum_range(); } -// Converts an enum value to tis string representation. -template -std::string enum_to_string(const EnumType _enum) { - if constexpr (internal::enums::is_flag_enum) { +namespace internal { + +template +std::vector>> +build_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + std::vector> out; + constexpr auto enumerators = get_enumerator_array(); + out.reserve(enumerators.size()); + for (const auto& [raw_name, val] : enumerators) { + out.emplace_back( + resolve_enum_wire_name_for_transform(val, raw_name), + val); + } + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [val, wire] : get_enum_overrides()) { + bool already_present = false; + for (const auto& entry : out) { + if (entry.second == val) { + already_present = true; + break; + } + } + if (!already_present) { + out.emplace_back(std::string(wire), val); + } + } + } + return out; +} + +template +const std::vector>>& +get_cached_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kTable = build_enum_wire_names_with_transform(); + return kTable; +} + +template +const std::vector>>& +get_cached_unique_enum_wire_names_with_transform() { + using E = std::remove_cvref_t; + static const auto kUnique = []() { + std::vector> out; + const auto& all = get_cached_enum_wire_names_with_transform(); + out.reserve(all.size()); + for (const auto& entry : all) { + bool dup = false; + for (const auto& existing : out) { + if (existing.first == entry.first) { + dup = true; + break; + } + } + if (!dup) { + out.push_back(entry); + } + } + return out; + }(); + return kUnique; +} + +template +std::string enum_to_single_wire_name(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (val == _enum) { + return wire; + } + } + return std::to_string(static_cast>(_enum)); + } else { + return internal::enums::to_string(_enum); + } +} + +template +std::string enum_to_string_with_transform(const EnumType _enum) { + using E = std::remove_cvref_t; + if constexpr (internal::enums::is_flag_enum) { // Iterates through the enum bit by bit and matches it against the flags. - using T = std::underlying_type_t; + using T = std::underlying_type_t; auto val = static_cast(_enum); int i = 0; std::vector flags; while (val != 0) { const auto bit = val & static_cast(1); if (bit == 1) { - auto str = internal::enums::to_string( - static_cast(static_cast(1) << i)); + auto str = enum_to_single_wire_name( + static_cast(static_cast(1) << i)); flags.emplace_back(std::move(str)); } ++i; val >>= 1; } if (flags.empty()) { - return internal::enums::to_string(static_cast(0)); + return enum_to_single_wire_name(static_cast(0)); } return internal::strings::join("|", flags); } else { - return internal::enums::to_string(_enum); + return enum_to_single_wire_name(_enum); } } -// Converts a string to a value of the given enum type. -// -// By default, numeric values are accepted in addition to the declared -// enumerator names, even when they do not correspond to a declared -// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 -// will produce the cast value 4). Pass enum_names_only = true (or use the -// EnumNamesOnly processor with a parser) to accept only the declared -// enumerator names instead. -template -Result string_to_enum(const std::string& _str) { - const auto make_error_msg = [&](const auto& name) { +template +Result> string_to_enum_with_transform( + const std::string_view _str) { + using E = std::remove_cvref_t; + const auto make_error_msg = [](const std::string_view name) { std::string msg = "Invalid enum value: '"; msg += name; msg += "'. Must be one of ["; const char* sep = ""; - for (const auto& p : get_enumerator_array()) { - msg += sep; - msg += p.first; - sep = ", "; + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& p : + get_cached_unique_enum_wire_names_with_transform()) { + msg += sep; + msg += p.first; + sep = ", "; + } + } else { + for (const auto& p : get_enumerator_array()) { + msg += sep; + msg += p.first; + sep = ", "; + } } msg += "]."; return error(msg); }; const auto cast_numbers_or_names = - [&](const std::string& name) -> Result { - const auto r = internal::enums::from_string(name); - if (r) { - return *r; + [&](const std::string_view name) -> Result { + if constexpr (has_custom_enum_names_for_transform_v) { + for (const auto& [wire, val] : + get_cached_enum_wire_names_with_transform()) { + if (wire == name) { + return val; + } + } + } else { + const auto r = internal::enums::from_string(name); + if (r) { + return *r; + } } if constexpr (enum_names_only) { return make_error_msg(name); } else { - try { - const auto val = std::stoi(name); - return static_cast(val); - } catch (std::exception& exp) { + if (name.empty()) { return make_error_msg(name); } + using Underlying = std::underlying_type_t; + using ParseType = std::conditional_t< + (sizeof(Underlying) < sizeof(int)), int, + std::conditional_t< + std::is_signed_v, + std::conditional_t< + (sizeof(Underlying) <= sizeof(int)), int, + std::conditional_t<(sizeof(Underlying) <= sizeof(long)), long, + long long>>, + std::conditional_t< + (sizeof(Underlying) <= sizeof(unsigned int)), unsigned int, + std::conditional_t< + (sizeof(Underlying) <= sizeof(unsigned long)), + unsigned long, unsigned long long>>>>; + ParseType val{}; + const auto* begin = name.data(); + const auto* end = begin + name.size(); + const auto [ptr, ec] = std::from_chars(begin, end, val); + if (ec == std::errc{} && ptr == end) { + return static_cast(val); + } + return make_error_msg(name); } }; - if constexpr (internal::enums::is_flag_enum) { - using T = std::underlying_type_t; - const auto split = internal::strings::split(_str, "|"); + if constexpr (internal::enums::is_flag_enum) { + using T = std::underlying_type_t; auto res = static_cast(0); - for (const auto& s : split) { - const auto r = cast_numbers_or_names(s); - if (r) { - res |= static_cast(*r); - } else { + std::string_view remaining = _str; + while (true) { + const auto pos = remaining.find('|'); + const auto token = remaining.substr(0, pos); + const auto r = cast_numbers_or_names(token); + if (!r) { return r; } + res |= static_cast(*r); + if (pos == std::string_view::npos) { + break; + } + remaining.remove_prefix(pos + 1); } - return static_cast(res); + return static_cast(res); } else { return cast_numbers_or_names(_str); } } +template +Result> string_to_enum_with_transform_noexcept( + const std::string_view _str) noexcept { + try { + return string_to_enum_with_transform( + _str); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception thrown while parsing enum value."); + } +} + +} // namespace internal + +// Converts an enum value to its wire string representation, honoring +// `rfl::EnumNames` and any `rfl::TransformEnumNames<...>` processor +// passed in `Ps...`. +template +std::string enum_to_string(const EnumType _enum) { + return internal::enum_to_string_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(_enum); +} + +// Returns all declared enumerators (plus any explicit `rfl::EnumNames` +// overrides for values outside the reflected range) paired with their resolved +// wire names. +template +std::vector>> +get_enum_wire_names() { + return internal::get_cached_enum_wire_names_with_transform< + std::remove_cvref_t, + internal::enum_name_transform_v>>(); +} + +// Converts a string to a value of the given enum type. +// +// By default, numeric values are accepted in addition to the declared +// enumerator names, even when they do not correspond to a declared +// enumerator (for instance, reading "4" into an enum with values 1, 2 and 3 +// will produce the cast value 4). Pass enum_names_only = true (or use the +// EnumNamesOnly processor with a parser) to accept only the declared +// enumerator names instead. +template +Result> string_to_enum( + const std::string_view _str) noexcept { + return internal::string_to_enum_with_transform_noexcept< + std::remove_cvref_t, enum_names_only, + internal::enum_name_transform_v>>(_str); +} + } // namespace rfl #endif // RFL_ENUMS_HPP_ diff --git a/include/rfl/env/Reader.hpp b/include/rfl/env/Reader.hpp index 68545f790..b87690baa 100644 --- a/include/rfl/env/Reader.hpp +++ b/include/rfl/env/Reader.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -170,14 +171,13 @@ struct Reader { /// @param _var The ENV variable to check /// @return true if the variable is empty, false otherwise bool is_empty(const InputVarType& _var) const noexcept { - const auto str = std::getenv(_var.path.c_str()); - if (str != nullptr) { - return false; - } if (_var.path.empty()) { return true; } - const auto prefix = _var.path.empty() ? std::string("") : _var.path + "_"; + if (has_env_var(_var.path.c_str())) { + return false; + } + const auto prefix = _var.path + "_"; for (char** env = get_environ(); *env != nullptr; ++env) { const std::string env_entry(*env); if (env_entry.size() <= prefix.size()) { @@ -304,14 +304,41 @@ struct Reader { } private: + static bool has_env_var(const char* _name) noexcept { + if (_name == nullptr || *_name == '\0') { + return false; + } +#ifdef _MSC_VER + std::size_t required_size = 0; + return ::getenv_s(&required_size, nullptr, 0, _name) == 0 && + required_size > 0; +#else + return std::getenv(_name) != nullptr; +#endif + } + static std::optional get_value( const InputVarType& _var) noexcept { + if (_var.path.empty()) { + return std::nullopt; + } +#ifdef _MSC_VER + char* env_value = nullptr; + if (::_dupenv_s(&env_value, nullptr, _var.path.c_str()) == 0 && + env_value != nullptr) { + std::string result(env_value); + std::free(env_value); + return result; + } + return std::nullopt; +#else const char* env_value = std::getenv(_var.path.c_str()); if (env_value) { return std::string(env_value); } else { return std::nullopt; } +#endif } }; diff --git a/include/rfl/env/Writer.hpp b/include/rfl/env/Writer.hpp index 23512bb72..d0d505fd4 100644 --- a/include/rfl/env/Writer.hpp +++ b/include/rfl/env/Writer.hpp @@ -56,7 +56,7 @@ class RFL_API Writer { } template - OutputVarType value_as_root(const T& _var) const noexcept { + OutputVarType value_as_root(const T&) const noexcept { static_assert( always_false_v, "Writing basic types to ENV as root variables is not supported."); diff --git a/include/rfl/internal/StringLiteral.hpp b/include/rfl/internal/StringLiteral.hpp index 56a64e108..c8bf5d1e9 100644 --- a/include/rfl/internal/StringLiteral.hpp +++ b/include/rfl/internal/StringLiteral.hpp @@ -1,68 +1,11 @@ #ifndef RFL_INTERNAL_STRINGLITERAL_HPP_ #define RFL_INTERNAL_STRINGLITERAL_HPP_ -#include -#include -#include -#include -#include +#include "../StringLiteral.hpp" namespace rfl::internal { -/// Normal strings cannot be used as template -/// parameters, but this can. This is needed -/// for the parameters names in the NamedTuples. -template -struct StringLiteral { - /// Constrained via template type parameters rather than a requires-fold - /// over decltype of the function parameter pack: the latter crashes - /// clang 21/22 in C++26 mode (llvm/llvm-project#198052, #205000). - template ... Chars> - constexpr StringLiteral(const Chars... _chars) : arr_{_chars..., '\0'} {} - - constexpr StringLiteral(const std::array _arr) : arr_(_arr) {} - - constexpr StringLiteral(const char (&_str)[N]) { - std::copy_n(_str, N, std::data(arr_)); - } - - constexpr StringLiteral(const std::string_view _str) { - std::copy_n(_str.data(), _str.size(), std::data(arr_)); - } - - template - requires(std::is_same_v || std::is_same_v) - explicit constexpr StringLiteral(T _data) { - std::copy_n(_data, N, std::data(arr_)); - } - - /// Returns the value as a string. - std::string str() const { return std::string(string_view()); } - - /// Returns the value as a string. - constexpr std::string_view string_view() const { - return std::string_view(std::data(arr_), N - 1); - } - - static constexpr size_t length = N - 1; - - std::array arr_{}; -}; - -template -constexpr inline bool operator==(const StringLiteral& _first, - const StringLiteral& _second) { - if constexpr (N1 != N2) { - return false; - } - return _first.string_view() == _second.string_view(); -} - -template -constexpr inline bool operator!=(const StringLiteral& _first, - const StringLiteral& _second) { - return !(_first == _second); -} +using rfl::StringLiteral; } // namespace rfl::internal diff --git a/include/rfl/internal/bind_to_tuple.hpp b/include/rfl/internal/bind_to_tuple.hpp index b6a578c34..49e7333d9 100644 --- a/include/rfl/internal/bind_to_tuple.hpp +++ b/include/rfl/internal/bind_to_tuple.hpp @@ -1,6 +1,8 @@ #ifndef RFL_INTERNAL_BIND_TO_TUPLE_HPP_ #define RFL_INTERNAL_BIND_TO_TUPLE_HPP_ +#include + #ifndef REFLECTCPP_USE_CPP26_REFLECTION #include "cpp20/bind_to_tuple.hpp" #else @@ -9,6 +11,15 @@ namespace rfl::internal { +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { +#ifndef REFLECTCPP_USE_CPP26_REFLECTION + return cpp20::apply_to_fields(_t, std::forward(_f)); +#else + return cpp26::apply_to_fields(_t, std::forward(_f)); +#endif +} + template auto bind_to_tuple(T& _t) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION diff --git a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp index 5f3a13926..32a30e737 100644 --- a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp +++ b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp @@ -10,21 +10,15 @@ namespace rfl::internal { -template -auto copy_one_element(const auto& _flattened_tuple) { - const auto name_literal = FieldNames::template name_of<_i>(); - return rfl::make_field< - lit_name_v>>( - std::get<_i>(_flattened_tuple)); -} - template auto copy_flattened_tuple_to_named_tuple(const auto& _flattened_tuple) { constexpr auto size = rfl::tuple_size_v>; return [&](std::integer_sequence) { return make_named_tuple( - copy_one_element(_flattened_tuple)...); + rfl::make_field())>>>( + std::get<_i>(_flattened_tuple))...); }(std::make_integer_sequence()); } diff --git a/include/rfl/internal/cpp20/Result.hpp b/include/rfl/internal/cpp20/Result.hpp index fb436bedb..00436331f 100644 --- a/include/rfl/internal/cpp20/Result.hpp +++ b/include/rfl/internal/cpp20/Result.hpp @@ -2,7 +2,6 @@ #define RFL_INTERNAL_CPP20_RESULT_HPP_ #include -#include #include #include #include @@ -60,7 +59,9 @@ template class Result { static_assert(!std::is_same(), "The result type cannot be Error."); - using TOrErr = std::array; + using TOrErr = + std::array sizeof(Error) ? sizeof(T) : sizeof(Error))>; public: using value_type = T; @@ -555,7 +556,7 @@ class Result { std::is_same()(std::declval())), Error>(), "A function passed to transform_error must return an error."); if (!has_value()) { - return Result{std::invoke(f, std::move(*this).get_err())}; + return Result{std::forward(f)(std::move(*this).get_err())}; } else { return Result{std::move(*this).value()}; } @@ -584,7 +585,7 @@ class Result { std::is_same()(std::declval())), Error>(), "A function passed to transform_error must return an error."); if (!has_value()) { - return Result{std::invoke(f, get_err())}; + return Result{std::forward(f)(get_err())}; } else { return Result{value()}; } @@ -681,7 +682,8 @@ class Result { bool success_; /// The underlying data, can either be T or Error. - alignas(std::max(alignof(T), alignof(Error))) TOrErr t_or_err_; + alignas((alignof(T) > alignof(Error) ? alignof(T) + : alignof(Error))) TOrErr t_or_err_; }; } // namespace rfl::internal::cpp20 diff --git a/include/rfl/internal/cpp20/bind_to_tuple.hpp b/include/rfl/internal/cpp20/bind_to_tuple.hpp index 9733f1dbe..218e34c70 100644 --- a/include/rfl/internal/cpp20/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp20/bind_to_tuple.hpp @@ -5,6 +5,7 @@ #include #include +#include #include #include "../../Tuple.hpp" @@ -16,14 +17,14 @@ namespace rfl::internal::cpp20 { #define RFL_INTERNAL_TUPLE_VIEW_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS( \ n, ...) \ auto& [__VA_ARGS__] = _t; \ - return [](auto&... _refs) { return rfl::make_tuple(&_refs...); }(__VA_ARGS__); + return std::forward(_f)(__VA_ARGS__); // The following boilerplate code has been generated with -// scripts/bind_to_tuple_impl.py -template -auto bind_to_tuple_impl(auto& _t) { +// scripts/bind_to_tuple.py +template +decltype(auto) apply_to_fields_impl(T& _t, F&& _f) { if constexpr (_num_fields == 0) { - return rfl::make_tuple(); + return std::forward(_f)(); } else { if constexpr (_num_fields < 129) { if constexpr (_num_fields < 65) { @@ -4384,9 +4385,16 @@ auto bind_to_tuple_impl(auto& _t) { #undef RFL_INTERNAL_TUPLE_VIEW_IF_YOU_SEE_AN_ERROR_REFER_TO_DOCUMENTATION_ON_C_ARRAYS +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { + return cpp20::apply_to_fields_impl>>( + _t, std::forward(_f)); +} + template auto bind_to_tuple(T& _t) { - return bind_to_tuple_impl>(_t); + return cpp20::apply_to_fields( + _t, [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); } } // namespace rfl::internal::cpp20 diff --git a/include/rfl/internal/cpp20/num_fields.hpp b/include/rfl/internal/cpp20/num_fields.hpp index 3864336e1..b2931518d 100644 --- a/include/rfl/internal/cpp20/num_fields.hpp +++ b/include/rfl/internal/cpp20/num_fields.hpp @@ -98,15 +98,60 @@ struct CountFieldsHelper { } template - static consteval std::size_t count_max_args_in_agg_init() { - static_assert(n <= static_cast(sizeof(T))); - if constexpr (constructible() && !constructible()) { + static consteval std::size_t find_first_constructible() { + if constexpr (constructible()) { return n; + } else if constexpr (n < static_cast(sizeof(T))) { + return find_first_constructible(); } else { - return count_max_args_in_agg_init(); + static_assert(n < static_cast(sizeof(T)), + "Type is not aggregate-constructible; rfl::num_fields " + "requires an aggregate type."); + return 0; } } + template + static consteval std::size_t binary_search_max() { + if constexpr (lo + 1 >= hi) { + return lo; + } else { + constexpr std::size_t mid = lo + (hi - lo) / 2; + if constexpr (constructible()) { + return binary_search_max(); + } else { + return binary_search_max(); + } + } + } + + template + static consteval std::size_t expand_and_search() { + static_assert(lo <= static_cast(sizeof(T))); + constexpr std::size_t max_possible = static_cast(sizeof(T)); + constexpr std::size_t probe = + (step > max_possible - lo) ? (max_possible + 1) : (lo + step); + if constexpr (probe <= max_possible && constructible()) { + return expand_and_search(); + } else if constexpr (probe > max_possible && constructible()) { + static_assert(probe <= max_possible, + "Type is constructible with more arguments than sizeof(T); " + "rfl::num_fields requires an aggregate type."); + return max_possible; + } else { + return binary_search_max(); + } + } + + static consteval std::size_t count_max_args_in_agg_init() { + // Once constructible() holds, constructible() is monotone + // non-increasing for k >= first (every trailing member from `first` onward + // is default-initializable), so exponential + binary search finds the + // exact maximum in O(log N) SFINAE evaluations instead of O(N). + constexpr std::size_t first = find_first_constructible<0>(); + return expand_and_search(); + } + template static consteval std::size_t get_nested_array_size() { if constexpr (size < 1) { diff --git a/include/rfl/internal/cpp26/bind_to_tuple.hpp b/include/rfl/internal/cpp26/bind_to_tuple.hpp index e98f3f2c8..050e7208c 100644 --- a/include/rfl/internal/cpp26/bind_to_tuple.hpp +++ b/include/rfl/internal/cpp26/bind_to_tuple.hpp @@ -8,18 +8,26 @@ #include #include #include +#include +#include #include "../../Tuple.hpp" #include "get_members.hpp" namespace rfl::internal::cpp26 { -template -auto bind_to_tuple(T& _t) { +template +decltype(auto) apply_to_fields(T& _t, F&& _f) { using Type = std::remove_cvref_t; constexpr auto members = std::define_static_array(get_members()); constexpr auto [... indices] = std::make_index_sequence(); - return rfl::make_tuple(&_t.[:members[indices]:]...); + return std::forward(_f)(_t.[:members[indices]:]...); +} + +template +auto bind_to_tuple(T& _t) { + return cpp26::apply_to_fields( + _t, [](auto&... _refs) { return rfl::make_tuple(&_refs...); }); } } // namespace rfl::internal::cpp26 diff --git a/include/rfl/internal/cpp26/get_type_name.hpp b/include/rfl/internal/cpp26/get_type_name.hpp index dbcb50678..97eb82773 100644 --- a/include/rfl/internal/cpp26/get_type_name.hpp +++ b/include/rfl/internal/cpp26/get_type_name.hpp @@ -11,10 +11,10 @@ namespace rfl::internal::cpp26 { template -consteval auto get_type_name() { +consteval auto get_type_name_str_view() { using Type = std::remove_cvref_t; if constexpr (std::is_pointer_v) { - return get_type_name>(); + return get_type_name_str_view>(); } else { // TODO: Is there a way to get the name of the type without using // compiler-specific extensions? @@ -22,9 +22,7 @@ consteval auto get_type_name() { constexpr auto display_string = std::meta::display_string_of(^^Type); constexpr auto drop_last_char = display_string.substr(0, display_string.size() - 1); - constexpr auto name = - drop_last_char.substr(drop_last_char.find("{aka ") + 5); - return StringLiteral(name); + return drop_last_char.substr(drop_last_char.find("{aka ") + 5); #else static_assert(false, "You are using an unsupported compiler. Please use GCC or " @@ -32,6 +30,12 @@ consteval auto get_type_name() { #endif } } + +template +consteval auto get_type_name() { + constexpr auto name = get_type_name_str_view(); + return StringLiteral(name); +} } // namespace rfl::internal::cpp26 #endif diff --git a/include/rfl/internal/enum_name_transform_v.hpp b/include/rfl/internal/enum_name_transform_v.hpp new file mode 100644 index 000000000..7c4249bdd --- /dev/null +++ b/include/rfl/internal/enum_name_transform_v.hpp @@ -0,0 +1,49 @@ +#ifndef RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ +#define RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ + +#include + +#include "../Processors.hpp" +#include "../TransformEnumNames.hpp" + +namespace rfl::internal { + +template +struct enum_name_transform_from_processors { + static constexpr EnumNameTransform value = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform value = _t; +}; + +template <> +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform value = EnumNameTransform::none; +}; + +template +struct enum_name_transform_from_processors> { + static constexpr EnumNameTransform head_val = + enum_name_transform_from_processors< + std::remove_cvref_t>>::value; + static constexpr EnumNameTransform tail_val = + enum_name_transform_from_processors>::value; + static_assert(head_val == EnumNameTransform::none || + tail_val == EnumNameTransform::none || + head_val == tail_val, + "Conflicting rfl::TransformEnumNames processors cannot be " + "combined."); + static constexpr EnumNameTransform value = + head_val != EnumNameTransform::none ? head_val : tail_val; +}; + +template +inline constexpr EnumNameTransform enum_name_transform_v = + enum_name_transform_from_processors< + std::remove_cvref_t>>::value; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_ENUM_NAME_TRANSFORM_V_HPP_ diff --git a/include/rfl/internal/enums/cpp20/from_string.hpp b/include/rfl/internal/enums/cpp20/from_string.hpp index b14315964..1d1cec7de 100644 --- a/include/rfl/internal/enums/cpp20/from_string.hpp +++ b/include/rfl/internal/enums/cpp20/from_string.hpp @@ -3,15 +3,14 @@ #ifndef REFLECTCPP_USE_CPP26_REFLECTION -#include -#include +#include #include "enchantum.hpp" // NOLINT(unused-includes) namespace rfl::internal::enums::cpp20 { template -auto from_string(const std::string& _str) { +auto from_string(const std::string_view _str) { return enchantum::cast(_str); } diff --git a/include/rfl/internal/enums/cpp26/from_string.hpp b/include/rfl/internal/enums/cpp26/from_string.hpp index 919be47c6..1f4698529 100644 --- a/include/rfl/internal/enums/cpp26/from_string.hpp +++ b/include/rfl/internal/enums/cpp26/from_string.hpp @@ -5,13 +5,13 @@ #include #include -#include +#include #include namespace rfl::internal::enums::cpp26 { template -std::optional from_string(const std::string& _str) { +std::optional from_string(const std::string_view _str) { template for (constexpr auto e : std::define_static_array( std::meta::enumerators_of(^^EnumType))) { if (_str == std::meta::identifier_of(e)) { diff --git a/include/rfl/internal/enums/from_string.hpp b/include/rfl/internal/enums/from_string.hpp index 160363283..c966f6d36 100644 --- a/include/rfl/internal/enums/from_string.hpp +++ b/include/rfl/internal/enums/from_string.hpp @@ -1,6 +1,8 @@ #ifndef RFL_INTERNAL_ENUMS_FROM_STRING_HPP_ #define RFL_INTERNAL_ENUMS_FROM_STRING_HPP_ +#include + #ifndef REFLECTCPP_USE_CPP26_REFLECTION #include "cpp20/from_string.hpp" #else @@ -10,7 +12,7 @@ namespace rfl::internal::enums { template -auto from_string(const std::string& _str) { +auto from_string(const std::string_view _str) { #ifndef REFLECTCPP_USE_CPP26_REFLECTION return cpp20::from_string(_str); #else diff --git a/include/rfl/internal/find_index.hpp b/include/rfl/internal/find_index.hpp index 04c524e7d..c962ae5e6 100644 --- a/include/rfl/internal/find_index.hpp +++ b/include/rfl/internal/find_index.hpp @@ -25,7 +25,7 @@ constexpr auto operator|(const FieldWrapper& _f1, template constexpr auto find_matching_field(const Head& _head, const Tail&... _tail) { return (_head | ... | _tail); -}; +} template constexpr auto wrap_fields(std::integer_sequence) { diff --git a/include/rfl/internal/get_type_name.hpp b/include/rfl/internal/get_type_name.hpp index 9596ad231..c5299fbe7 100644 --- a/include/rfl/internal/get_type_name.hpp +++ b/include/rfl/internal/get_type_name.hpp @@ -20,7 +20,11 @@ consteval auto get_type_name() { template consteval auto get_type_name_str_view() { - return get_type_name().string_view(); +#ifndef REFLECTCPP_USE_CPP26_REFLECTION + return cpp20::get_type_name_str_view(); +#else + return cpp26::get_type_name_str_view(); +#endif } } // namespace rfl::internal diff --git a/include/rfl/internal/has_default_val_v.hpp b/include/rfl/internal/has_default_val_v.hpp index 1d19ef96b..c47ca0cae 100644 --- a/include/rfl/internal/has_default_val_v.hpp +++ b/include/rfl/internal/has_default_val_v.hpp @@ -2,44 +2,85 @@ #define RFL_HASDEFAULTVALV_HPP_ #include +#include #include +#include -#include "../NamedTuple.hpp" -#include "../named_tuple_t.hpp" +#include "bind_to_tuple.hpp" #include "is_default_val_v.hpp" +#include "is_field.hpp" +#include "is_flatten_field.hpp" -namespace rfl::internal { +namespace rfl { -template -struct HasDefaultVal; +template +class NamedTuple; + +namespace internal { template struct HasDefaultVal { static constexpr bool value = false; }; +// NamedTupleParser invokes has_default_val_v on view NamedTuples whose fields +// hold pointers to the original members (e.g. Field*>), so +// this specialization intentionally strips one pointer level. template struct HasDefaultVal> { static constexpr bool value = (false || ... || - is_default_val_v< - std::remove_cvref_t>>); + is_default_val>>::value); }; template - requires(std::is_class_v && std::is_aggregate_v) -struct HasDefaultVal : HasDefaultVal> {}; +struct is_named_tuple_spec : std::false_type {}; + +template +struct is_named_tuple_spec> : std::true_type {}; + +template +constexpr bool has_default_val_field() { + using U = std::remove_cvref_t; + if constexpr (is_field::value) { + return is_default_val>::value; + } else if constexpr (is_flatten_field::value) { + return HasDefaultVal< + std::remove_cvref_t>>::value; + } else { + return is_default_val::value; + } +} + +struct HasDefaultValVisitor { + template + constexpr auto operator()(Fields&...) const noexcept + -> std::bool_constant<(false || ... || + has_default_val_field())> { + return {}; + } +}; + +template + requires(!is_named_tuple_spec::value && std::is_class_v && + std::is_aggregate_v) +struct HasDefaultVal { + static constexpr bool value = decltype(rfl::internal::apply_to_fields( + std::declval(), HasDefaultValVisitor{}))::value; +}; -template +template struct HasDefaultVal> : HasDefaultVal> { }; -template +template struct HasDefaultVal : HasDefaultVal> {}; template constexpr bool has_default_val_v = HasDefaultVal>::value; -} // namespace rfl::internal +} // namespace internal +} // namespace rfl #endif diff --git a/include/rfl/internal/integer_bounds_v.hpp b/include/rfl/internal/integer_bounds_v.hpp new file mode 100644 index 000000000..45651d293 --- /dev/null +++ b/include/rfl/internal/integer_bounds_v.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_INTEGER_BOUNDS_V_HPP_ +#define RFL_INTERNAL_INTEGER_BOUNDS_V_HPP_ + +#include + +#include "../IntegerBounds.hpp" +#include "../Processors.hpp" + +namespace rfl::internal { + +template +struct integer_bounds : std::false_type {}; + +template <> +struct integer_bounds : std::true_type {}; + +template +struct integer_bounds> + : std::bool_constant< + (integer_bounds>::value || ...)> {}; + +template +inline constexpr bool integer_bounds_v = + integer_bounds>>::value; + +} // namespace rfl::internal + +#endif // RFL_INTERNAL_INTEGER_BOUNDS_V_HPP_ diff --git a/include/rfl/internal/move_from_tuple.hpp b/include/rfl/internal/move_from_tuple.hpp index c5edf9043..3855f7741 100644 --- a/include/rfl/internal/move_from_tuple.hpp +++ b/include/rfl/internal/move_from_tuple.hpp @@ -44,7 +44,7 @@ struct IndptrHelper { static constexpr auto indptr_ = ArrayType{_head, _tail...}; template - consteval auto operator+(const IndptrHelper<_is...>& _other) const { + consteval auto operator+(const IndptrHelper<_is...>&) const { constexpr auto last = std::get(indptr_); return IndptrHelper<_head, _tail..., (last + _is)...>{}; } diff --git a/include/rfl/internal/nth_element.hpp b/include/rfl/internal/nth_element.hpp index 281e5968c..c5c5c9c77 100644 --- a/include/rfl/internal/nth_element.hpp +++ b/include/rfl/internal/nth_element.hpp @@ -23,7 +23,7 @@ constexpr auto operator|(const ElementWrapper& _e1, template constexpr auto find_matching_element(const Head& _head, const Tail&... _tail) { return (_head | ... | _tail); -}; +} template constexpr auto wrap_elements(Ts... _ts, std::integer_sequence) { diff --git a/include/rfl/internal/strings/utf8_conversions.hpp b/include/rfl/internal/strings/utf8_conversions.hpp index dc24923f4..7be5e57e5 100644 --- a/include/rfl/internal/strings/utf8_conversions.hpp +++ b/include/rfl/internal/strings/utf8_conversions.hpp @@ -46,7 +46,8 @@ inline std::optional decode_utf8(const std::string& _str) { return std::nullopt; // truncated multi-byte sequence } for (int k = 1; k <= extra; ++k) { - const auto cc = static_cast(_str[i + k]); + const auto cc = + static_cast(_str[i + static_cast(k)]); if ((cc >> 6) != 0x2) { return std::nullopt; // bad continuation byte } diff --git a/include/rfl/internal/variants_as_one_of_v.hpp b/include/rfl/internal/variants_as_one_of_v.hpp new file mode 100644 index 000000000..c03d42f20 --- /dev/null +++ b/include/rfl/internal/variants_as_one_of_v.hpp @@ -0,0 +1,62 @@ +#ifndef RFL_INTERNAL_VARIANTSASONEOF_HPP_ +#define RFL_INTERNAL_VARIANTSASONEOF_HPP_ + +#include + +#include "../Processors.hpp" +#include "../VariantsAsOneOf.hpp" + +namespace rfl::internal { + +template +struct variants_as_one_of : std::false_type {}; + +template <> +struct variants_as_one_of : std::true_type {}; + +template +struct variants_as_one_of> + : std::bool_constant< + (variants_as_one_of>::value || ...)> {}; + +template +inline constexpr bool variants_as_one_of_v = + variants_as_one_of>::value; + +template +struct concat_processors; + +template +struct concat_processors, Processors> { + using type = Processors; +}; + +template +struct remove_variants_as_one_of { + using type = Processors; +}; + +template <> +struct remove_variants_as_one_of { + using type = Processors<>; +}; + +template <> +struct remove_variants_as_one_of> { + using type = Processors<>; +}; + +template +struct remove_variants_as_one_of> { + using type = typename concat_processors< + typename remove_variants_as_one_of>::type, + typename remove_variants_as_one_of>::type>::type; +}; + +template +using remove_variants_as_one_of_t = + typename remove_variants_as_one_of>::type; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index cac6b0e23..a42bd82fa 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -3,6 +3,7 @@ #include "../rfl.hpp" #include "json/Parser.hpp" +#include "json/Raw.hpp" #include "json/Reader.hpp" #include "json/Writer.hpp" #include "json/load.hpp" diff --git a/include/rfl/json/Raw.hpp b/include/rfl/json/Raw.hpp new file mode 100644 index 000000000..7543c1bad --- /dev/null +++ b/include/rfl/json/Raw.hpp @@ -0,0 +1,161 @@ +#ifndef RFL_JSON_RAW_HPP_ +#define RFL_JSON_RAW_HPP_ + +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../common.hpp" +#include "../generic/Reader.hpp" +#include "../generic/Writer.hpp" +#include "../parsing/AreReaderAndWriter.hpp" +#include "../parsing/Parent.hpp" +#include "../parsing/Parser.hpp" +#include "../parsing/schema/Type.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl::json { + +/// Holds a raw JSON value for passthrough serialization and deserialization +/// without converting into intermediate C++ structures. +/// +/// Note on reading vs. writing: +/// - Writing emits the stored JSON text verbatim via `yyjson_mut_rawncpy` +/// without re-parsing. Construct with `Raw::from_string()` so malformed or +/// non-RFC-8259 JSON is rejected up front, or use `Raw::from_trusted_string()` +/// only for already-validated JSON text (e.g., output of `rfl::json::write`). +/// - Reading captures the parsed yyjson subtree via `yyjson_val_write_opts` with +/// strict RFC 8259 formatting (flag 0), which canonicalizes whitespace and +/// rejects non-standard values such as `NaN`/`Infinity`. Pass +/// `YYJSON_READ_BIGNUM_AS_RAW` to `rfl::json::read` if you need integers +/// wider than 64 bits preserved verbatim. +class RFL_API Raw { + public: + Raw() = default; + + /// Validates that `_str` contains a single strict RFC 8259 JSON value and + /// constructs a `Raw` holding `_str` verbatim. + static Result from_string(std::string_view _str); + + /// Constructs a `Raw` from pre-validated JSON text without re-parsing. + /// Empty input becomes `"null"`. Caller must guarantee `_value` is valid + /// RFC 8259 JSON with no embedded NUL bytes. + static Raw from_trusted_string(const std::string_view _value) { + return Raw(_value.empty() ? std::string("null") : std::string(_value)); + } + + template + requires std::is_same_v + static Raw from_trusted_string(T&& _value) { + return Raw(_value.empty() ? std::string("null") : std::move(_value)); + } + + const std::string& str() const noexcept { return value_; } + + const std::string& value() const noexcept { return value_; } + + const std::string& get() const noexcept { return value_; } + + const std::string& operator*() const noexcept { return value_; } + + const std::string& operator()() const noexcept { return value_; } + + const char* c_str() const noexcept { return value_.c_str(); } + + bool operator==(const Raw&) const = default; + + static Result from_json_obj(const Reader::YYJSONInputVar& _var); + + /// Parses the stored raw JSON text into an `rfl::Generic`. + Result to_generic() const; + + /// Serializes an `rfl::Generic` into an `rfl::json::Raw`. + static Result from_generic(const Generic& _g) noexcept; + + private: + explicit Raw(std::string _value) : value_(std::move(_value)) {} + + std::string value_{"null"}; +}; + +} // namespace rfl::json + +namespace rfl::parsing { + +template + requires AreReaderAndWriter +struct Parser { + static_assert( + always_false_v, + "rfl::json::Raw is only supported with rfl::json and rfl::Generic."); +}; + +template + requires AreReaderAndWriter +struct Parser { + public: + using InputVarType = typename json::Reader::InputVarType; + using ParentType = Parent; + + static Result read(const json::Reader& _r, + const InputVarType& _var) noexcept { + return _r.template use_custom_constructor(_var); + } + + template + static void write(const json::Writer& _w, const json::Raw& _raw, + const P& _parent) { + using Type = std::remove_cvref_t

; + if constexpr (std::is_same_v) { + _w.add_raw_to_array(_raw.str(), _parent.arr_); + } else if constexpr (std::is_same_v) { + _w.add_raw_to_object(_parent.name_, _raw.str(), _parent.obj_); + } else if constexpr (std::is_same_v) { + _w.raw_as_root(_raw.str()); + } else { + static_assert(always_false_v, "Unsupported parent type."); + } + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +template + requires AreReaderAndWriter +struct Parser { + public: + using InputVarType = typename generic::Reader::InputVarType; + + static Result read(const generic::Reader&, + const InputVarType& _var) noexcept { + return json::Raw::from_generic(_var); + } + + template + static void write(const generic::Writer& _w, const json::Raw& _raw, + const P& _parent) { + const auto g = _raw.to_generic().value(); + Parser::write( + _w, g, _parent); + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index fe4c576b3..9ea6d340e 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -185,15 +185,23 @@ struct Reader { return static_cast(value); } else if constexpr (std::is_integral>()) { - if (!yyjson_is_int(_var.val_)) { + using Target = std::remove_cvref_t; + if (yyjson_is_uint(_var.val_)) { + const auto value = yyjson_get_uint(_var.val_); + if (value > static_cast(std::numeric_limits::max())) { + return error("Integer is out of range for the target type."); + } + return static_cast(value); + } + if (!yyjson_is_sint(_var.val_)) { return error("Could not cast to int."); } const auto value = yyjson_get_sint(_var.val_); - if (value < std::numeric_limits>::min() || - value > std::numeric_limits>::max()) { + if (value < std::numeric_limits::min() || + value > std::numeric_limits::max()) { return error("Integer is out of range for the target type."); } - return static_cast(value); + return static_cast(value); } else { static_assert(rfl::always_false_v, "Unsupported type."); diff --git a/include/rfl/json/Writer.hpp b/include/rfl/json/Writer.hpp index 7530ea98c..9748279a5 100644 --- a/include/rfl/json/Writer.hpp +++ b/include/rfl/json/Writer.hpp @@ -81,6 +81,12 @@ class RFL_API Writer { /// @return An output variable representing null OutputVarType null_as_root() const noexcept; + /// Creates a raw JSON value as the root element of the output. + /// Emits null if _str is empty. + /// @param _str The raw JSON text to write + /// @return An output variable representing the raw JSON value + OutputVarType raw_as_root(const std::string_view& _str) const noexcept; + /// Creates a value as the root element of the output. /// Supports basic types like strings, numbers, and booleans. /// @tparam T The type of the value to serialize @@ -177,6 +183,26 @@ class RFL_API Writer { OutputVarType add_null_to_object(const std::string_view& _name, OutputObjectType* _parent) const; + /// Adds a raw JSON value to a parent array. + /// Emits null if _str is empty. + /// @param _str The raw JSON text to add + /// @param _parent Pointer to the parent array to add to + /// @return An output variable representing the raw JSON value + /// @throws std::runtime_error if the value cannot be added + OutputVarType add_raw_to_array(const std::string_view& _str, + OutputArrayType* _parent) const; + + /// Adds a raw JSON value to a parent object with the specified field name. + /// Emits null if _str is empty. + /// @param _name The name of the field in the parent object + /// @param _str The raw JSON text to add + /// @param _parent Pointer to the parent object to add to + /// @return An output variable representing the raw JSON value + /// @throws std::runtime_error if the field cannot be added + OutputVarType add_raw_to_object(const std::string_view& _name, + const std::string_view& _str, + OutputObjectType* _parent) const; + /// Finalizes a JSON array after all elements have been added. /// This is a no-op for yyjson as arrays don't need explicit finalization. /// @param Pointer to the array (unused) diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index ad3e47b1e..94d7ef06a 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -18,6 +18,61 @@ namespace rfl { namespace json { +/// Stop after parsing the first JSON value instead of issuing an error if +/// trailing content follows. +inline constexpr yyjson_read_flag stop_when_done = YYJSON_READ_STOP_WHEN_DONE; + +/// Allow a single trailing comma at the end of an object or array. +inline constexpr yyjson_read_flag allow_trailing_commas = + YYJSON_READ_ALLOW_TRAILING_COMMAS; + +/// Allow C-style single-line (//) and multi-line (/* */) comments. +inline constexpr yyjson_read_flag allow_comments = YYJSON_READ_ALLOW_COMMENTS; + +/// Allow Inf/NaN numbers and literals (e.g. 1e999, NaN, inf, -Infinity). +inline constexpr yyjson_read_flag read_allow_inf_and_nan = + YYJSON_READ_ALLOW_INF_AND_NAN; + +/// Allow invalid UTF-8 byte sequences when parsing string values. +inline constexpr yyjson_read_flag read_allow_invalid_unicode = + YYJSON_READ_ALLOW_INVALID_UNICODE; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000B00 +/// Allow and skip a leading UTF-8 BOM before parsing. +/// Requires yyjson >= 0.11.0. +inline constexpr yyjson_read_flag allow_bom = YYJSON_READ_ALLOW_BOM; +#endif + +/// Convenience flag for JSONC (comments and trailing commas). +inline constexpr yyjson_read_flag jsonc = + allow_comments | allow_trailing_commas; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 +/// Allow extended number formats (hexadecimal, leading/trailing decimal point, +/// leading plus sign). Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_number = + YYJSON_READ_ALLOW_EXT_NUMBER; + +/// Allow extended escape sequences in strings. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_escape = + YYJSON_READ_ALLOW_EXT_ESCAPE; + +/// Allow extended whitespace characters. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_whitespace = + YYJSON_READ_ALLOW_EXT_WHITESPACE; + +/// Allow strings enclosed in single quotes. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_single_quoted_str = + YYJSON_READ_ALLOW_SINGLE_QUOTED_STR; + +/// Allow unquoted object keys. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_unquoted_key = + YYJSON_READ_ALLOW_UNQUOTED_KEY; + +/// Convenience flag for JSON5. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag json5 = YYJSON_READ_JSON5; +#endif + using InputObjectType = typename Reader::InputObjectType; using InputVarType = typename Reader::InputVarType; diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp index b032c83b2..3416e335c 100644 --- a/include/rfl/json/schema/Type.hpp +++ b/include/rfl/json/schema/Type.hpp @@ -1,6 +1,7 @@ #ifndef RFL_JSON_SCHEMA_TYPE_HPP_ #define RFL_JSON_SCHEMA_TYPE_HPP_ +#include #include #include #include @@ -33,6 +34,8 @@ struct Type { struct Integer { Literal<"integer"> type{}; rfl::Flatten annotations{}; + std::optional minimum{}; + std::optional maximum{}; }; struct Number { diff --git a/include/rfl/json/write.hpp b/include/rfl/json/write.hpp index 88e762aff..c3a6fa7ca 100644 --- a/include/rfl/json/write.hpp +++ b/include/rfl/json/write.hpp @@ -1,7 +1,6 @@ #ifndef RFL_JSON_WRITE_HPP_ #define RFL_JSON_WRITE_HPP_ -#include #if __has_include() #include #else @@ -19,9 +18,41 @@ namespace rfl { namespace json { -/// Convenient alias for the YYJSON pretty flag +/// Write JSON pretty-printed with 4-space indentation. inline constexpr yyjson_write_flag pretty = YYJSON_WRITE_PRETTY; +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000700 +/// Write JSON pretty-printed with 2-space indentation. +/// Overrides `pretty` if both are set. Requires yyjson >= 0.7.0. +inline constexpr yyjson_write_flag pretty_two_spaces = + YYJSON_WRITE_PRETTY_TWO_SPACES; +#endif + +/// Escape non-ASCII Unicode characters as `\uXXXX` for ASCII-only output. +inline constexpr yyjson_write_flag escape_unicode = YYJSON_WRITE_ESCAPE_UNICODE; + +/// Escape forward slashes `/` as `\/`. +inline constexpr yyjson_write_flag escape_slashes = YYJSON_WRITE_ESCAPE_SLASHES; + +/// Write Inf and NaN numbers as `Infinity` and `NaN` literals (non-standard). +inline constexpr yyjson_write_flag write_allow_inf_and_nan = + YYJSON_WRITE_ALLOW_INF_AND_NAN; + +/// Write Inf and NaN numbers as `null`. +/// Overrides `write_allow_inf_and_nan` if both are set. +inline constexpr yyjson_write_flag inf_and_nan_as_null = + YYJSON_WRITE_INF_AND_NAN_AS_NULL; + +/// Allow invalid UTF-8 byte sequences when encoding string values. +inline constexpr yyjson_write_flag write_allow_invalid_unicode = + YYJSON_WRITE_ALLOW_INVALID_UNICODE; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 +/// Append a trailing newline `\n` at the end of the JSON output. +/// Requires yyjson >= 0.9.0. +inline constexpr yyjson_write_flag newline_at_end = YYJSON_WRITE_NEWLINE_AT_END; +#endif + /// Returns a JSON string representation of the object. /// Uses compile-time reflection to serialize a C++ object to JSON format. /// @tparam Ps Processors to apply during serialization (transforms the data) diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 7e586b749..3468d4679 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -11,6 +11,7 @@ #include "../Variant.hpp" #include "../internal/no_duplicate_field_names.hpp" #include "../internal/to_ptr_field.hpp" +#include "../internal/variants_as_one_of_v.hpp" #include "../make_named_tuple.hpp" #include "FieldVariantReader.hpp" #include "Parser_base.hpp" @@ -97,7 +98,8 @@ struct FieldVariantParser { std::map* _definitions) { return schema::Type{schema::Type::AnyOf{ .types_ = std::vector( - {one_field_to_type(_definitions)...})}}; + {one_field_to_type(_definitions)...}), + .mutually_exclusive_ = internal::variants_as_one_of_v}}; } private: diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index b7454b1a7..bd144c32d 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -12,6 +12,7 @@ #include "../internal/is_array.hpp" #include "../internal/nth_element_t.hpp" #include "Parser_base.hpp" +#include "wrap_error.hpp" namespace rfl::parsing { @@ -80,11 +81,12 @@ class FieldVariantReader { const auto to_variant = [](ValueType&& _val) { return rfl::Variant(FieldType(std::move(_val))); }; - const auto embellish_error = [&](const Error& _e) { + const auto embellish_error = [&](Error _e) { std::stringstream stream; stream << "Could not parse rfl::Variant with field '" - << std::string(_disc_value) << "': " << _e.what(); - return Error(stream.str()); + << std::string(_disc_value) << "': "; + return wrap_error(stream.str(), std::string(_disc_value), + std::move(_e)); }; *field_variant_ = Parser::read(*r_, _var) .transform(to_variant) diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index fe1e8ffdc..ac26baf41 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -10,6 +10,7 @@ #include "../Result.hpp" #include "../always_false.hpp" #include "../internal/has_reflection_type_v.hpp" +#include "../internal/is_validator.hpp" #include "Parser_base.hpp" #include "wrap_error.hpp" @@ -65,8 +66,10 @@ class MapReader { } else { static_assert(always_false_v, "Unsupported type"); } - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while parsing map key."); } } @@ -75,12 +78,28 @@ class MapReader { "Expected an rvalue"); const auto to_pair = [&](auto&& _key) -> Result> { - try { - using K = decltype(_key); - return std::make_pair(KeyType(std::forward(_key)), - std::move(_pair.second)); - } catch (std::exception& e) { - return error(e.what()); + using K = decltype(_key); + if constexpr (internal::is_validator_v) { + try { + return KeyType::from_value(std::forward(_key)) + .transform([&](KeyType&& _validated) { + return std::make_pair(std::move(_validated), + std::move(_pair.second)); + }); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception while constructing validated map key."); + } + } else { + try { + return std::make_pair(KeyType(std::forward(_key)), + std::move(_pair.second)); + } catch (const std::exception& e) { + return error(e.what()); + } catch (...) { + return error("Unknown exception while constructing map key."); + } } }; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..2dd492d90 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -2,12 +2,18 @@ #define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ #include +#include #include #include +#include #include +#include +#include #include #include +#include +#include "../Generic.hpp" #include "../NamedTuple.hpp" #include "../Result.hpp" #include "../internal/always_inline.hpp" @@ -78,6 +84,252 @@ concept CanEmitDefault = namespace rfl::parsing { +template +struct is_std_optional_for_default : std::false_type {}; + +template +struct is_std_optional_for_default> : std::true_type {}; + +template +inline constexpr bool is_plain_integer_for_default_v = + std::is_integral_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v; + +/// Fast-path conversion of a scalar or optional-scalar default value to +/// `rfl::Generic` for schema emission, matching `rfl::generic::Writer::to_generic` +/// semantics without instantiating `rfl::to_generic` / +/// `rfl::generic::Writer`. Complex types fall back to `rfl::to_generic`. +template +inline Generic to_default_generic(const U& _val) { + using T = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return Generic(_val); + } else if constexpr (is_plain_integer_for_default_v) { + return Generic(static_cast(_val)); + } else if constexpr (std::is_floating_point_v) { + return Generic(static_cast(_val)); + } else if constexpr (std::is_same_v) { + return Generic(_val); + } else if constexpr (is_std_optional_for_default::value) { + if (_val.has_value()) { + return to_default_generic(*_val); + } + return Generic(); + } else { + return rfl::to_generic(_val); + } +} + +/// Sets the default value of the DefaultVal node in `_schema`. +inline void set_schema_default_value(Generic _default, schema::Type* _schema) { + _schema->variant_.visit([&](auto& _s) { + if constexpr (std::is_same_v, + schema::Type::DefaultVal>) { + _s.default_value_ = std::move(_default); + } + }); +} + +/// Free per-field serialization helper parameterized only by ValueType (never +/// the enclosing NamedTuple's FieldTypes... pack). +template +void write_named_tuple_field(const W& _w, const std::string_view _name, + const ValueType& _value, + OutputObjectOrArrayType* _ptr) { + using ParentType = Parent; + const auto make_parent = [](const std::string_view _n, + OutputObjectOrArrayType* _p) { + if constexpr (_no_field_names) { + return typename ParentType::Array{_p}; + } else { + return typename ParentType::Object{_n, _p}; + } + }; + if constexpr (internal::is_extra_fields_v) { + for (const auto& [k, v] : *_value) { + const auto new_parent = make_parent(k, _ptr); + Parser, ProcessorsType>::write( + _w, v, new_parent); + } + } else if constexpr (!_all_required && !_no_field_names && + !is_required()) { + const auto new_parent = make_parent(_name, _ptr); + if (!is_empty(_value)) { + if constexpr (internal::is_attribute_v) { + Parser::write( + _w, _value, new_parent.as_attribute()); + } else { + Parser::write(_w, _value, new_parent); + } + } + } else { + const auto new_parent = make_parent(_name, _ptr); + if constexpr (internal::is_attribute_v) { + Parser::write(_w, _value, + new_parent.as_attribute()); + } else { + Parser::write(_w, _value, new_parent); + } + } +} + +/// Extracts a pointer to a view slot for schema default inspection. +/// Pointer slots (including `T*` and C-array pointers `T (*)[N]`) are returned +/// directly without dereferencing; non-pointer processor-added slots (such as +/// `rfl::AddStructName`'s `rfl::Literal<...>`) return `nullptr`. +template +RFL_ALWAYS_INLINE auto extract_schema_field_ptr(const SlotT& _slot) noexcept { + if constexpr (std::is_pointer_v) { + return _slot; + } else { + return static_cast(nullptr); + } +} + +/// Free per-field schema helper parameterized only by field type U and its +/// view-slot pointer type (never the enclosing NamedTuple's FieldTypes... +/// pack). Deduces `FieldValPtrT` independently of `U` so both raw C-array +/// pointers (`T (*)[N]` vs `rfl::internal::Array`) and non-pointer +/// processor-added slots (`const void*` / `nullptr`) work cleanly. +template +void build_named_tuple_field_schema( + std::map* _definitions, SchemaType* _schema, + const std::string_view _name, const FieldValPtrT _field_val) noexcept { + using PtrT = std::remove_cvref_t; + if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { + auto s = Parser::to_schema(_definitions); + if constexpr (!std::is_same_v && + !std::is_same_v && + !std::is_same_v && + internal::CanEmitDefault) { + if (_field_val != nullptr) { + set_schema_default_value( + to_default_generic( + internal::get_default_val(*_field_val).get()), + &s); + } + } + if constexpr (_no_field_names) { + _schema->types_.emplace_back(std::move(s)); + } else { + _schema->types_[std::string(_name)] = std::move(s); + } + } +} + +/// Whether a missing rfl::DefaultVal field can be value-initialized. Only +/// an rfl::NamedTuple does this at runtime, and it cannot have const fields, +/// so const fields of structs need no instantiation. +template +constexpr bool can_value_initialize_default_val() { + using T = typename internal::default_val_t::Type; + return !std::is_const_v && std::is_default_constructible_v && + std::is_default_constructible_v; +} + +/// Free per-field missing-field handler parameterized only by FieldSlotType +/// (never the enclosing NamedTuple's FieldTypes... pack). +/// Precondition: `_is_set_ptr` is non-null whenever `_defaults_constructed` is +/// false (the uninitialized-memory read path). +template +RFL_ALWAYS_INLINE void handle_missing_named_tuple_field( + const std::string_view _name, const bool _is_found, + const FieldSlotType& _field_slot, bool* _is_set_ptr, + FieldErrors* _errors, + const bool _value_initialize_default_vals) noexcept { + using SlotT = std::remove_cvref_t; + using ValueType = std::remove_reference_t>; + constexpr bool is_default_val_field = internal::is_default_val_v; + constexpr bool is_required_field = + !is_default_val_field && !internal::is_extra_fields_v && + (_all_required || is_required()); + + // When the struct was default-constructed, missing optional or DefaultVal + // fields already hold their default values, so nothing is needed. + if constexpr (_defaults_constructed && !is_required_field) { + return; + } else { + if (should_stop_on_field_error(*_errors)) return; + if (!_is_found) { + if constexpr (std::is_pointer_v && !_defaults_constructed && + is_default_val_field) { + if constexpr (can_value_initialize_default_val()) { + if (_value_initialize_default_vals) { + // The value's constructor can throw, for instance a Validator + // whose zero value is invalid. + try { + ::new (_field_slot) ValueType(); + } catch (const std::exception& e) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } catch (...) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: unknown exception.")); + return; + } + *_is_set_ptr = true; + return; + } + } + } + + if constexpr (is_required_field || + (is_default_val_field && !_defaults_constructed)) { + std::stringstream stream; + stream << "Field named '" << std::string(_name) << "' not found."; + _errors->emplace_back( + make_nested_error(std::string(_name), stream.str())); + return; + } + + if constexpr (std::is_pointer_v && !_defaults_constructed && + !is_required_field && !is_default_val_field) { + using NonConstT = std::remove_const_t; + const auto ptr = const_cast(_field_slot); + if constexpr (std::is_nothrow_default_constructible_v) { + ::new (ptr) NonConstT(); + } else { + // The default value can throw, for instance a Validator whose + // default value is invalid. + try { + ::new (ptr) NonConstT(); + } catch (const std::exception& e) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } catch (...) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: unknown exception.")); + return; + } + } + *_is_set_ptr = true; + } + } + } +} + template requires AreReaderAndWriter> @@ -246,83 +498,39 @@ struct NamedTupleParser { } private: - template - static void add_field_to_object(const W& _w, - const NamedTuple& _tup, - OutputObjectOrArrayType* _ptr) { - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - using ValueType = std::remove_cvref_t; - const auto value = rfl::get<_i>(_tup); - if constexpr (internal::is_extra_fields_v) { - for (const auto& [k, v] : *value) { - const auto new_parent = make_parent(k, _ptr); - Parser, ProcessorsType>::write( - _w, v, new_parent); - } - } else if constexpr (!_all_required && !_no_field_names && - !is_required()) { - constexpr auto name = FieldType::name_.string_view(); - const auto new_parent = make_parent(name, _ptr); - if (!is_empty(value)) { - if constexpr (internal::is_attribute_v) { - Parser::write( - _w, value, new_parent.as_attribute()); - } else { - Parser::write(_w, value, new_parent); - } - } - } else { - constexpr auto name = FieldType::name_.string_view(); - const auto new_parent = make_parent(name, _ptr); - if constexpr (internal::is_attribute_v) { - Parser::write( - _w, value, new_parent.as_attribute()); - } else { - Parser::write(_w, value, new_parent); - } - } - } - - template - static void add_field_to_schema( - std::map* _definitions, - SchemaType* _schema, - View* _view) noexcept { - using F = internal::nth_element_t<_i, FieldTypes...>; - using U = std::remove_cvref_t; - if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { - // Add default value here - auto s = Parser::to_schema(_definitions); - if constexpr (!std::is_same_v && internal::CanEmitDefault) { - s.variant_.visit([&](auto& value) { - if constexpr (std::is_same_v, - schema::Type::DefaultVal>) { - value.default_value_ = - rfl::to_generic((*rfl::get<_i>(*_view)).get()); - } - }); - } - if constexpr (_no_field_names) { - _schema->types_.emplace_back(std::move(s)); - } else { - _schema->types_[std::string(F::name())] = std::move(s); - } - } - }; - template static void build_object(const W& _w, const NamedTuple& _tup, OutputObjectOrArrayType* _ptr, std::integer_sequence) { - (add_field_to_object<_is>(_w, _tup, _ptr), ...); + (write_named_tuple_field( + _w, internal::nth_element_t<_is, FieldTypes...>::name_.string_view(), + rfl::get<_is>(_tup), _ptr), + ...); } - template + template static void build_schema(std::map* _definitions, - SchemaType* _schema, - View* _view, + SchemaType* _schema, View* _view, std::integer_sequence) noexcept { - (add_field_to_schema(_definitions, _schema, _view), ...); + if constexpr (!std::is_same_v) { + (build_named_tuple_field_schema< + R, W, _no_field_names, ProcessorsType, + std::remove_cvref_t< + typename internal::nth_element_t<_is, FieldTypes...>::Type>>( + _definitions, _schema, + internal::nth_element_t<_is, FieldTypes...>::name(), + _view ? extract_schema_field_ptr(rfl::get<_is>(*_view)) : nullptr), + ...); + } else { + (build_named_tuple_field_schema< + R, W, _no_field_names, ProcessorsType, + std::remove_cvref_t< + typename internal::nth_element_t<_is, FieldTypes...>::Type>>( + _definitions, _schema, + internal::nth_element_t<_is, FieldTypes...>::name(), nullptr), + ...); + } if constexpr (NamedTupleType::pos_extra_fields() != -1) { using F = internal::nth_element_t - static RFL_ALWAYS_INLINE void handle_one_missing_field( - const std::array& _found, const NamedTupleType& _view, - std::array* _set, FieldErrors* _errors, - const bool _value_initialize_default_vals) noexcept { - if (should_stop_on_field_error(*_errors)) return; - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - using ValueType = std::remove_reference_t< - std::remove_pointer_t>; - - if (!std::get<_i>(_found)) { - constexpr bool is_default_val_field = - internal::is_default_val_v; - constexpr bool is_required_field = - !is_default_val_field && !internal::is_extra_fields_v && - (_all_required || is_required()); - - // Without _set, the struct was default-constructed before it was read, - // so the field already holds its default value. With _set, the fields - // are constructed in raw memory. An rfl::NamedTuple has no in-class - // initializers, so a missing bare rfl::DefaultVal field is - // value-initialized there. Otherwise the field's default value is not - // available, so the field is required. - const bool defaults_constructed = _set == nullptr; - - if constexpr (is_default_val_field) { - if constexpr (can_value_initialize_default_val()) { - if (_value_initialize_default_vals && !defaults_constructed) { - // The value's constructor can throw, for instance a Validator - // whose zero value is invalid. - try { - ::new (rfl::get<_i>(_view)) ValueType(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; - } - std::get<_i>(*_set) = true; - return; - } - } - } - - if (is_required_field || - (is_default_val_field && !defaults_constructed)) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - std::stringstream stream; - stream << "Field named '" << std::string(current_name) - << "' not found."; - _errors->emplace_back( - make_nested_error(std::string(current_name), stream.str())); - return; - } - - if constexpr (!is_required_field && !is_default_val_field) { - if (defaults_constructed) { - return; - } - using NonConstT = std::remove_const_t; - const auto ptr = const_cast(rfl::get<_i>(_view)); - if constexpr (std::is_nothrow_default_constructible_v) { - ::new (ptr) NonConstT(); - } else { - // The default value can throw, for instance a Validator whose - // default value is invalid. - try { - ::new (ptr) NonConstT(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; - } - } - std::get<_i>(*_set) = true; - } - } - } - - /// Whether a missing rfl::DefaultVal field can be value-initialized. Only - /// an rfl::NamedTuple does this at runtime, and it cannot have const fields, - /// so const fields of structs need no instantiation. - template - static constexpr bool can_value_initialize_default_val() { - using T = typename internal::default_val_t::Type; - return !std::is_const_v && std::is_default_constructible_v && - std::is_default_constructible_v; - } - - /// Generates error messages for when fields are missing. - template + template static RFL_ALWAYS_INLINE void handle_missing_fields( const std::array& _found, const NamedTupleType& _view, std::array* _set, FieldErrors* _errors, const bool _value_initialize_default_vals, std::integer_sequence) noexcept { - (handle_one_missing_field<_is>(_found, _view, _set, _errors, - _value_initialize_default_vals), + (handle_missing_named_tuple_field<_ignore_empty_containers, _all_required, + _defaults_constructed, ProcessorsType>( + internal::nth_element_t<_is, FieldTypes...>::name(), + std::get<_is>(_found), rfl::get<_is>(_view), + _set ? &std::get<_is>(*_set) : nullptr, _errors, + _value_initialize_default_vals), ...); } - static auto make_parent(const std::string_view& _name, - OutputObjectOrArrayType* _ptr) { - if constexpr (_no_field_names) { - return typename ParentType::Array{_ptr}; - } else { - return typename ParentType::Object{_name, _ptr}; - } - } - static RFL_ALWAYS_INLINE std::pair, std::optional> read_object_or_array(const R& _r, @@ -484,9 +585,9 @@ struct NamedTupleParser { } } if (!should_stop_on_field_error(errors)) { - handle_missing_fields(found, *_view, &set, &errors, - _value_initialize_default_vals, - std::make_integer_sequence()); + handle_missing_fields( + found, *_view, &set, &errors, _value_initialize_default_vals, + std::make_integer_sequence()); } if constexpr (internal::fail_fast_v) { return std::make_pair(set, std::move(errors).error()); @@ -517,9 +618,10 @@ struct NamedTupleParser { if constexpr (internal::has_default_val_v && !internal::default_if_missing_v) { if (!should_stop_on_field_error(errors)) { - handle_missing_fields(reader.found(), *_view, nullptr, &errors, - /*_value_initialize_default_vals=*/false, - std::make_integer_sequence()); + handle_missing_fields( + reader.found(), *_view, nullptr, &errors, + /*_value_initialize_default_vals=*/false, + std::make_integer_sequence()); } } if constexpr (internal::fail_fast_v) { diff --git a/include/rfl/parsing/ParserBasicType.hpp b/include/rfl/parsing/ParserBasicType.hpp index f950ff017..2a9ffc8a7 100644 --- a/include/rfl/parsing/ParserBasicType.hpp +++ b/include/rfl/parsing/ParserBasicType.hpp @@ -1,6 +1,8 @@ #ifndef RFL_PARSING_PARSER_BASIC_TYPE_HPP_ #define RFL_PARSING_PARSER_BASIC_TYPE_HPP_ +#include +#include #include #include @@ -13,6 +15,7 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" +#include "../internal/integer_bounds_v.hpp" #include "../internal/is_basic_type.hpp" #include "../internal/is_description.hpp" #include "../internal/is_literal.hpp" @@ -33,6 +36,15 @@ namespace rfl::parsing { +template +inline constexpr bool is_bounded_integer_v = []() { + using U = std::remove_cvref_t; + return std::is_integral_v && sizeof(U) <= sizeof(std::int64_t) && + !std::is_same_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v; +}(); + /// Default case - anything that cannot be explicitly matched. template struct ParserBasicType { @@ -78,6 +90,18 @@ struct ParserBasicType { if constexpr (std::is_same()) { return Type{Type::Boolean{}}; + } else if constexpr (is_bounded_integer_v && + internal::integer_bounds_v && + !schemaful::IsSchemafulReader && + !schemaful::IsSchemafulWriter) { + return Type{Type::BoundedInteger{ + .minimum_ = std::is_unsigned_v + ? std::int64_t{0} + : static_cast( + std::numeric_limits::min()), + .maximum_ = static_cast( + std::numeric_limits::max())}}; + } else if constexpr (std::is_same()) { return Type{Type::Int32{}}; diff --git a/include/rfl/parsing/ParserDefaultVal.hpp b/include/rfl/parsing/ParserDefaultVal.hpp index 9f11fea44..23620dfdb 100644 --- a/include/rfl/parsing/ParserDefaultVal.hpp +++ b/include/rfl/parsing/ParserDefaultVal.hpp @@ -64,8 +64,10 @@ struct ParserDefaultVal { static schema::Type to_schema( std::map* _definitions) { using U = std::remove_cvref_t; - return schema::Type{schema::Type::DefaultVal{Ref::make( - Parser::to_schema(_definitions))}}; + return schema::Type{schema::Type::DefaultVal{ + .type_ = Ref::make( + Parser::to_schema(_definitions)), + .default_value_ = std::nullopt}}; } }; diff --git a/include/rfl/parsing/ParserEnum.hpp b/include/rfl/parsing/ParserEnum.hpp index 4a216f434..4dd5f6977 100644 --- a/include/rfl/parsing/ParserEnum.hpp +++ b/include/rfl/parsing/ParserEnum.hpp @@ -7,6 +7,7 @@ #include "../Result.hpp" #include "../config.hpp" #include "../enums.hpp" +#include "../internal/enum_name_transform_v.hpp" #include "../internal/enum_names_only_v.hpp" #include "../internal/enums/is_flag_enum.hpp" #include "../internal/enums/is_scoped_enum.hpp" @@ -60,9 +61,13 @@ struct ParserEnum { return _r.template to_basic_type>(_var) .transform([](const auto _val) { return static_cast(_val); }); } else { + constexpr auto transform = + internal::enum_name_transform_v; + constexpr bool enum_names_only = + internal::enum_names_only_v; return _r.template to_basic_type(_var).and_then( - rfl::string_to_enum>); + &internal::string_to_enum_with_transform_noexcept< + T, enum_names_only, transform>); } } @@ -84,7 +89,10 @@ struct ParserEnum { const auto val = static_cast>(_var); ParentType::add_value(_w, val, _parent); } else { - const auto str = rfl::enum_to_string(_var); + constexpr auto transform = + internal::enum_name_transform_v; + const auto str = + internal::enum_to_string_with_transform(_var); ParentType::add_value(_w, str, _parent); } } @@ -119,15 +127,40 @@ struct ParserEnum { } else if constexpr (config::enum_descriptions::has_descriptions) { // Generate DescribedLiteral for enums with descriptions auto described = Type::DescribedLiteral{}; - constexpr auto enumerators = get_enumerator_array(); - for (const auto& [name, value] : enumerators) { - auto desc = config::enum_descriptions::get(value); - described.values_.push_back( - Type::DescribedLiteral::ValueWithDescription{ - .value_ = std::string(name), - .description_ = std::string(desc)}); + if constexpr (internal::has_custom_enum_names_v) { + constexpr auto transform = + internal::enum_name_transform_v; + for (const auto& [wire, value] : + internal::get_cached_unique_enum_wire_names_with_transform< + U, transform>()) { + auto desc = config::enum_descriptions::get(value); + described.values_.push_back( + Type::DescribedLiteral::ValueWithDescription{ + .value_ = wire, .description_ = std::string(desc)}); + } + } else { + constexpr auto enumerators = get_enumerator_array(); + for (const auto& [name, value] : enumerators) { + auto desc = config::enum_descriptions::get(value); + described.values_.push_back( + Type::DescribedLiteral::ValueWithDescription{ + .value_ = std::string(name), + .description_ = std::string(desc)}); + } } return Type{std::move(described)}; + } else if constexpr (internal::has_custom_enum_names_v) { + constexpr auto transform = + internal::enum_name_transform_v; + const auto& entries = + internal::get_cached_unique_enum_wire_names_with_transform< + U, transform>(); + std::vector vals; + vals.reserve(entries.size()); + for (const auto& entry : entries) { + vals.push_back(entry.first); + } + return Type{Type::Literal{.values_ = std::move(vals)}}; } else { return Parser< R, W, diff --git a/include/rfl/parsing/ParserExpected.hpp b/include/rfl/parsing/ParserExpected.hpp index 6d5cdc2c0..96edee4a5 100644 --- a/include/rfl/parsing/ParserExpected.hpp +++ b/include/rfl/parsing/ParserExpected.hpp @@ -3,6 +3,7 @@ #include #include +#include #include "../Field.hpp" #include "../NamedTuple.hpp" @@ -11,7 +12,8 @@ #include "Parser_base.hpp" #include "schema/Type.hpp" -#if __has_include() +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L && \ + __has_include() #include #endif diff --git a/include/rfl/parsing/ParserRflVariant.hpp b/include/rfl/parsing/ParserRflVariant.hpp index 857aff132..130707868 100644 --- a/include/rfl/parsing/ParserRflVariant.hpp +++ b/include/rfl/parsing/ParserRflVariant.hpp @@ -9,6 +9,7 @@ #include "../internal/add_tags_to_variants_v.hpp" #include "../internal/all_fields.hpp" #include "../internal/nth_element_t.hpp" +#include "../internal/variants_as_one_of_v.hpp" #include "../visit.hpp" #include "FieldVariantParser.hpp" #include "Parent.hpp" @@ -202,7 +203,9 @@ class ParserRflVariant, } else { return schema::Type{schema::Type::AnyOf{ .types_ = std::vector( - {one_field_to_type(_definitions)...})}}; + {one_field_to_type(_definitions)...}), + .mutually_exclusive_ = + internal::variants_as_one_of_v}}; } } diff --git a/include/rfl/parsing/ParserTaggedUnion.hpp b/include/rfl/parsing/ParserTaggedUnion.hpp index dee232752..572c0e7fd 100644 --- a/include/rfl/parsing/ParserTaggedUnion.hpp +++ b/include/rfl/parsing/ParserTaggedUnion.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "../Result.hpp" #include "../TaggedUnion.hpp" @@ -129,10 +130,14 @@ struct ParserTaggedUnion, return Parser, ProcessorsType>::to_schema(_definitions); } else { - using VariantType = std::variant(std::declval())) - ...>; - return Parser::to_schema(_definitions); + // The tags are unique, so a value can match at most one alternative. + return schema::Type{schema::Type::AnyOf{ + .types_ = std::vector( + {Parser( + std::declval())), + ProcessorsType>::to_schema(_definitions)...}), + .mutually_exclusive_ = true}}; } } @@ -158,7 +163,10 @@ struct ParserTaggedUnion, << _discriminator.str() << " '" << _disc_value << "'. The following tags are allowed: " << internal::strings::join(", ", names); - return error(stream.str()); + const ErrorDetail::PathSegment seg = + no_field_names_ ? ErrorDetail::PathSegment(size_t{0}) + : ErrorDetail::PathSegment(_discriminator.str()); + return error(make_nested_error(seg, stream.str())); } } @@ -217,7 +225,10 @@ struct ParserTaggedUnion, std::stringstream stream; stream << "Could not parse tagged union: Could not find field '" << _discriminator.str() << "' or type of field was not a string."; - return Error(stream.str()); + const ErrorDetail::PathSegment seg = + no_field_names_ ? ErrorDetail::PathSegment(size_t{0}) + : ErrorDetail::PathSegment(_discriminator.str()); + return make_nested_error(seg, stream.str()); }; if constexpr (no_field_names_) { diff --git a/include/rfl/parsing/ParserTimePoint.hpp b/include/rfl/parsing/ParserTimePoint.hpp index 558bb42b5..71adc0086 100644 --- a/include/rfl/parsing/ParserTimePoint.hpp +++ b/include/rfl/parsing/ParserTimePoint.hpp @@ -161,8 +161,10 @@ struct ParserTimePoint { } return std::chrono::time_point_cast(tp); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while parsing time point."); } } diff --git a/include/rfl/parsing/ParserVariant.hpp b/include/rfl/parsing/ParserVariant.hpp index 6ea04ce5d..d740dbc49 100644 --- a/include/rfl/parsing/ParserVariant.hpp +++ b/include/rfl/parsing/ParserVariant.hpp @@ -12,6 +12,7 @@ #include "../internal/add_tags_to_variants_v.hpp" #include "../internal/all_fields.hpp" #include "../internal/to_ptr_field.hpp" +#include "../internal/variants_as_one_of_v.hpp" #include "../visit.hpp" #include "FieldVariantParser.hpp" #include "Parent.hpp" @@ -235,7 +236,9 @@ class ParserVariant, ProcessorsType> { } else { return schema::Type{schema::Type::AnyOf{ .types_ = std::vector( - {one_field_to_type(_definitions)...})}}; + {one_field_to_type(_definitions)...}), + .mutually_exclusive_ = + internal::variants_as_one_of_v}}; } } diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..058d4fdd7 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -5,6 +5,7 @@ #include #include +#include "../Generic.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "../internal/HasFromReflectionMethod.hpp" @@ -23,6 +24,7 @@ #include "../internal/processed_t.hpp" #include "../internal/ptr_cast.hpp" #include "../internal/to_ptr_named_tuple.hpp" +#include "../internal/variants_as_one_of_v.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" #include "MapParser.hpp" @@ -226,8 +228,10 @@ struct Parser { try { using NT = decltype(_named_tuple); return Reflector::to(std::forward(_named_tuple)); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception in Reflector::to."); } }; return Parser::ReflType, @@ -260,8 +264,10 @@ struct Parser { } else { return T{std::forward(_named_tuple)}; } - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while constructing reflected type."); } }; return Parser::read(_r, _var) @@ -609,6 +615,14 @@ struct Parser { } else if constexpr (internal::is_validator_v) { return make_validated(_definitions); + } else if constexpr (std::is_same_v && + internal::variants_as_one_of_v) { + // rfl::Generic's alternatives overlap (1 is both an integer and a + // number), so its schema stays anyOf even under VariantsAsOneOf. + return Parser>:: + to_schema(_definitions); + } else if constexpr (internal::has_reflection_type_v || internal::has_read_reflector || internal::has_write_reflector) { @@ -750,11 +764,15 @@ struct Parser { return error(std::move(*err)); } return t; - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); + } catch (...) { + return error("Unknown exception while reading struct with defaults."); } - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(default_construction_error(e.what())); + } catch (...) { + return error(default_construction_error("unknown exception")); } } diff --git a/include/rfl/parsing/TupleReader.hpp b/include/rfl/parsing/TupleReader.hpp index df127aa70..d812a89e8 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -108,7 +108,7 @@ class TupleReader { try { ::new (&(rfl::get<_i>(*tuple_))) CurrentType(); ++num_set_; - } catch (std::exception& e) { + } catch (const std::exception& e) { *_err = make_nested_error( static_cast(_i), "Field " + std::to_string(_i) + @@ -116,6 +116,13 @@ class TupleReader { "constructed: " + e.what()); return; + } catch (...) { + *_err = make_nested_error( + static_cast(_i), + "Field " + std::to_string(_i) + + " was missing, and its default value could not be " + "constructed: unknown exception."); + return; } } } diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp index 2be9ee2e7..3e30934c2 100644 --- a/include/rfl/parsing/VectorParser.hpp +++ b/include/rfl/parsing/VectorParser.hpp @@ -92,7 +92,8 @@ struct VectorParser { MapParser::write(_w, _vec, _parent); } else { auto arr = ParentType::add_array( - _w, std::distance(_vec.begin(), _vec.end()), _parent); + _w, static_cast(std::distance(_vec.begin(), _vec.end())), + _parent); const auto new_parent = typename ParentType::Array{&arr}; for (const auto& v : _vec) { Parser, ProcessorsType>::write(_w, v, diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 84ee4b826..b43ef6e15 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -10,15 +10,106 @@ #include "../Tuple.hpp" #include "../internal/always_inline.hpp" +#include "../internal/cold.hpp" #include "../internal/is_array.hpp" #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" #include "Parser_base.hpp" +#include "find_field_index.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "wrap_error.hpp" namespace rfl::parsing { +/// Placement-moves a parsed field value into uninitialized struct storage. +/// Free function parameterized only by (Target, Source)—never ViewType—so +/// instantiations do not carry the enclosing NamedTuple in mangled symbol +/// names or DWARF debug info. +template +void placement_move_field(Target* _t, Source* _s) { + if constexpr (std::is_const_v) { + placement_move_field(const_cast*>(_t), _s); + } else if constexpr (!internal::is_array_v && + !std::is_array_v) { + ::new (_t) Target(std::move(*_s)); + } else if constexpr (internal::is_array_v) { + static_assert(std::is_array_v, "Expected target to be a c-array."); + for (size_t i = 0; i < _s->arr_.size(); ++i) { + placement_move_field(&((*_t)[i]), &(_s->arr_[i])); + } + } else { + for (size_t i = 0; i < _s->size(); ++i) { + placement_move_field(&((*_t)[i]), &((*_s)[i])); + } + } +} + +template +RFL_COLD void record_uninitialized_field_error(const std::string_view _name, + Error _err, + FieldErrorsType* _errors, + const size_t _reserve_errors) { + // Reserve lazily to avoid error-vector reallocations while keeping + // successful reads allocation-free. + _errors->reserve(_reserve_errors); + _errors->emplace_back(wrap_field_error(_name, std::move(_err))); +} + +/// Reads one field into an uninitialized view slot. Free function parameterized +/// only by (R, W, OriginalType, ProcessorsType)—never the enclosing ViewType—so +/// instantiations do not repeat the full NamedTuple in mangled symbol names or +/// DWARF debug info. +template +RFL_ALWAYS_INLINE void assign_uninitialized_view_field_inline( + const R& _r, const typename R::InputVarType& _var, + const std::string_view _name, OriginalType& _slot, bool& _is_set, + FieldErrors* _errors, const size_t _reserve_errors) { + using T = std::remove_cvref_t>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + record_uninitialized_field_error(_name, std::move(res).error(), _errors, + _reserve_errors); + return; + } + if constexpr (std::is_pointer_v) { + placement_move_field(_slot, &(*res)); + } else { + _slot = std::move(*res); + } + _is_set = true; +} + +template +inline void assign_uninitialized_view_field( + const R& _r, const typename R::InputVarType& _var, + const std::string_view _name, OriginalType& _slot, bool& _is_set, + FieldErrors* _errors, const size_t _reserve_errors) { + assign_uninitialized_view_field_inline( + _r, _var, _name, _slot, _is_set, _errors, _reserve_errors); +} + +/// Reads one extra field into an uninitialized ExtraFields slot. +template +void assign_extra_uninitialized_field( + const R& _r, const std::string_view _current_name, + const typename R::InputVarType& _var, ExtraFieldsType* _extra_fields, + bool& _is_found, bool& _is_set, FieldErrors* _errors) { + using T = std::remove_cvref_t< + std::remove_pointer_t>; + if (!_is_set) { + ::new (_extra_fields) ExtraFieldsType(); + _is_set = true; + _is_found = true; + } + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(res).error())); + return; + } + _extra_fields->emplace(std::string(_current_name), std::move(*res)); +} + template class ViewReader { public: @@ -38,7 +129,8 @@ class ViewReader { * @param _errors The field error collector. */ ViewReader(const R* _r, ViewType* _view, std::array* _found, - std::array* _set, FieldErrors* _errors) + std::array* _set, + FieldErrors* _errors) : r_(_r), view_(_view), found_(_found), set_(_set), errors_(_errors) {} ~ViewReader() = default; @@ -49,10 +141,25 @@ class ViewReader { * @param _name The name of the field. * @param _var The input variable to read from. */ - void read(const std::string_view& _name, const InputVarType& _var) const { + RFL_ALWAYS_INLINE void read(const std::string_view& _name, + const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _name, _var, view_, errors_, found_, set_, - std::make_integer_sequence()); + if constexpr (size_ == 0) { + static_cast(_var); + if constexpr (internal::no_extra_fields_v) { + handle_no_extra_fields_error(_name, errors_); + } else { + static_cast(_name); + } + } else if constexpr (size_ <= 4) { + assign_to_matching_name_small(*r_, _name, _var, view_, errors_, found_, + set_, + std::make_integer_sequence()); + } else { + assign_to_matching_name(*r_, _name, _var, view_, errors_, found_, set_, + next_idx_, + std::make_integer_sequence()); + } } /** @@ -63,7 +170,7 @@ class ViewReader { */ void read(const int _index, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _index, _var, view_, errors_, found_, set_, + assign_to_matching_index(*r_, _index, _var, view_, errors_, found_, set_, std::make_integer_sequence()); } @@ -71,8 +178,35 @@ class ViewReader { template void read(std::integral_constant, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, i, _var, view_, errors_, found_, set_, - std::integer_sequence()); + bool already_assigned = false; + using FieldType = tuple_element_t; + if (!std::get(*found_)) { + std::get(*found_) = true; + already_assigned = true; + assign_uninitialized_view_field_inline( + *r_, _var, FieldType::name(), rfl::get(*view_), std::get(*set_), + errors_, size_); + } + + if constexpr (ViewType::pos_extra_fields() != -1) { + static_assert(!schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); + static_assert(ViewType::pos_extra_fields() == -1, + "rfl::ExtraFields are not supported for positional reads."); + } else if constexpr (internal::no_extra_fields_v) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); + if (!already_assigned) { + std::stringstream stream; + stream << "Value named '" << i << "' not used."; + errors_->emplace_back( + make_nested_error(static_cast(i), stream.str())); + } + } } /** @@ -83,101 +217,170 @@ class ViewReader { static constexpr size_t size() { return size_; } private: - template - static bool is_matching(const int _current_index) { - return _current_index == i; - } - - template - static bool is_matching(const std::string_view& _current_name) { - return _current_name == FieldType::name(); + template + static RFL_ALWAYS_INLINE void assign_by_index_small( + const R& _r, const int _idx, const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, std::array* _set, + std::integer_sequence) { + using Fields = typename ViewType::Fields; + static_cast( + ((_idx == is + ? (assign_uninitialized_view_field_inline< + R, W, typename tuple_element_t::Type, + ProcessorsType>(_r, _var, + tuple_element_t::name(), + rfl::get(*_view), std::get(*_set), + _errors, size_), + true) + : false) || + ...)); } - static ErrorDetail::PathSegment to_path_segment(const int _current_index) { - return static_cast(_current_index); + template + static void assign_by_index(const R& _r, const int _idx, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, + std::array* _set, + std::integer_sequence) { + using Fields = typename ViewType::Fields; + if constexpr (size_ <= 4) { + assign_by_index_small(_r, _idx, _var, _view, _errors, _set, + std::integer_sequence()); + } else { + static_cast( + ((_idx == is ? (assign_uninitialized_view_field< + R, W, typename tuple_element_t::Type, + ProcessorsType>( + _r, _var, tuple_element_t::name(), + rfl::get(*_view), std::get(*_set), + _errors, size_), + true) + : false) || + ...)); + } } - static ErrorDetail::PathSegment to_path_segment( - const std::string_view& _current_name) { - return std::string(_current_name); + template + static RFL_ALWAYS_INLINE void assign_to_matching_name_small( + const R& _r, const std::string_view _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, std::array* _found, + std::array* _set, std::integer_sequence) { + using Fields = typename ViewType::Fields; + const bool matched = + (((is != ViewType::pos_extra_fields() && + _current_name == tuple_element_t::name()) + ? (!std::get(*_found) + ? (std::get(*_found) = true, + assign_uninitialized_view_field_inline< + R, W, typename tuple_element_t::Type, + ProcessorsType>( + _r, _var, tuple_element_t::name(), + rfl::get(*_view), std::get(*_set), _errors, + size_), + true) + : false) + : false) || + ...); + if constexpr (ViewType::pos_extra_fields() != -1) { + if (!matched) { + handle_extra_field_name(_r, _current_name, _var, _view, _errors, _found, + _set); + } + } else if constexpr (internal::no_extra_fields_v) { + if (!matched) { + handle_no_extra_fields_error(_current_name, _errors); + } + } else { + static_cast(matched); + } } - template - static RFL_ALWAYS_INLINE void assign_if_field_matches( - const R& _r, const auto _current_name_or_index, const auto& _var, - auto* _view, auto* _errors, auto* _found, auto* _set, - bool* _already_assigned) { - using FieldType = tuple_element_t; - using OriginalType = typename FieldType::Type; - using T = - std::remove_cvref_t>; - if (!(*_already_assigned) && !std::get(*_found) && - is_matching(_current_name_or_index)) { - std::get(*_found) = true; - *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) [[unlikely]] { - constexpr auto name = FieldType::name(); - // Reserve lazily to avoid error-vector reallocations while keeping - // successful reads allocation-free. - _errors->reserve(size_); - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; + template + static void assign_to_matching_name( + const R& _r, const std::string_view _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, std::array* _found, + std::array* _set, size_t& _next_idx, + std::integer_sequence _seq) { + bool matched = false; + if constexpr (size_ > 0) { + if (const int idx = FieldNameLookup:: + find_with_hint(_current_name, _next_idx); + idx >= 0 && idx != ViewType::pos_extra_fields()) { + if (!(*_found)[static_cast(idx)]) { + (*_found)[static_cast(idx)] = true; + assign_by_index(_r, idx, _var, _view, _errors, _set, _seq); + matched = true; + } } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); - } else { - rfl::get(*_view) = std::move(*res); + } + if constexpr (ViewType::pos_extra_fields() != -1) { + if (!matched) { + handle_extra_field_name(_r, _current_name, _var, _view, _errors, _found, + _set); + } + } else if constexpr (internal::no_extra_fields_v) { + if (!matched) { + handle_no_extra_fields_error(_current_name, _errors); } - std::get(*_set) = true; + } else { + static_cast(matched); } } - template - static void assign_to_extra_fields(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, auto* _set) { - auto* extra_fields = _view->template get<_pos>(); + static void handle_extra_field_name(const R& _r, + const std::string_view _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, + std::array* _found, + std::array* _set) { + static_assert(!schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); + constexpr int pos = ViewType::pos_extra_fields(); + auto* extra_fields = _view->template get(); using ExtraFieldsType = std::remove_cvref_t>; - using T = std::remove_cvref_t< - std::remove_pointer_t>; - if (!std::get<_pos>(*_set)) { - ::new (extra_fields) ExtraFieldsType(); - std::get<_pos>(*_set) = true; - std::get<_pos>(*_found) = true; - } - auto res = Parser::read(_r, _var); - if (!res) [[unlikely]] { - _errors->emplace_back( - wrap_field_error(_current_name, std::move(res).error())); - return; - } - extra_fields->emplace(std::string(_current_name), std::move(*res)); + assign_extra_uninitialized_field( + _r, _current_name, _var, extra_fields, std::get(*_found), + std::get(*_set), _errors); + } + + static RFL_COLD void handle_no_extra_fields_error( + const std::string_view _current_name, + FieldErrors* _errors) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); + std::stringstream stream; + stream << "Value named '" << _current_name << "' not used."; + _errors->emplace_back( + make_nested_error(std::string(_current_name), stream.str())); } template - static void assign_to_matching_field(const R& _r, - const auto _current_name_or_index, - const auto& _var, auto* _view, - auto* _errors, auto* _found, auto* _set, - std::integer_sequence) { + static void assign_to_matching_index( + const R& _r, const int _index, const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, std::array* _found, + std::array* _set, std::integer_sequence _seq) { bool already_assigned = false; - - (assign_if_field_matches(_r, _current_name_or_index, _var, _view, - _errors, _found, _set, &already_assigned), - ...); + if constexpr (size_ > 0) { + if (_index >= 0 && static_cast(_index) < size_ && + !(*_found)[static_cast(_index)]) { + (*_found)[static_cast(_index)] = true; + already_assigned = true; + assign_by_index(_r, _index, _var, _view, _errors, _set, _seq); + } + } if constexpr (ViewType::pos_extra_fields() != -1) { static_assert(!schemaful::IsSchemafulReader, "rfl::ExtraFields are not supported for schemaful formats, " "because schemaful formats cannot have extra fields."); - constexpr int pos = ViewType::pos_extra_fields(); - if (!already_assigned) { - assign_to_extra_fields(_r, _current_name_or_index, _var, _view, - _errors, _found, _set); - } + static_assert(ViewType::pos_extra_fields() == -1, + "rfl::ExtraFields are not supported for positional reads."); } else if constexpr (internal::no_extra_fields_v) { static_assert( !schemaful::IsSchemafulReader, @@ -185,29 +388,9 @@ class ViewReader { "sense, because schemaful formats cannot have extra fields."); if (!already_assigned) { std::stringstream stream; - stream << "Value named '" << _current_name_or_index << "' not used."; - _errors->emplace_back(make_nested_error( - to_path_segment(_current_name_or_index), stream.str())); - } - } - } - - template - static void move_to(Target* _t, Source* _s) { - if constexpr (std::is_const_v) { - return move_to(const_cast*>(_t), _s); - } else if constexpr (!rfl::internal::is_array_v && - !std::is_array_v) { - ::new (_t) Target(std::move(*_s)); - } else if constexpr (rfl::internal::is_array_v) { - static_assert(std::is_array_v, - "Expected target to be a c-array."); - for (size_t i = 0; i < _s->arr_.size(); ++i) { - move_to(&((*_t)[i]), &(_s->arr_[i])); - } - } else { - for (size_t i = 0; i < _s->size(); ++i) { - move_to(&((*_t)[i]), &((*_s)[i])); + stream << "Value named '" << _index << "' not used."; + _errors->emplace_back( + make_nested_error(static_cast(_index), stream.str())); } } } @@ -228,6 +411,10 @@ class ViewReader { /// Stores field errors according to the selected processor policy. FieldErrors* errors_; + + /// Sequential-key cursor hint for O(1) lookup when keys arrive in + /// declaration order. + mutable size_t next_idx_ = 0; }; } // namespace rfl::parsing diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..450125c6a 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -4,20 +4,109 @@ #include #include #include +#include #include #include #include #include "../Ref.hpp" #include "../Tuple.hpp" +#include "../internal/always_inline.hpp" +#include "../internal/cold.hpp" #include "../internal/is_array.hpp" #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" #include "Parser_base.hpp" +#include "find_field_index.hpp" #include "wrap_error.hpp" namespace rfl::parsing { +/// Move-assigns a parsed field value into an already-constructed struct field. +/// Free function parameterized only by (Target, Source)—never ViewType—so +/// instantiations do not carry the enclosing NamedTuple in mangled symbol +/// names or DWARF debug info. +template +void move_assign_field(Target* _t, Source* _s) { + if constexpr (!internal::is_array_v && !std::is_array_v) { + if constexpr (std::is_const_v) { + // The struct was default-constructed, so *_t is a live const object + // and must not be assigned to. Re-create it in place instead. If the + // constructor throws, we are inside a noexcept function, so it cannot + // be destroyed twice. + using NonConstTarget = std::remove_const_t; + auto* const ptr = const_cast(_t); + std::destroy_at(ptr); + ::new (ptr) NonConstTarget(std::move(*_s)); + } else { + *_t = Target(std::move(*_s)); + } + } else if constexpr (internal::is_array_v) { + static_assert(std::is_array_v, "Expected target to be a c-array."); + for (size_t i = 0; i < _s->arr_.size(); ++i) { + move_assign_field(&((*_t)[i]), &(_s->arr_[i])); + } + } else { + for (size_t i = 0; i < _s->size(); ++i) { + move_assign_field(&((*_t)[i]), &((*_s)[i])); + } + } +} + +template +RFL_COLD void record_default_field_error(const std::string_view _name, + Error _err, FieldErrorsType* _errors) { + _errors->emplace_back(wrap_field_error(_name, std::move(_err))); +} + +/// Reads one field into an already-constructed view slot. Free function +/// parameterized only by (R, W, OriginalType, ProcessorsType)—never the +/// enclosing ViewType—so instantiations do not repeat the full NamedTuple in +/// mangled symbol names or DWARF debug info. +template +RFL_ALWAYS_INLINE void assign_default_view_field_inline( + const R& _r, const typename R::InputVarType& _var, + const std::string_view _name, OriginalType& _slot, + FieldErrors* _errors) { + using T = std::remove_cvref_t>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + record_default_field_error(_name, std::move(res).error(), _errors); + return; + } + if constexpr (std::is_pointer_v) { + move_assign_field(_slot, &(*res)); + } else { + _slot = std::move(*res); + } +} + +template +inline void assign_default_view_field( + const R& _r, const typename R::InputVarType& _var, + const std::string_view _name, OriginalType& _slot, + FieldErrors* _errors) { + assign_default_view_field_inline( + _r, _var, _name, _slot, _errors); +} + +/// Reads one extra field into an already-constructed ExtraFields slot. +template +void assign_extra_default_field( + const R& _r, const std::string_view _current_name, + const typename R::InputVarType& _var, ExtraFieldsType* _extra_fields, + FieldErrors* _errors) { + using T = std::remove_cvref_t< + std::remove_pointer_t>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(res).error())); + return; + } + _extra_fields->emplace(std::string(_current_name), std::move(*res)); +} + template class ViewReaderWithDefault { public: @@ -54,10 +143,25 @@ class ViewReaderWithDefault { * @param _name The name of the field. * @param _var The input variable to read from. */ - void read(const std::string_view& _name, const InputVarType& _var) const { + RFL_ALWAYS_INLINE void read(const std::string_view& _name, + const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _name, _var, view_, errors_, found_.get(), - std::make_integer_sequence()); + if constexpr (size_ == 0) { + static_cast(_var); + if constexpr (internal::no_extra_fields_v) { + handle_no_extra_fields_error(_name, errors_); + } else { + static_cast(_name); + } + } else if constexpr (size_ <= 4) { + assign_to_matching_field_small(*r_, _name, _var, view_, errors_, + found_.get(), + std::make_integer_sequence()); + } else { + assign_to_matching_field(*r_, _name, _var, view_, errors_, found_.get(), + next_idx_, + std::make_integer_sequence()); + } } /** @@ -68,109 +172,102 @@ class ViewReaderWithDefault { static constexpr size_t size() { return size_; } private: - template - static void assign_if_field_matches(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, - bool* _already_assigned) { - using FieldType = tuple_element_t; - using OriginalType = typename FieldType::Type; - using T = - std::remove_cvref_t>; - constexpr auto name = FieldType::name(); - if (!(*_already_assigned) && !std::get(*_found) && - _current_name == name) { - std::get(*_found) = true; - *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; + template + static RFL_ALWAYS_INLINE void assign_to_matching_field_small( + const R& _r, const std::string_view _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, std::array* _found, + std::integer_sequence) { + using Fields = typename ViewType::Fields; + const bool matched = + (((is != ViewType::pos_extra_fields() && + _current_name == tuple_element_t::name()) + ? (!std::get(*_found) + ? (std::get(*_found) = true, + assign_default_view_field_inline< + R, W, typename tuple_element_t::Type, + ProcessorsType>( + _r, _var, tuple_element_t::name(), + rfl::get(*_view), _errors), + true) + : false) + : false) || + ...); + if constexpr (ViewType::pos_extra_fields() != -1) { + if (!matched) { + handle_extra_field(_r, _current_name, _var, _view, _errors); } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); - } else { - rfl::get(*_view) = std::move(*res); + } else if constexpr (internal::no_extra_fields_v) { + if (!matched) { + handle_no_extra_fields_error(_current_name, _errors); } + } else { + static_cast(matched); } } - template - static void assign_to_extra_fields(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors) { - auto* extra_fields = _view->template get<_pos>(); - using ExtraFieldsType = - std::remove_cvref_t>; - using T = std::remove_cvref_t< - std::remove_pointer_t>; - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back( - wrap_field_error(_current_name, std::move(res).error())); - return; - } - extra_fields->emplace(std::string(_current_name), std::move(*res)); - } - template - static void assign_to_matching_field(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, - std::integer_sequence) { - bool already_assigned = false; - - (assign_if_field_matches(_r, _current_name, _var, _view, _errors, - _found, &already_assigned), - ...); - + static void assign_to_matching_field( + const R& _r, const std::string_view _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, std::array* _found, + size_t& _next_idx, std::integer_sequence) { + using Fields = typename ViewType::Fields; + bool matched = false; + if constexpr (size_ > 0) { + if (const int idx = FieldNameLookup:: + find_with_hint(_current_name, _next_idx); + idx >= 0 && idx != ViewType::pos_extra_fields()) { + if (!(*_found)[static_cast(idx)]) { + (*_found)[static_cast(idx)] = true; + static_cast( + ((idx == is + ? (assign_default_view_field< + R, W, typename tuple_element_t::Type, + ProcessorsType>(_r, _var, + tuple_element_t::name(), + rfl::get(*_view), _errors), + true) + : false) || + ...)); + matched = true; + } + } + } if constexpr (ViewType::pos_extra_fields() != -1) { - constexpr int pos = ViewType::pos_extra_fields(); - if (!already_assigned) { - assign_to_extra_fields(_r, _current_name, _var, _view, _errors); + if (!matched) { + handle_extra_field(_r, _current_name, _var, _view, _errors); } } else if constexpr (internal::no_extra_fields_v) { - if (!already_assigned) { - std::stringstream stream; - stream << "Value named '" << std::string(_current_name) - << "' not used. Remove the rfl::NoExtraFields processor or add " - "rfl::ExtraFields to avoid this error message."; - _errors->emplace_back( - make_nested_error(std::string(_current_name), stream.str())); + if (!matched) { + handle_no_extra_fields_error(_current_name, _errors); } + } else { + static_cast(matched); } } - template - static void move_to(Target* _t, Source* _s) { - if constexpr (!rfl::internal::is_array_v && - !std::is_array_v) { - if constexpr (std::is_const_v) { - // The struct was default-constructed, so *_t is a live const object - // and must not be assigned to. Re-create it in place instead. If the - // constructor throws, we are inside a noexcept function, so it cannot - // be destroyed twice. - using NonConstTarget = std::remove_const_t; - auto* const ptr = const_cast(_t); - std::destroy_at(ptr); - ::new (ptr) NonConstTarget(std::move(*_s)); - } else { - *_t = Target(std::move(*_s)); - } - } else if constexpr (rfl::internal::is_array_v) { - static_assert(std::is_array_v, - "Expected target to be a c-array."); - for (size_t i = 0; i < _s->arr_.size(); ++i) { - move_to(&((*_t)[i]), &(_s->arr_[i])); - } - } else { - for (size_t i = 0; i < _s->size(); ++i) { - move_to(&((*_t)[i]), &((*_s)[i])); - } - } + static void handle_extra_field(const R& _r, + const std::string_view _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors) { + constexpr int pos = ViewType::pos_extra_fields(); + auto* extra_fields = _view->template get(); + using ExtraFieldsType = + std::remove_cvref_t>; + assign_extra_default_field( + _r, _current_name, _var, extra_fields, _errors); + } + + static RFL_COLD void handle_no_extra_fields_error( + const std::string_view _current_name, + FieldErrors* _errors) { + std::stringstream stream; + stream << "Value named '" << std::string(_current_name) + << "' not used. Remove the rfl::NoExtraFields processor or add " + "rfl::ExtraFields to avoid this error message."; + _errors->emplace_back( + make_nested_error(std::string(_current_name), stream.str())); } private: @@ -185,6 +282,10 @@ class ViewReaderWithDefault { /// Stores field errors according to the selected processor policy. FieldErrors* errors_; + + /// Sequential-key cursor hint for O(1) lookup when keys arrive in + /// declaration order. + mutable size_t next_idx_ = 0; }; } // namespace rfl::parsing diff --git a/include/rfl/parsing/call_destructors_where_necessary.hpp b/include/rfl/parsing/call_destructors_where_necessary.hpp index 403609760..a78450fd6 100644 --- a/include/rfl/parsing/call_destructors_where_necessary.hpp +++ b/include/rfl/parsing/call_destructors_where_necessary.hpp @@ -2,7 +2,9 @@ #define RFL_PARSING_CALL_DESTRUCTORS_WHERE_NECESSARY_HPP_ #include +#include #include +#include #include "../get.hpp" @@ -17,41 +19,42 @@ namespace rfl::parsing { */ template void call_destructor_on_array(const size_t _size, T* _ptr) { - for (size_t i = 0; i < _size; ++i) { - if constexpr (std::is_array_v) { - call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); - } else if constexpr (std::is_destructible_v>) { - (_ptr + i)->~T(); + if constexpr (!std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + for (size_t i = 0; i < _size; ++i) { + if constexpr (std::is_array_v) { + call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); + } else if constexpr (std::is_destructible_v>) { + (_ptr + i)->~T(); + } } } } /** - * @brief Calls the destructor on a single element of a view, if necessary. - * - * @tparam ViewType The type of the view. - * @tparam _size The size of the set array. - * @tparam _i The index of the element. - * @param _set A boolean array indicating which elements have been set. - * @param _view The view to call the destructor on. + * @brief Calls the destructor on a single field pointer if it was set. + * Free function parameterized only by the field's pointer type (never + * ViewType) so instantiations do not carry the enclosing NamedTuple in their + * mangled symbol name or DWARF debug info. */ -template -void call_destructor_on_one_if_necessary(const std::array& _set, - ViewType* _view) { - using FieldType = tuple_element_t<_i, typename ViewType::Fields>; - using OriginalType = std::remove_cv_t; - using ValueType = - std::remove_cvref_t>; - if constexpr (!std::is_array_v && - std::is_pointer_v && - std::is_destructible_v) { - if (std::get<_i>(_set)) { - rfl::get<_i>(*_view)->~ValueType(); +template +inline void destroy_field_if_set(const bool _is_set, + const OriginalType& _slot) noexcept { + using CleanOriginal = std::remove_cvref_t; + using ValueType = std::remove_cvref_t>; + if constexpr (std::is_pointer_v && + std::is_array_v) { + if constexpr (!std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + if (_is_set) { + call_destructor_on_array(sizeof(*_slot) / sizeof(**_slot), *_slot); + } } - } else if constexpr (std::is_array_v) { - if (std::get<_i>(_set)) { - auto ptr = rfl::get<_i>(*_view); - call_destructor_on_array(sizeof(*ptr) / sizeof(**ptr), *ptr); + } else if constexpr (std::is_pointer_v && + std::is_destructible_v && + !std::is_trivially_destructible_v) { + if (_is_set) { + _slot->~ValueType(); } } } @@ -68,7 +71,17 @@ template void call_destructors_where_necessary(const std::array& _set, ViewType* _view) { [&](std::integer_sequence) { - (call_destructor_on_one_if_necessary(_set, _view), + ([&]() { + using CleanOriginal = + std::remove_cvref_t(*_view))>; + using ValueType = + std::remove_cvref_t>; + if constexpr (std::is_pointer_v && + !std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + destroy_field_if_set(std::get<_i>(_set), rfl::get<_i>(*_view)); + } + }.template operator()(), ...); }(std::make_integer_sequence()); } diff --git a/include/rfl/parsing/find_field_index.hpp b/include/rfl/parsing/find_field_index.hpp new file mode 100644 index 000000000..dd4827390 --- /dev/null +++ b/include/rfl/parsing/find_field_index.hpp @@ -0,0 +1,181 @@ +#ifndef RFL_PARSING_FIND_FIELD_INDEX_HPP_ +#define RFL_PARSING_FIND_FIELD_INDEX_HPP_ + +#include +#include +#include +#include +#include + +#include "../Literal.hpp" +#include "../internal/StringLiteral.hpp" +#include "../internal/always_inline.hpp" +#include "../internal/cold.hpp" + +namespace rfl::parsing { + +struct FieldNameEntry { + std::string_view name; + int field_idx; +}; + +RFL_ALWAYS_INLINE bool field_name_equals(const std::string_view _a, + const std::string_view _b) noexcept { + const std::size_t n = _a.size(); + if (n != _b.size()) { + return false; + } + if (n == 0) { + return true; + } + const char* p = _a.data(); + const char* q = _b.data(); + if (n >= 8) { + if (n <= 16) { + std::uint64_t a0 = 0; + std::uint64_t b0 = 0; + std::uint64_t a1 = 0; + std::uint64_t b1 = 0; + std::memcpy(&a0, p, 8); + std::memcpy(&b0, q, 8); + std::memcpy(&a1, p + n - 8, 8); + std::memcpy(&b1, q + n - 8, 8); + return ((a0 ^ b0) | (a1 ^ b1)) == 0; + } + return std::memcmp(p, q, n) == 0; + } + if (n >= 4) { + std::uint32_t a0 = 0; + std::uint32_t b0 = 0; + std::uint32_t a1 = 0; + std::uint32_t b1 = 0; + std::memcpy(&a0, p, 4); + std::memcpy(&b0, q, 4); + std::memcpy(&a1, p + n - 4, 4); + std::memcpy(&b1, q + n - 4, 4); + return ((a0 ^ b0) | (a1 ^ b1)) == 0; + } + return p[0] == q[0] && p[n >> 1] == q[n >> 1] && p[n - 1] == q[n - 1]; +} + +/// O(N log N) constexpr heapsort for FieldNameEntry tables (avoids relying on +/// C++20 constexpr std::sort support in older libc++ releases). +template +constexpr void sort_field_name_table( + std::array& _table) noexcept { + auto sift_down = [&](std::size_t _root, const std::size_t _end) { + while (true) { + std::size_t child = _root * 2 + 1; + if (child >= _end) { + break; + } + if (child + 1 < _end && _table[child].name < _table[child + 1].name) { + ++child; + } + if (_table[_root].name < _table[child].name) { + const auto tmp = _table[_root]; + _table[_root] = _table[child]; + _table[child] = tmp; + _root = child; + } else { + break; + } + } + }; + for (std::size_t start = _n / 2; start > 0; --start) { + sift_down(start - 1, _n); + } + for (std::size_t end = _n; end > 1; --end) { + const auto tmp = _table[0]; + _table[0] = _table[end - 1]; + _table[end - 1] = tmp; + sift_down(0, end - 1); + } +} + +/// Compile-time field name lookup keyed solely on a NamedTuple's `Names` +/// (`rfl::Literal<_names...>`), so the lookup table is independent of field +/// value types (e.g., `rfl::Description` wrappers) and shared across +/// `ViewReader`, `ViewReaderWithDefault`, readers, writers, and processors. +template +struct FieldNameLookup; + +template <> +struct FieldNameLookup> { + static constexpr std::size_t size_ = 0; + static constexpr std::array decl_names_{}; + + static RFL_COLD int find(const std::string_view) noexcept { return -1; } + + static RFL_ALWAYS_INLINE int find_with_hint(const std::string_view, + std::size_t&) noexcept { + return -1; + } +}; + +template +struct FieldNameLookup> { + static constexpr std::size_t size_ = sizeof...(_names); + + static constexpr std::array decl_names_ = { + _names.string_view()...}; + + static constexpr auto make_table() { + std::array table{}; + int idx = 0; + ((table[static_cast(idx)] = + FieldNameEntry{_names.string_view(), idx}, + ++idx), + ...); + if constexpr (size_ > 8) { + sort_field_name_table(table); + } + return table; + } + + static RFL_COLD int find(const std::string_view _name) noexcept { + if constexpr (size_ <= 8) { + for (std::size_t i = 0; i < size_; ++i) { + if (field_name_equals(decl_names_[i], _name)) { + return static_cast(i); + } + } + return -1; + } else { + static constexpr auto table = make_table(); + std::size_t lo = 0; + std::size_t hi = table.size(); + while (lo < hi) { + const std::size_t mid = lo + (hi - lo) / 2; + if (table[mid].name < _name) { + lo = mid + 1; + } else { + hi = mid; + } + } + if (lo < table.size() && field_name_equals(table[lo].name, _name)) { + return table[lo].field_idx; + } + return -1; + } + } + + static RFL_ALWAYS_INLINE int find_with_hint(const std::string_view _name, + std::size_t& _next_idx) noexcept { + if (_next_idx < size_ && field_name_equals(decl_names_[_next_idx], _name)) + [[likely]] { + const int idx = static_cast(_next_idx); + ++_next_idx; + return idx; + } + const int idx = find(_name); + if (idx >= 0) { + _next_idx = static_cast(idx) + 1; + } + return idx; + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/make_type_name.hpp b/include/rfl/parsing/make_type_name.hpp index 35e9a554b..0d0ad397a 100644 --- a/include/rfl/parsing/make_type_name.hpp +++ b/include/rfl/parsing/make_type_name.hpp @@ -1,6 +1,9 @@ #ifndef RFL_PARSING_MAKETYPENAME_HPP_ #define RFL_PARSING_MAKETYPENAME_HPP_ +#include +#include + #include "../type_name_t.hpp" #include "is_tagged_union_wrapper.hpp" @@ -14,7 +17,7 @@ namespace rfl::parsing { */ inline std::string replace_non_alphanumeric(std::string _str) { for (auto& ch : _str) { - ch = std::isalnum(ch) ? ch : '_'; + ch = std::isalnum(static_cast(ch)) ? ch : '_'; } return _str; } diff --git a/include/rfl/parsing/schema/Type.hpp b/include/rfl/parsing/schema/Type.hpp index ea3bc17de..6c209a8bb 100644 --- a/include/rfl/parsing/schema/Type.hpp +++ b/include/rfl/parsing/schema/Type.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_SCHEMA_TYPE_HPP_ #include +#include #include #include #include @@ -33,6 +34,11 @@ struct RFL_API Type { struct Integer {}; + struct BoundedInteger { + std::int64_t minimum_; + std::uint64_t maximum_; + }; + struct Float {}; struct Double {}; @@ -41,6 +47,11 @@ struct RFL_API Type { struct AnyOf { std::vector types_; + /// True if a value may match only one of the types: always for a tagged + /// union, whose alternatives differ in their tag, and for other variants + /// when the VariantsAsOneOf processor is passed. JSON schema emits these + /// as oneOf instead of anyOf. + bool mutually_exclusive_ = false; }; struct Deprecated { @@ -116,8 +127,8 @@ struct RFL_API Type { using VariantType = rfl::Variant; diff --git a/include/rfl/thirdparty/enchantum/details/enchantum_msvc.hpp b/include/rfl/thirdparty/enchantum/details/enchantum_msvc.hpp index a72e3193c..c410927eb 100644 --- a/include/rfl/thirdparty/enchantum/details/enchantum_msvc.hpp +++ b/include/rfl/thirdparty/enchantum/details/enchantum_msvc.hpp @@ -27,7 +27,8 @@ namespace details { if constexpr (ScopedEnum) { if (s.front() == '(') { s.remove_prefix(sizeof("(enum ") - 1); - s.remove_suffix(sizeof(")0x0") - 1); + // MSVC appends an extra 0 (")0x00") for 8-byte enum casts (ZXShady/enchantum@66acc35f). + s.remove_suffix(sizeof(")0x0") - 1 + (sizeof(Enum) == 8)); return s; } return s.substr(0, s.rfind("::")); @@ -35,7 +36,7 @@ namespace details { else { if (s.front() == '(') { s.remove_prefix(sizeof("(enum ") - 1); - s.remove_suffix(sizeof(")0x0") - 1); + s.remove_suffix(sizeof(")0x0") - 1 + (sizeof(Enum) == 8)); } if (const auto pos = s.rfind("::"); pos != s.npos) return s.substr(0, pos); diff --git a/include/rfl/type_name.hpp b/include/rfl/type_name.hpp new file mode 100644 index 000000000..b5f594cae --- /dev/null +++ b/include/rfl/type_name.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_TYPE_NAME_HPP_ +#define RFL_TYPE_NAME_HPP_ + +#include + +#include "internal/get_type_name.hpp" + +namespace rfl { + +/// Compile-time `std::string_view` containing the name of type `T` without +/// instantiating an `rfl::Literal` or `rfl::internal::StringLiteral`. +/// @tparam T The type whose name to retrieve +template +inline constexpr std::string_view type_name_v = + internal::get_type_name_str_view(); + +/// Returns the compile-time name of type `T` as a `std::string_view` (usable +/// in both `constexpr` and runtime contexts). +/// @tparam T The type whose name to retrieve +template +constexpr std::string_view type_name() noexcept { + return type_name_v; +} + +} // namespace rfl + +#endif diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp index 6ef06975b..c3eb1f6d7 100644 --- a/include/rfl/xml/Reader.hpp +++ b/include/rfl/xml/Reader.hpp @@ -64,12 +64,12 @@ struct Reader { const size_t _idx, const InputArrayType& _arr) const noexcept { const auto name = _arr.node_.name(); size_t i = 0; - for (auto node = _arr.node_; node; node = node.next_sibling(name)) { + for (auto node = _arr.node_; node; node = node.next_sibling(name), ++i) { if (i == _idx) { return InputVarType(node); } } - return error("Index " + std::to_string(_idx) + " of of bounds."); + return error("Index " + std::to_string(_idx) + " out of bounds."); } /// Retrieves a field from an XML object by name. diff --git a/include/rfl/xml/write.hpp b/include/rfl/xml/write.hpp index c71d937a6..51841e172 100644 --- a/include/rfl/xml/write.hpp +++ b/include/rfl/xml/write.hpp @@ -87,7 +87,7 @@ template std::string write(const auto& _obj, const std::string& _indent = " ") { std::stringstream stream; - write<_root, Ps...>(_obj, stream); + write<_root, Ps...>(_obj, stream, _indent); return stream.str(); } diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index c8625c04a..d5c459798 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -4,7 +4,9 @@ #include #include +#include #include +#include #include #include #include @@ -18,6 +20,7 @@ #include "../Result.hpp" #include "../always_false.hpp" +#include "../common.hpp" namespace rfl { namespace yaml { @@ -59,6 +62,23 @@ struct Reader { static constexpr bool has_custom_constructor = (requires(InputVarType var) { T::from_yaml_obj(var); }); + /// @brief RAII guard tracking ancestor YAML nodes on the current thread to + /// reject cyclic aliases while keeping const Reader instances thread-safe and + /// allowing non-cyclic (DAG) alias reuse. + class RFL_API ActiveNodeGuard { + public: + explicit ActiveNodeGuard(const YAML::Node& _node); + ~ActiveNodeGuard(); + ActiveNodeGuard(const ActiveNodeGuard&) = delete; + ActiveNodeGuard& operator=(const ActiveNodeGuard&) = delete; + + bool is_cycle() const noexcept { return is_cycle_; } + + private: + bool is_cycle_; + bool pushed_; + }; + /// @brief Constructs a Reader from a YAML string view. /// @param _yaml_str The YAML document as a string view. Reader(const std::string_view& _yaml_str) noexcept : yaml_str_(_yaml_str) {} @@ -105,11 +125,12 @@ struct Reader { template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { try { - if constexpr (std::is_same, std::string>() || - std::is_same, bool>() || - std::is_floating_point>()) { - auto result = _var.node_.as>(); - if constexpr (std::is_same, std::string>()) { + using Target = std::remove_cvref_t; + if constexpr (std::is_same() || + std::is_same() || + std::is_floating_point()) { + auto result = _var.node_.as(); + if constexpr (std::is_same()) { // In case of multi-line YAML literal strings, yaml-cpp may parse an // extra new line which is not there intentionally. This may break // multiple re-serialization checks, for this reason we trim trailing @@ -117,8 +138,10 @@ struct Reader { // // This is only done for literal blocks which doesn't have tags or // anchors - if (_var.node_.Tag() == "!" && - yaml_str_[_var.node_.Mark().pos] == '|') { + const auto pos = _var.node_.Mark().pos; + if (_var.node_.Tag() == "!" && pos >= 0 && + static_cast(pos) < yaml_str_.size() && + yaml_str_[static_cast(pos)] == '|') { auto last_non_new_line = result.find_last_not_of("\r\n"); if (last_non_new_line != std::string::npos) { result = result.substr(0, last_non_new_line + 1); @@ -127,14 +150,49 @@ struct Reader { } return result; - } else if constexpr (std::is_integral>()) { - return static_cast(_var.node_.as>()); + } else if constexpr (std::is_unsigned()) { + if (!_var.node_.IsScalar()) { + return error("Could not cast to uint."); + } + const auto& scalar = _var.node_.Scalar(); + const auto first = scalar.find_first_not_of(" \t\r\n\v\f"); + if (first != std::string::npos && scalar[first] == '-') { + return error("Could not cast to uint."); + } + const auto value = _var.node_.as(); + if constexpr (static_cast( + std::numeric_limits::max()) < + std::numeric_limits::max()) { + if (value > + static_cast(std::numeric_limits::max())) { + return error("Integer is out of range for the target type."); + } + } + return static_cast(value); + + } else if constexpr (std::is_integral()) { + if (!_var.node_.IsScalar()) { + return error("Could not cast to int."); + } + const auto value = _var.node_.as(); + if constexpr (std::numeric_limits::min() > + std::numeric_limits::min() || + std::numeric_limits::max() < + std::numeric_limits::max()) { + if (value < + static_cast(std::numeric_limits::min()) || + value > + static_cast(std::numeric_limits::max())) { + return error("Integer is out of range for the target type."); + } + } + return static_cast(value); } else { static_assert(rfl::always_false_v, "Unsupported type."); } - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); } } @@ -159,6 +217,10 @@ struct Reader { template std::optional read_array(const ArrayReader& _array_reader, const InputArrayType& _arr) const noexcept { + const ActiveNodeGuard guard(_arr.node_); + if (guard.is_cycle()) { + return Error("Recursive YAML alias detected."); + } if constexpr (requires { _array_reader.reserve(_arr.node_.size()); }) { if (auto err = _array_reader.reserve(_arr.node_.size())) { return err; @@ -182,13 +244,24 @@ struct Reader { template std::optional read_object(const ObjectReader& _object_reader, const InputObjectType& _obj) const noexcept { + const ActiveNodeGuard guard(_obj.node_); + if (guard.is_cycle()) { + return Error("Recursive YAML alias detected."); + } for (const auto& p : _obj.node_) { + std::string_view key; try { - const auto k = p.first.as(); - _object_reader.read(std::string_view(k), InputVarType(p.second)); - } catch (std::exception& e) { - continue; + if (p.first.IsScalar()) { + key = p.first.Scalar(); + } else if (p.first.IsNull()) { + key = "null"; + } else { + return Error("YAML mapping key must be a scalar."); + } + } catch (const std::exception& e) { + return Error(e.what()); } + _object_reader.read(key, InputVarType(p.second)); } return std::nullopt; } diff --git a/include/rfl/yaml/Writer.hpp b/include/rfl/yaml/Writer.hpp index 04412791f..35f292629 100644 --- a/include/rfl/yaml/Writer.hpp +++ b/include/rfl/yaml/Writer.hpp @@ -3,6 +3,7 @@ #include +#include #include #include #include @@ -196,19 +197,23 @@ class RFL_API Writer { template OutputVarType insert_value(const std::string_view& _name, const T& _var) const { - if constexpr (std::is_same, std::string>() || - std::is_same, bool>() || - std::is_same, + using Target = std::remove_cvref_t; + if constexpr (std::is_same() || + std::is_same() || + std::is_same>()) { (*out_) << YAML::Key << std::string(_name) << YAML::Value; insert_literal_block_if_needed(_var); (*out_) << _var; - } else if constexpr (std::is_floating_point>()) { + } else if constexpr (std::is_floating_point()) { // std::to_string is necessary to ensure that floating point values are // always written as floats. (*out_) << YAML::Key << std::string(_name) << YAML::Value << std::to_string(_var); - } else if constexpr (std::is_integral>()) { + } else if constexpr (std::is_unsigned()) { + (*out_) << YAML::Key << std::string(_name) << YAML::Value + << static_cast(_var); + } else if constexpr (std::is_integral()) { (*out_) << YAML::Key << std::string(_name) << YAML::Value << static_cast(_var); } else { @@ -223,17 +228,20 @@ class RFL_API Writer { /// @return OutputVarType representing the inserted value. template OutputVarType insert_value(const T& _var) const { - if constexpr (std::is_same, std::string>() || - std::is_same, bool>() || - std::is_same, + using Target = std::remove_cvref_t; + if constexpr (std::is_same() || + std::is_same() || + std::is_same>()) { insert_literal_block_if_needed(_var); (*out_) << _var; - } else if constexpr (std::is_floating_point>()) { + } else if constexpr (std::is_floating_point()) { // std::to_string is necessary to ensure that floating point values are // always written as floats. (*out_) << std::to_string(_var); - } else if constexpr (std::is_integral>()) { + } else if constexpr (std::is_unsigned()) { + (*out_) << static_cast(_var); + } else if constexpr (std::is_integral()) { (*out_) << static_cast(_var); } else { static_assert(rfl::always_false_v, "Unsupported type."); diff --git a/scripts/bind_to_tuple.py b/scripts/bind_to_tuple.py index 5b29d356d..f3b38224f 100644 --- a/scripts/bind_to_tuple.py +++ b/scripts/bind_to_tuple.py @@ -1,5 +1,5 @@ """ -Creates the boilerplate code in rfl/internal/bind_to_tuple.hpp +Creates the boilerplate code in rfl/internal/cpp20/bind_to_tuple.hpp """ @@ -35,10 +35,10 @@ def _generate_bind_to_tuple_impl(maximum: int) -> str: macros = _generate_macros(1, maximum) return ( """ -template -auto bind_to_tuple_impl(auto& _t) { +template +decltype(auto) apply_to_fields_impl(T& _t, F&& _f) { if constexpr(_num_fields == 0) { - return rfl::make_tuple(); + return std::forward(_f)(); } else { """ + macros diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index ea76c27ca..d0f6de31b 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -30,6 +30,7 @@ SOFTWARE. // compilation. #include "rfl/Generic.cpp" +#include "rfl/TransformEnumNames.cpp" #include "rfl/env/Writer.cpp" #include "rfl/generic/Writer.cpp" #include "rfl/internal/strings/strings.cpp" diff --git a/src/reflectcpp_json.cpp b/src/reflectcpp_json.cpp index 7b7bd66e6..3d8f8ded9 100644 --- a/src/reflectcpp_json.cpp +++ b/src/reflectcpp_json.cpp @@ -29,5 +29,6 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. +#include "rfl/json/Raw.cpp" #include "rfl/json/Writer.cpp" #include "rfl/json/to_schema.cpp" diff --git a/src/reflectcpp_yaml.cpp b/src/reflectcpp_yaml.cpp index 3f3f1beab..8e6b2aad2 100644 --- a/src/reflectcpp_yaml.cpp +++ b/src/reflectcpp_yaml.cpp @@ -29,4 +29,5 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. +#include "rfl/yaml/Reader.cpp" #include "rfl/yaml/Writer.cpp" diff --git a/src/rfl/TransformEnumNames.cpp b/src/rfl/TransformEnumNames.cpp new file mode 100644 index 000000000..1bbc1f0ae --- /dev/null +++ b/src/rfl/TransformEnumNames.cpp @@ -0,0 +1,118 @@ +#include "rfl/TransformEnumNames.hpp" + +#include +#include +#include + +namespace rfl { +namespace { + +constexpr char ascii_to_upper(const char _ch) noexcept { + return (_ch >= 'a' && _ch <= 'z') ? static_cast(_ch - ('a' - 'A')) + : _ch; +} + +constexpr char ascii_to_lower(const char _ch) noexcept { + return (_ch >= 'A' && _ch <= 'Z') ? static_cast(_ch + ('a' - 'A')) + : _ch; +} + +constexpr bool ascii_is_upper(const char _ch) noexcept { + return _ch >= 'A' && _ch <= 'Z'; +} + +constexpr bool ascii_is_lower(const char _ch) noexcept { + return _ch >= 'a' && _ch <= 'z'; +} + +} // namespace + +std::string apply_enum_name_transform(const std::string_view _name, + const EnumNameTransform _transform) { + switch (_transform) { + case EnumNameTransform::none: + return std::string(_name); + case EnumNameTransform::snake_to_kebab: { + std::string out(_name); + for (char& ch : out) { + if (ch == '_') { + ch = '-'; + } + } + return out; + } + case EnumNameTransform::snake_to_camel: { + std::string out; + out.reserve(_name.size()); + bool cap_next = false; + for (const char ch : _name) { + if (ch == '_') { + if (!out.empty()) { + cap_next = true; + } + } else if (out.empty()) { + out.push_back(ascii_to_lower(ch)); + } else if (cap_next) { + out.push_back(ascii_to_upper(ch)); + cap_next = false; + } else { + out.push_back(ch); + } + } + return out; + } + case EnumNameTransform::snake_to_pascal: { + std::string out; + out.reserve(_name.size()); + bool cap_next = true; + for (const char ch : _name) { + if (ch == '_') { + cap_next = true; + } else if (cap_next) { + out.push_back(ascii_to_upper(ch)); + cap_next = false; + } else { + out.push_back(ch); + } + } + return out; + } + case EnumNameTransform::camel_to_snake: { + std::string out; + out.reserve(_name.size() + 4); + for (std::size_t i = 0; i < _name.size(); ++i) { + const char ch = _name[i]; + if (ascii_is_upper(ch)) { + if (i > 0 && _name[i - 1] != '_' && + (ascii_is_lower(_name[i - 1]) || + (i + 1 < _name.size() && ascii_is_lower(_name[i + 1])))) { + out.push_back('_'); + } + out.push_back(ascii_to_lower(ch)); + } else { + out.push_back(ch); + } + } + return out; + } + case EnumNameTransform::to_lower: { + std::string out; + out.reserve(_name.size()); + for (const char ch : _name) { + out.push_back(ascii_to_lower(ch)); + } + return out; + } + case EnumNameTransform::to_upper: { + std::string out; + out.reserve(_name.size()); + for (const char ch : _name) { + out.push_back(ascii_to_upper(ch)); + } + return out; + } + } + return std::string(_name); +} + +} // namespace rfl diff --git a/src/rfl/avro/to_schema.cpp b/src/rfl/avro/to_schema.cpp index 5b8e25a3b..c8a99bd45 100644 --- a/src/rfl/avro/to_schema.cpp +++ b/src/rfl/avro/to_schema.cpp @@ -26,6 +26,9 @@ SOFTWARE. #include "rfl/avro/to_schema.hpp" +#include +#include + #include "rfl/avro/schema/Type.hpp" #include "rfl/json.hpp" #include "rfl/parsing/schemaful/tuple_to_object.hpp" @@ -35,8 +38,13 @@ namespace rfl::avro { inline bool is_named_type(const parsing::schema::Type& _type) { return _type.variant_.visit([&](const auto& _v) -> bool { using T = std::remove_cvref_t; - return std::is_same() || - std::is_same(); + if constexpr (std::is_same_v || + std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same(); + } }); } @@ -63,6 +71,14 @@ schema::Type type_to_avro_schema_type( std::is_same()) { return schema::Type{.value = schema::Type::Long{}}; + } else if constexpr (std::is_same()) { + const bool fits_i32 = + _t.minimum_ >= std::numeric_limits::min() && + _t.maximum_ <= static_cast( + std::numeric_limits::max()); + return fits_i32 ? schema::Type{.value = schema::Type::Int{}} + : schema::Type{.value = schema::Type::Long{}}; + } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::Float{}}; diff --git a/src/rfl/capnproto/to_schema.cpp b/src/rfl/capnproto/to_schema.cpp index 6d166e286..cb04f3cc7 100644 --- a/src/rfl/capnproto/to_schema.cpp +++ b/src/rfl/capnproto/to_schema.cpp @@ -26,6 +26,8 @@ SOFTWARE. #include "rfl/capnproto/to_schema.hpp" +#include +#include #include #include #include @@ -139,6 +141,18 @@ schema::Type reference_to_capnproto_schema_type( } } +inline bool is_literal_type(const parsing::schema::Type& _type) { + return _type.variant_.visit([](const auto& _v) -> bool { + using T = std::remove_cvref_t; + if constexpr (std::is_same_v || + std::is_same_v) { + return is_literal_type(*_v.type_); + } else { + return std::is_same_v; + } + }); +} + schema::Type string_map_to_capnproto_schema_type( const parsing::schema::Type::StringMap& _map, const std::map& _definitions, @@ -151,12 +165,7 @@ schema::Type string_map_to_capnproto_schema_type( if constexpr (std::is_same_v) { const auto it = _definitions.find(_value.type_name); return _cnp_types->enums_.contains(_value.type_name) || - (it != _definitions.end() && - it->second.variant_.visit([](const auto& _definition) { - return std::is_same_v< - std::remove_cvref_t, - parsing::schema::Type::Literal>; - })); + (it != _definitions.end() && is_literal_type(it->second)); } else { return !std::is_same_v && !std::is_same_v && !std::is_same_v && !std::is_same_v && @@ -196,6 +205,20 @@ schema::Type type_to_capnproto_schema_type( std::is_same()) { return schema::Type{.value = schema::Type::Int32{}}; + } else if constexpr (std::is_same()) { + if (_t.minimum_ < 0) { + const bool fits_i32 = + _t.minimum_ >= std::numeric_limits::min() && + _t.maximum_ <= static_cast( + std::numeric_limits::max()); + return fits_i32 ? schema::Type{.value = schema::Type::Int32{}} + : schema::Type{.value = schema::Type::Int64{}}; + } + const bool fits_u32 = + _t.maximum_ <= std::numeric_limits::max(); + return fits_u32 ? schema::Type{.value = schema::Type::UInt32{}} + : schema::Type{.value = schema::Type::UInt64{}}; + } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::Int64{}}; diff --git a/src/rfl/json/Raw.cpp b/src/rfl/json/Raw.cpp new file mode 100644 index 000000000..fab1d12f6 --- /dev/null +++ b/src/rfl/json/Raw.cpp @@ -0,0 +1,98 @@ +/* + +MIT License + +Copyright (c) 2023-2024 Code17 GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +#include "rfl/json/Raw.hpp" + +#if __has_include() +#include +#else +#include "rfl/thirdparty/yyjson.h" +#endif + +#include +#include +#include +#include +#include + +#include "rfl/json/read.hpp" +#include "rfl/json/write.hpp" + +namespace rfl::json { + +Result Raw::from_string(const std::string_view _str) { + if (_str.empty()) { + return error("Invalid raw JSON: input is empty."); + } + yyjson_read_err err{}; + yyjson_doc* doc = yyjson_read_opts(const_cast(_str.data()), + _str.size(), 0, nullptr, &err); + if (!doc) { + return error("Invalid raw JSON: " + + std::string(err.msg ? err.msg : "parse error")); + } + yyjson_doc_free(doc); + return Raw(std::string(_str)); +} + +Result Raw::from_json_obj(const Reader::YYJSONInputVar& _var) { + if (!_var.val_) { + return error("Cannot construct rfl::json::Raw from null JSON value."); + } + struct FreeDeleter { + void operator()(char* _p) const noexcept { std::free(_p); } + }; + yyjson_write_err err{}; + size_t len = 0; + std::unique_ptr buf( + yyjson_val_write_opts(_var.val_, 0, nullptr, &len, &err)); + if (!buf) { + return error("Could not serialize JSON value into rfl::json::Raw: " + + std::string(err.msg ? err.msg : "write error")); + } + return Raw(std::string(buf.get(), len)); +} + +Result Raw::to_generic() const { + if (value_.empty()) { + return Generic(); + } + return rfl::json::read(value_); +} + +Result Raw::from_generic(const Generic& _g) noexcept { + try { + return Raw(rfl::json::write(_g)); + } catch (const std::exception& _e) { + return error( + std::string("Could not serialize rfl::Generic into rfl::json::Raw: ") + + _e.what()); + } catch (...) { + return error("Could not serialize rfl::Generic into rfl::json::Raw."); + } +} + +} // namespace rfl::json diff --git a/src/rfl/json/Writer.cpp b/src/rfl/json/Writer.cpp index fbb5e3234..2c179cf35 100644 --- a/src/rfl/json/Writer.cpp +++ b/src/rfl/json/Writer.cpp @@ -28,6 +28,16 @@ SOFTWARE. namespace rfl::json { +namespace { + +yyjson_mut_val* make_raw_or_null(yyjson_mut_doc* _doc, + const std::string_view _str) noexcept { + return _str.empty() ? yyjson_mut_null(_doc) + : yyjson_mut_rawncpy(_doc, _str.data(), _str.size()); +} + +} // namespace + Writer::Writer() : doc_(std::shared_ptr(yyjson_mut_doc_new(NULL), yyjson_mut_doc_free)) {} @@ -50,6 +60,13 @@ Writer::OutputVarType Writer::null_as_root() const noexcept { return OutputVarType(null); } +Writer::OutputVarType Writer::raw_as_root( + const std::string_view& _str) const noexcept { + const auto val = make_raw_or_null(doc(), _str); + yyjson_mut_doc_set_root(doc(), val); + return OutputVarType(val); +} + Writer::OutputArrayType Writer::add_array_to_array( const size_t, OutputArrayType* _parent) const { const auto arr = yyjson_mut_arr(doc()); @@ -118,6 +135,30 @@ Writer::OutputVarType Writer::add_null_to_object( return OutputVarType(null); } +Writer::OutputVarType Writer::add_raw_to_array( + const std::string_view& _str, OutputArrayType* _parent) const { + const auto val = make_raw_or_null(doc(), _str); + const bool ok = yyjson_mut_arr_add_val(_parent->val_, val); + if (!ok) { + throw std::runtime_error("Adding raw JSON to an array failed."); + } + return OutputVarType(val); +} + +Writer::OutputVarType Writer::add_raw_to_object( + const std::string_view& _name, const std::string_view& _str, + OutputObjectType* _parent) const { + const auto val = make_raw_or_null(doc(), _str); + const bool ok = yyjson_mut_obj_add( + _parent->val_, yyjson_mut_strncpy(doc(), _name.data(), _name.size()), + val); + if (!ok) { + throw std::runtime_error("Could not add field '" + std::string(_name) + + "' to object."); + } + return OutputVarType(val); +} + void Writer::end_array(OutputArrayType*) const noexcept {} void Writer::end_object(OutputObjectType*) const noexcept {} diff --git a/src/rfl/json/to_schema.cpp b/src/rfl/json/to_schema.cpp index 3fda88bd2..2cdff6e92 100644 --- a/src/rfl/json/to_schema.cpp +++ b/src/rfl/json/to_schema.cpp @@ -62,7 +62,8 @@ std::string numeric_type_to_string(const parsing::schema::Type& _type) { std::is_same() || std::is_same() || std::is_same() || - std::is_same()) { + std::is_same() || + std::is_same()) { return schema::Type::Integer{}.type.str(); } else { return schema::Type::Number{}.type.str(); @@ -204,6 +205,10 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::Boolean{}}; + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Integer{ + .minimum = _t.minimum_, .maximum = _t.maximum_}}; + } else if constexpr (std::is_same() || std::is_same() || std::is_same() || @@ -228,7 +233,12 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, for (const auto& t : _t.types_) { any_of.emplace_back(type_to_json_schema_type(t, _no_required)); } - return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}}; + if (_t.mutually_exclusive_) { + return schema::Type{ + .value = schema::Type::OneOf{.oneOf = std::move(any_of)}}; + } + return schema::Type{ + .value = schema::Type::AnyOf{.anyOf = std::move(any_of)}}; } else if constexpr (std::is_same()) { auto res = type_to_json_schema_type(*_t.type_, _no_required); @@ -318,10 +328,31 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, .additionalProperties = additional_properties}}; } else if constexpr (std::is_same()) { + auto has_annotations = [](const schema::Type::Annotations& _a) { + const auto& [description, deprecated, deprecation_message, + default_value] = _a; + return description.has_value() || deprecated.has_value() || + deprecation_message.has_value() || + default_value.value().has_value(); + }; + auto inner = type_to_json_schema_type(*_t.type_, _no_required); + if (auto* any_of = rfl::get_if(&inner.value); + any_of && !has_annotations(any_of->annotations.value_)) { + bool has_null = false; + for (const auto& branch : any_of->anyOf) { + if (rfl::holds_alternative(branch.value)) { + has_null = true; + break; + } + } + if (!has_null) { + any_of->anyOf.emplace_back(schema::Type{schema::Type::Null{}}); + } + return inner; + } return schema::Type{ .value = schema::Type::AnyOf{ - .anyOf = {type_to_json_schema_type(*_t.type_, _no_required), - schema::Type{schema::Type::Null{}}}}}; + .anyOf = {std::move(inner), schema::Type{schema::Type::Null{}}}}}; } else if constexpr (std::is_same()) { return schema::Type{ @@ -347,7 +378,15 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, type_to_json_schema_type(*_t.type_, _no_required))}}; } else if constexpr (std::is_same()) { - return handle_validation_type(*_t.type_, _t.validation_, _no_required); + auto validated = + handle_validation_type(*_t.type_, _t.validation_, _no_required); + if (rfl::holds_alternative(_t.type_->variant_)) { + auto bounded = type_to_json_schema_type(*_t.type_, _no_required); + return schema::Type{ + .value = schema::Type::AllOf{ + .allOf = {std::move(bounded), std::move(validated)}}}; + } + return validated; } else { static_assert(rfl::always_false_v, "Not all cases were covered."); diff --git a/src/rfl/yaml/Reader.cpp b/src/rfl/yaml/Reader.cpp new file mode 100644 index 000000000..7aae58866 --- /dev/null +++ b/src/rfl/yaml/Reader.cpp @@ -0,0 +1,48 @@ +#include "rfl/yaml/Reader.hpp" + +#include + +namespace rfl::yaml { + +namespace { + +std::vector& active_nodes() noexcept { + static thread_local std::vector nodes; + return nodes; +} + +bool is_active_node(const std::vector& _nodes, + const YAML::Node& _node) noexcept { + if (!_node.IsDefined()) { + return false; + } + for (const auto& active : _nodes) { + if (active.is(_node)) { + return true; + } + } + return false; +} + +} // namespace + +Reader::ActiveNodeGuard::ActiveNodeGuard(const YAML::Node& _node) + : is_cycle_(false), pushed_(false) { + auto& nodes = active_nodes(); + if (is_active_node(nodes, _node)) { + is_cycle_ = true; + return; + } + if (_node.IsDefined()) { + nodes.push_back(_node); + pushed_ = true; + } +} + +Reader::ActiveNodeGuard::~ActiveNodeGuard() { + if (pushed_) { + active_nodes().pop_back(); + } +} + +} // namespace rfl::yaml diff --git a/tests/avro/test_description_deprecated_named_type.cpp b/tests/avro/test_description_deprecated_named_type.cpp new file mode 100644 index 000000000..f286ebe02 --- /dev/null +++ b/tests/avro/test_description_deprecated_named_type.cpp @@ -0,0 +1,67 @@ +#include + +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_avro_description_deprecated_named_type { + +struct DescribedRetries { + using Inner = rfl::NamedTuple>; + using ReflectionType = rfl::Description<"Nested retry settings", Inner>; + + DescribedRetries() = default; + DescribedRetries(const ReflectionType& _value) + : retries(rfl::get<"retries">(_value.value())) {} + + ReflectionType reflection() const { + return ReflectionType(Inner(rfl::make_field<"retries">(retries))); + } + + int retries = 3; +}; + +struct DeprecatedRetries { + using Inner = rfl::NamedTuple>; + using ReflectionType = + rfl::Deprecated<"Use DescribedRetries", "Legacy retry settings", Inner>; + + DeprecatedRetries() = default; + DeprecatedRetries(const ReflectionType& _value) + : retries(rfl::get<"retries">(_value.value())) {} + + ReflectionType reflection() const { + return ReflectionType(Inner(rfl::make_field<"retries">(retries))); + } + + int retries = 1; +}; + +struct OuterConfig { + std::string name; + DescribedRetries primary; + DescribedRetries secondary; + DeprecatedRetries fallback; +}; + +TEST(avro, test_description_and_deprecated_named_type) { + const auto schema = rfl::avro::to_schema(); + EXPECT_NE(schema.str().find(R"("DescribedRetries")"), std::string::npos); + EXPECT_NE(schema.str().find(R"("DeprecatedRetries")"), std::string::npos); + EXPECT_EQ(schema.str().find(R"("unnamed_)"), std::string::npos); + + const auto cfg = OuterConfig{ + .name = "svc", + .primary = DescribedRetries(DescribedRetries::ReflectionType( + DescribedRetries::Inner(rfl::make_field<"retries">(5)))), + .secondary = DescribedRetries(DescribedRetries::ReflectionType( + DescribedRetries::Inner(rfl::make_field<"retries">(2)))), + .fallback = DeprecatedRetries(DeprecatedRetries::ReflectionType( + DeprecatedRetries::Inner(rfl::make_field<"retries">(1))))}; + write_and_read(cfg); +} + +} // namespace test_avro_description_deprecated_named_type diff --git a/tests/capnproto/test_description_deprecated_named_type.cpp b/tests/capnproto/test_description_deprecated_named_type.cpp new file mode 100644 index 000000000..2bb4003c0 --- /dev/null +++ b/tests/capnproto/test_description_deprecated_named_type.cpp @@ -0,0 +1,80 @@ +#include + +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_capnproto_description_deprecated_named_type { + +struct DescribedRetries { + using Inner = rfl::NamedTuple>; + using ReflectionType = rfl::Description<"Nested retry settings", Inner>; + + DescribedRetries() = default; + DescribedRetries(const ReflectionType& _value) + : retries(rfl::get<"retries">(_value.value())) {} + + ReflectionType reflection() const { + return ReflectionType(Inner(rfl::make_field<"retries">(retries))); + } + + int retries = 3; +}; + +struct DescribedColor { + using Inner = rfl::Literal<"red", "green", "blue">; + using ReflectionType = rfl::Description<"Primary color", Inner>; + + DescribedColor() = default; + DescribedColor(const ReflectionType& _value) : value_(_value.value()) {} + + ReflectionType reflection() const { return ReflectionType(value_); } + + private: + Inner value_ = Inner::make<"red">(); +}; + +struct DeprecatedColor { + using Inner = rfl::Literal<"cyan", "magenta">; + using ReflectionType = + rfl::Deprecated<"Use DescribedColor", "Legacy color", Inner>; + + DeprecatedColor() = default; + DeprecatedColor(const ReflectionType& _value) : value_(_value.value()) {} + + ReflectionType reflection() const { return ReflectionType(value_); } + + private: + Inner value_ = Inner::make<"cyan">(); +}; + +struct OuterConfig { + std::string name; + DescribedRetries retries; + std::map colors; + std::map legacy_colors; +}; + +TEST(capnproto, test_description_and_deprecated_named_type) { + const auto schema = rfl::capnproto::to_schema(); + EXPECT_NE(schema.str().find("DescribedRetries"), std::string::npos); + EXPECT_NE(schema.str().find("ScalarMap"), std::string::npos); + + const auto cfg = OuterConfig{ + .name = "svc", + .retries = DescribedRetries(DescribedRetries::ReflectionType( + DescribedRetries::Inner(rfl::make_field<"retries">(5)))), + .colors = {{"primary", + DescribedColor(DescribedColor::ReflectionType( + DescribedColor::Inner::make<"blue">()))}}, + .legacy_colors = {{"old", + DeprecatedColor(DeprecatedColor::ReflectionType( + DeprecatedColor::Inner::make<"magenta">()))}}}; + write_and_read(cfg); +} + +} // namespace test_capnproto_description_deprecated_named_type diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp new file mode 100644 index 000000000..2ac41d4d7 --- /dev/null +++ b/tests/cli/test_usage.cpp @@ -0,0 +1,410 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_usage { + +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional input_file; + std::string host_name; + bool verbose; + std::vector tags; + rfl::Short<"p", int> port; + Database database; + std::optional log_level; +}; + +TEST(cli, test_usage_synopsis) { + // The exact string proposed in + // https://github.com/munich-data-engineering/reflect-cpp/issues/692. + EXPECT_EQ(rfl::cli::usage("my_binary").value(), + "Usage: my_binary --host-name= " + "--verbose[=] --tags= -p|--port= " + "--database.host= --database.port= " + "[--log-level=]\n"); +} + +// The issue's second example: rfl::Positional and rfl::Short inside +// rfl::Description, which the parser finds, and so does the help. +struct Described { + rfl::Description<"Path to the input file", rfl::Positional> + input_file; + rfl::Description<"Host to connect to", std::string> host_name; + bool verbose; + rfl::Description<"Port to connect on", rfl::Short<"p", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; +}; + +TEST(cli, test_usage_detailed) { + EXPECT_EQ( + rfl::cli::usage("my_binary", true).value(), + "Usage: my_binary --host-name= --verbose[=] " + "-p|--port= [--log-level=]\n" + "\n" + "Arguments:\n" + " Path to the input file. Required.\n" + " --host-name= Host to connect to. Required.\n" + " --verbose[=] Required.\n" + " -p, --port= Port to connect on. Required.\n" + " --log-level= Minimum level to log\n"); + + // What the help advertises is what the parser accepts. + const char* args[] = {"my_binary", "in.txt", "--host-name=localhost", + "--verbose", "-p", "8080", + "--log-level=warn"}; + const auto result = + rfl::cli::read(7, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input_file().value(), "in.txt"); + EXPECT_EQ(result.value().port().value(), 8080); + EXPECT_EQ(result.value().log_level.get(), LogLevel::warn); + + // A plain bool is required, as the help says. + const char* no_verbose[] = {"my_binary", "in.txt", "--host-name=localhost", + "-p", "8080"}; + EXPECT_FALSE(rfl::cli::read(5, const_cast(no_verbose))); +} + +struct Limits { + rfl::DefaultVal> per_host = 4; + int total; +}; + +/// rfl::DefaultVal combined with other wrappers. +struct WrappedDefaultVal { + rfl::DefaultVal< + rfl::Short<"l", rfl::Description<"Minimum level to log", LogLevel>>> + log_level = LogLevel::info; + rfl::DefaultVal> timeout = 30; + rfl::DefaultVal> output = "out.txt"; + rfl::Short<"n", rfl::Description<"Number of runs", int>> runs; + Limits limits; +}; + +TEST(cli, test_usage_wrapped_default_val) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app [-l|--log-level=] " + "[--timeout=] [] " + "-n|--runs= [--limits.per-host=] " + "--limits.total=\n" + "\n" + "Arguments:\n" + " -l, --log-level= Minimum level to log\n" + " --timeout= Seconds to wait\n" + " \n" + " -n, --runs= Number of runs. Required.\n" + " --limits.per-host= Connections per host\n" + " --limits.total= Required.\n"); + + // Everything the help leaves optional can be left out. + const char* minimal[] = {"app", "-n", "3", "--limits.total=8"}; + const auto defaulted = + rfl::cli::read(4, const_cast(minimal)); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().output.get().value(), "out.txt"); + + // What the help calls required is required. + const char* no_runs[] = {"app", "--limits.total=8"}; + EXPECT_FALSE( + rfl::cli::read(2, const_cast(no_runs))); + const char* no_total[] = {"app", "-n", "3"}; + EXPECT_FALSE( + rfl::cli::read(3, const_cast(no_total))); +} + +/// The default-constructed `port` does not satisfy its validator. +struct WithInvalidDefault { + rfl::Validator> port; + rfl::DefaultVal threads = 4; +}; + +/// The same with the DefaultVal inside rfl::Short. +struct WithInvalidWrappedDefault { + rfl::Validator> port; + rfl::Short<"t", rfl::DefaultVal> threads = 4; +}; + +struct WithInvalidWrappedDefaultInside { + WithInvalidWrappedDefault server; +}; + +/// Has no default constructor, so neither has a struct that contains it. +class Port { + public: + using ReflectionType = int; + Port(int _value) : value_(_value) {} + int reflection() const { return value_; } + + private: + int value_; +}; + +struct WithPort { + Port port; + int retries = 3; +}; + +/// A bare DefaultVal here would not compile: the struct has no default +/// constructor. A wrapped one is required. +struct WithPortAndDefaultVal { + Port port; + rfl::Description<"Retries", rfl::DefaultVal> retries = 3; +}; + +TEST(cli, test_usage_defaults_without_default_construction) { + // The parser fills in a missing DefaultVal field only after it + // default-constructed the struct. If that throws (`port`'s zero value + // fails its validator) or the struct has no default constructor, the + // field is required, and the help says so. + static_assert(!std::is_default_constructible_v); + // With a bare DefaultVal, every read fails, and so does usage: the schema + // takes the defaults from a default-constructed struct. + const auto invalid = rfl::cli::usage("app", true); + ASSERT_FALSE(invalid); + EXPECT_EQ(std::string(invalid.error().what()), + "Value expected to be greater than or equal to 1, but got 0."); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --port= -t|--threads=\n"); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --server.port= --server.threads=\n"); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --port= --retries=\n"); + + // A bare DefaultVal makes every read fail; a wrapped one is required. + const char* both[] = {"app", "--port=1", "--threads=2"}; + EXPECT_FALSE(rfl::cli::read(3, const_cast(both))); + const auto wrapped = rfl::cli::read( + 3, const_cast(both)); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().threads.value().get(), 2); + const char* port_only[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(port_only))); + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(port_only))); + const char* nested[] = {"app", "--server.port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(nested))); + + // With rfl::DefaultIfMissing nothing is required, even without T{}. + static_assert(!std::is_default_constructible_v); + EXPECT_EQ((rfl::cli::usage("app", true).value()), + "Usage: app [--port=] [--retries=]\n" + "\n" + "Arguments:\n" + " --port=\n" + " --retries=\n"); +} + +struct Inner { + std::string host = "db"; + int port = 5432; +}; + +struct WithInitializers { + int count = 3; + std::string name; + bool verbose = false; + std::optional limit; + Inner database; +}; + +TEST(cli, test_usage_without_default_if_missing) { + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --count= --name= --verbose[=] " + "[--limit=] --database.host= " + "--database.port=\n"); + + const char* args[] = {"app"}; + EXPECT_FALSE(rfl::cli::read(1, const_cast(args))); +} + +struct Tls { + bool verify; +}; + +struct WithNestedFlag { + Tls tls; +}; + +TEST(cli, test_usage_nested_flag) { + // A nested bool is a flag, as for the parser. + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --tls.verify[=]\n"); +} + +struct Address { + std::string city; + int zip; +}; + +struct Names { + rfl::Rename<"output_dir", std::string> output_dir; + rfl::Flatten

address; + std::optional backup; + std::map labels; +}; + +TEST(cli, test_usage_names) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app --output_dir= --city= --zip= " + "[--backup.host=] [--backup.port=] " + "--labels.=\n" + "\n" + "Arguments:\n" + " --output_dir= Required.\n" + " --city= Required.\n" + " --zip= Required.\n" + " --backup.host=\n" + " --backup.port=\n" + " --labels.= Required.\n"); + + const char* args[] = {"app", "--output_dir=/tmp", "--city=Springfield", + "--zip=12345", "--labels.env=prod"}; + const auto result = rfl::cli::read(5, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().labels.at("env"), "prod"); +} + +struct Optionals { + rfl::Positional> level; + rfl::Short<"v", std::optional> verbose; + rfl::Deprecated<"Use --port instead", "Old port", std::optional> + old_port; + rfl::Description<"First line\nSecond line", std::string> notes; +}; + +TEST(cli, test_usage_optionals) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app [] [-v|--verbose[=]] " + "[--old-port=] --notes=\n" + "\n" + "Arguments:\n" + " Choices: debug|info|warn.\n" + " -v, --verbose[=]\n" + " --old-port= Old port\n" + " --notes= First line\n" + " Second line. Required.\n"); +} + +TEST(cli, test_usage_no_optionals) { + // Processors are applied exactly as in read: with rfl::NoOptionals, + // optional fields are required. + EXPECT_EQ((rfl::cli::usage("app").value()), + "Usage: app -v|--verbose[=] --old-port= " + "--notes=\n"); +} + +struct Empty {}; + +TEST(cli, test_usage_empty) { + EXPECT_EQ(rfl::cli::usage("app").value(), "Usage: app\n"); + EXPECT_EQ(rfl::cli::usage("app", true).value(), "Usage: app\n"); +} + +struct CountingDefault { + static inline int ctor_count = 0; + static std::string make_host() { + ++ctor_count; + return "localhost"; + } + std::string host = make_host(); +}; + +TEST(cli, test_usage_does_not_default_construct_without_default_val) { + CountingDefault::ctor_count = 0; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --host=\n"); + EXPECT_EQ(CountingDefault::ctor_count, 0); +} + +class WrappedRoot { + public: + struct Impl { + std::string host_name; + std::optional port; + }; + using ReflectionType = Impl; + WrappedRoot(Impl _impl) : impl_(std::move(_impl)) {} + const Impl& reflection() const { return impl_; } + + private: + Impl impl_; +}; + +TEST(cli, test_usage_named_tuple_and_reflection_type) { + using NT = rfl::NamedTuple>, + rfl::Field<"my_req", std::string>, + rfl::Field<"my_flag", bool>>; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app [--my_opt=] --my_req= " + "--my_flag[=]\n"); + const char* nt_args[] = {"app", "--my_req=hi", "--my_flag"}; + const auto nt_res = rfl::cli::read(3, const_cast(nt_args)); + ASSERT_TRUE(nt_res) << nt_res.error().what(); + EXPECT_EQ(nt_res.value().get<"my_opt">().get(), 0); + + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --host-name= [--port=]\n"); +} + +struct RichMapsAndTypes { + std::map dbs; + std::map flags; + std::map levels; + rfl::Short<"l", std::map> labels; + rfl::Literal<"fast", "slow"> mode; + std::array coords; + std::tuple pair; +}; + +struct RecursiveNode { + std::string name; + std::unique_ptr next; +}; + +struct TrailingNewlineDesc { + rfl::Description<"Line 1\n\nLine 2\n", std::string> note; +}; + +TEST(cli, test_usage_maps_recursive_literals_and_formatting) { + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --dbs..host= --dbs..port= " + "--flags.[=] --levels.= " + "--labels.= --mode= " + "--coords= --pair=\n"); + + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --name= [--next=]\n"); + + EXPECT_EQ( + (rfl::cli::usage("app").value()), + "Usage: app --host-name= --verbose[=] " + "--tags= -p|--port= --database.host= " + "--database.port= [--log-level=]\n"); + + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app --note=\n" + "\n" + "Arguments:\n" + " --note= Line 1\n" + "\n" + " Line 2. Required.\n"); +} + +} // namespace test_usage diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp new file mode 100644 index 000000000..2c358699e --- /dev/null +++ b/tests/cli/test_usage_options.cpp @@ -0,0 +1,79 @@ +#include + +#include +#include +#include +#include +#include + +// rfl::cli::usage for the parser's option features: wrappers in any order +// and positional order. Each test also reads the arguments as the help +// spells them. +namespace test_usage_options { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "app"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +struct WrapperOrder { + rfl::Description<"Where to write", rfl::Short<"o", std::string>> output; + rfl::DefaultVal> input = "in.txt"; + rfl::Description<"Be verbose", rfl::Short<"v", std::optional>> + verbose; +}; + +TEST(cli, test_usage_wrapper_order) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app -o|--output= [] [-v|--verbose[=]]\n" + "\n" + "Arguments:\n" + " -o, --output= Where to write. Required.\n" + " \n" + " -v, --verbose[=] Be verbose\n"); + + const auto defaulted = read({"-o", "out"}); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().input.value().value(), "in.txt"); +} + +/// The parser fills the rfl::Positional fields in declaration order, wherever +/// rfl::Positional sits among their wrappers. +struct PositionalOrder { + rfl::Description<"Files to process", rfl::Positional> files; + rfl::Positional pair; + rfl::Positional command; +}; + +TEST(cli, test_usage_positional_order) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app \n" + "\n" + "Arguments:\n" + " Files to process. Required.\n" + " Required.\n" + " Required.\n"); + + const auto result = read({"x", "a", "run"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().pair.value(), "a"); + EXPECT_EQ(result.value().command.value(), "run"); + EXPECT_EQ(result.value().files.value().value(), "x"); +} + +/// Two fields with the same short name fail every read, and usage too. +struct ShortNameTaken { + rfl::Short<"o", std::string> output; + rfl::Description<"Where to log", rfl::Short<"o", std::string>> log; +}; + +TEST(cli, test_usage_short_name_taken) { + const auto usage = rfl::cli::usage("app", true); + ASSERT_FALSE(usage); + EXPECT_EQ(std::string(usage.error().what()), + "Duplicate short name '-o' in struct definition."); +} + +} // namespace test_usage_options diff --git a/tests/generic/test_enum.cpp b/tests/generic/test_enum.cpp index cec7f9650..ed9a7a5b2 100644 --- a/tests/generic/test_enum.cpp +++ b/tests/generic/test_enum.cpp @@ -1,4 +1,5 @@ #include +#include #include #include "write_and_read.hpp" @@ -8,6 +9,18 @@ namespace test_enum { enum class Color { red, green, blue, yellow }; enum Location { left, centre, right }; // Unscoped enum +enum class Signed64NoZero : int64_t { alpha = 1, beta = 2 }; +enum class Unsigned64NoZero : uint64_t { gamma = 1, delta = 2 }; +enum UnscopedSigned64NoZero : int64_t { u_alpha = 1, u_beta = 2 }; +enum UnscopedUnsigned64NoZero : uint64_t { u_gamma = 1, u_delta = 2 }; + +struct WideEnums { + Signed64NoZero s; + Unsigned64NoZero u; + UnscopedSigned64NoZero us; + UnscopedUnsigned64NoZero uu; +}; + struct Circle { float radius; Color color; @@ -21,4 +34,36 @@ TEST(generic, test_enum) { write_and_read(circle); } +TEST(generic, test_enum_64bit_nonzero) { + EXPECT_EQ(rfl::enum_to_string(Signed64NoZero::alpha), "alpha"); + EXPECT_EQ(rfl::enum_to_string(Signed64NoZero::beta), "beta"); + const auto parsed_s = rfl::string_to_enum("alpha"); + ASSERT_TRUE(parsed_s.has_value()) << parsed_s.error().what(); + EXPECT_EQ(*parsed_s, Signed64NoZero::alpha); + + EXPECT_EQ(rfl::enum_to_string(Unsigned64NoZero::gamma), "gamma"); + EXPECT_EQ(rfl::enum_to_string(Unsigned64NoZero::delta), "delta"); + const auto parsed_u = rfl::string_to_enum("delta"); + ASSERT_TRUE(parsed_u.has_value()) << parsed_u.error().what(); + EXPECT_EQ(*parsed_u, Unsigned64NoZero::delta); + + EXPECT_EQ(rfl::enum_to_string(u_alpha), "u_alpha"); + EXPECT_EQ(rfl::enum_to_string(u_beta), "u_beta"); + const auto parsed_us = rfl::string_to_enum("u_alpha"); + ASSERT_TRUE(parsed_us.has_value()) << parsed_us.error().what(); + EXPECT_EQ(*parsed_us, u_alpha); + + EXPECT_EQ(rfl::enum_to_string(u_gamma), "u_gamma"); + EXPECT_EQ(rfl::enum_to_string(u_delta), "u_delta"); + const auto parsed_uu = + rfl::string_to_enum("u_delta"); + ASSERT_TRUE(parsed_uu.has_value()) << parsed_uu.error().what(); + EXPECT_EQ(*parsed_uu, u_delta); + + write_and_read(WideEnums{.s = Signed64NoZero::beta, + .u = Unsigned64NoZero::gamma, + .us = u_beta, + .uu = u_gamma}); +} + } // namespace test_enum diff --git a/tests/generic/test_expected.cpp b/tests/generic/test_expected.cpp index 15d4814e2..b363d7c78 100644 --- a/tests/generic/test_expected.cpp +++ b/tests/generic/test_expected.cpp @@ -2,10 +2,12 @@ #include #include +#include #include "write_and_read.hpp" -#if __has_include() +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L && \ + __has_include() #include #endif diff --git a/tests/generic/test_string_to_enum.cpp b/tests/generic/test_string_to_enum.cpp new file mode 100644 index 000000000..edec1543f --- /dev/null +++ b/tests/generic/test_string_to_enum.cpp @@ -0,0 +1,243 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_string_to_enum { + +using namespace std::string_view_literals; + +enum class Color { red = 1, green = 2, blue = 3 }; + +enum Location { left = 0, center = 1, right = 2 }; + +enum class SignedEnum : int { neg = -5, zero = 0, pos = 5 }; + +enum class Signed64Enum : int64_t { neg = -1, zero = 0, pos = 1 }; + +enum class Unsigned32Enum : uint32_t { a = 1, b = 2 }; + +enum class NarrowEnum : uint8_t { low = 1, high = 2 }; + +enum class BoolEnum : bool { no = false, yes = true }; + +enum class Perm { read = 1, write = 2, exec = 4 }; + +inline Perm operator|(Perm a, Perm b) noexcept { + return static_cast(static_cast(a) | static_cast(b)); +} + +enum class Flags64 : uint64_t { + none = 0, + flag_a = 1ULL << 0, + flag_b = 1ULL << 1 +}; + +inline Flags64 operator|(Flags64 a, Flags64 b) noexcept { + return static_cast(static_cast(a) | + static_cast(b)); +} + +TEST(generic, test_string_to_enum_string_view_literals) { + const auto red = rfl::string_to_enum("red"sv); + ASSERT_TRUE(red.has_value()); + EXPECT_EQ(*red, Color::red); + + const auto green = rfl::string_to_enum("green"sv); + ASSERT_TRUE(green.has_value()); + EXPECT_EQ(*green, Color::green); + + const auto loc = rfl::string_to_enum("center"sv); + ASSERT_TRUE(loc.has_value()); + EXPECT_EQ(*loc, Location::center); + + const auto invalid = rfl::string_to_enum("purple"sv); + EXPECT_FALSE(invalid.has_value()); + EXPECT_EQ(invalid.error().what(), + "Invalid enum value: 'purple'. Must be one of [red, green, blue]."); + + const auto empty = rfl::string_to_enum(""sv); + EXPECT_FALSE(empty.has_value()); + EXPECT_EQ(empty.error().what(), + "Invalid enum value: ''. Must be one of [red, green, blue]."); + + const auto default_sv = rfl::string_to_enum(std::string_view{}); + EXPECT_FALSE(default_sv.has_value()); + EXPECT_EQ(default_sv.error().what(), + "Invalid enum value: ''. Must be one of [red, green, blue]."); +} + +TEST(generic, test_string_to_enum_non_null_terminated_substring) { + // Raw character array with no null terminator. + const char name_buf[] = {'g', 'r', 'e', 'e', 'n', 'X'}; + const auto from_buf = + rfl::string_to_enum(std::string_view(name_buf, 5)); + ASSERT_TRUE(from_buf.has_value()); + EXPECT_EQ(*from_buf, Color::green); + + // Substring slice from a larger string_view. + const std::string_view full = "prefix_blue_suffix"; + const auto from_sub = rfl::string_to_enum(full.substr(7, 4)); + ASSERT_TRUE(from_sub.has_value()); + EXPECT_EQ(*from_sub, Color::blue); + + // Numeric substring immediately followed by more digits in memory. + const char num_buf[] = {'4', '2', '9', '9'}; + const auto from_num_sub = + rfl::string_to_enum(std::string_view(num_buf, 2)); + ASSERT_TRUE(from_num_sub.has_value()); + EXPECT_EQ(static_cast(*from_num_sub), 42); + + // Flag enum substring slice. + const std::string_view full_flags = "XXread|writeYY"; + const auto from_flag_sub = + rfl::string_to_enum(full_flags.substr(2, 10)); + ASSERT_TRUE(from_flag_sub.has_value()); + EXPECT_EQ(*from_flag_sub, Perm::read | Perm::write); + + // Invalid substring reports only the sliced characters. + const std::string_view full_invalid = "XXbadYY"; + const auto invalid_sub = rfl::string_to_enum(full_invalid.substr(2, 3)); + EXPECT_FALSE(invalid_sub.has_value()); + EXPECT_EQ(invalid_sub.error().what(), + "Invalid enum value: 'bad'. Must be one of [red, green, blue]."); +} + +TEST(generic, test_string_to_enum_flag_enums) { + const auto single = rfl::string_to_enum("read"sv); + ASSERT_TRUE(single.has_value()); + EXPECT_EQ(*single, Perm::read); + + const auto pair = rfl::string_to_enum("read|write"sv); + ASSERT_TRUE(pair.has_value()); + EXPECT_EQ(*pair, Perm::read | Perm::write); + + const auto all = rfl::string_to_enum("read|write|exec"sv); + ASSERT_TRUE(all.has_value()); + EXPECT_EQ(*all, Perm::read | Perm::write | Perm::exec); + + const auto with_numeric = rfl::string_to_enum("read|8"sv); + ASSERT_TRUE(with_numeric.has_value()); + EXPECT_EQ(static_cast(*with_numeric), 9); + + const auto invalid_flag = rfl::string_to_enum("read|invalid"sv); + EXPECT_FALSE(invalid_flag.has_value()); + EXPECT_EQ(invalid_flag.error().what(), + "Invalid enum value: 'invalid'. Must be one of [read, write, exec]."); + + EXPECT_FALSE(rfl::string_to_enum(""sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum("|"sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum("|read"sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum("read|"sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum("read||write"sv).has_value()); + + // 64-bit flag enum with high bit beyond 32-bit int range. + const auto high_bit = + rfl::string_to_enum("flag_a|1099511627776"sv); + ASSERT_TRUE(high_bit.has_value()); + EXPECT_EQ(static_cast(*high_bit), (1ULL << 0) | (1ULL << 40)); +} + +TEST(generic, test_string_to_enum_numeric_fallback) { + const auto zero = rfl::string_to_enum("0"sv); + ASSERT_TRUE(zero.has_value()); + EXPECT_EQ(*zero, SignedEnum::zero); + + const auto neg = rfl::string_to_enum("-5"sv); + ASSERT_TRUE(neg.has_value()); + EXPECT_EQ(*neg, SignedEnum::neg); + + const auto neg_undeclared = rfl::string_to_enum("-42"sv); + ASSERT_TRUE(neg_undeclared.has_value()); + EXPECT_EQ(static_cast(*neg_undeclared), -42); + + // Full 64-bit signed range. + const auto s64_min_str = + std::to_string(std::numeric_limits::min()); + const auto s64_min = rfl::string_to_enum(s64_min_str); + ASSERT_TRUE(s64_min.has_value()); + EXPECT_EQ(static_cast(*s64_min), + std::numeric_limits::min()); + + // Unsigned 32-bit range beyond INT_MAX, and rejection of negative values. + const auto u32_high = rfl::string_to_enum("3000000000"sv); + ASSERT_TRUE(u32_high.has_value()); + EXPECT_EQ(static_cast(*u32_high), 3000000000U); + EXPECT_FALSE(rfl::string_to_enum("-1"sv).has_value()); + + // Out-of-range values are rejected. + EXPECT_FALSE( + rfl::string_to_enum("99999999999999999999999999"sv).has_value()); + EXPECT_FALSE( + rfl::string_to_enum("99999999999999999999999999"sv) + .has_value()); + + // Trailing garbage, leading whitespace, and leading '+' are rejected. + EXPECT_FALSE(rfl::string_to_enum("1abc"sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum("1 "sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum(" 1"sv).has_value()); + EXPECT_FALSE(rfl::string_to_enum("+1"sv).has_value()); + + // Permissive narrow enum preserves legacy int-cast behavior. + const auto narrow = rfl::string_to_enum("300"sv); + ASSERT_TRUE(narrow.has_value()); + EXPECT_EQ(static_cast(*narrow), 44); + + // Enum with bool underlying type works for both names and numeric fallback. + const auto bool_name = rfl::string_to_enum("yes"sv); + ASSERT_TRUE(bool_name.has_value()); + EXPECT_EQ(*bool_name, BoolEnum::yes); + + const auto bool_num = rfl::string_to_enum("1"sv); + ASSERT_TRUE(bool_num.has_value()); + EXPECT_EQ(*bool_num, BoolEnum::yes); + + EXPECT_FALSE(rfl::string_to_enum("invalid"sv).has_value()); +} + +TEST(generic, test_string_to_enum_names_only) { + const auto valid = rfl::string_to_enum("green"sv); + ASSERT_TRUE(valid.has_value()); + EXPECT_EQ(*valid, Color::green); + + EXPECT_FALSE((rfl::string_to_enum("2"sv).has_value())); + EXPECT_FALSE((rfl::string_to_enum("4"sv).has_value())); + EXPECT_FALSE((rfl::string_to_enum("-1"sv).has_value())); + + const auto valid_flags = rfl::string_to_enum("read|exec"sv); + ASSERT_TRUE(valid_flags.has_value()); + EXPECT_EQ(*valid_flags, Perm::read | Perm::exec); + + EXPECT_FALSE((rfl::string_to_enum("read|8"sv).has_value())); +} + +TEST(generic, test_string_to_enum_caller_types) { + // const char* literal and variable. + const char* cstr = "red"; + ASSERT_TRUE(rfl::string_to_enum("red").has_value()); + EXPECT_EQ(*rfl::string_to_enum("red"), Color::red); + ASSERT_TRUE(rfl::string_to_enum(cstr).has_value()); + EXPECT_EQ(*rfl::string_to_enum(cstr), Color::red); + + // std::string lvalue, const reference, and rvalue. + std::string str = "green"; + const std::string& cref = str; + ASSERT_TRUE(rfl::string_to_enum(str).has_value()); + EXPECT_EQ(*rfl::string_to_enum(str), Color::green); + ASSERT_TRUE(rfl::string_to_enum(cref).has_value()); + EXPECT_EQ(*rfl::string_to_enum(cref), Color::green); + const auto from_rvalue = + rfl::string_to_enum(rfl::enum_to_string(Color::blue)); + ASSERT_TRUE(from_rvalue.has_value()); + EXPECT_EQ(*from_rvalue, Color::blue); + + // std::string_view lvalue. + const std::string_view sv = "blue"; + ASSERT_TRUE(rfl::string_to_enum(sv).has_value()); + EXPECT_EQ(*rfl::string_to_enum(sv), Color::blue); +} + +} // namespace test_string_to_enum diff --git a/tests/generic/test_validator_formatting.cpp b/tests/generic/test_validator_formatting.cpp new file mode 100644 index 000000000..a5941fe30 --- /dev/null +++ b/tests/generic/test_validator_formatting.cpp @@ -0,0 +1,200 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_validator_formatting { + +namespace { + +rfl::Error prefix_error(const rfl::Error& _err) { + return rfl::Error("wrapped: " + _err.what()); +} + +enum class Level : int { low = 1, high = 10 }; + +} // namespace + +TEST(generic, comparisons_error_messages_integers) { + const auto eq = rfl::EqualTo<5>::validate(3); + ASSERT_FALSE(eq); + EXPECT_EQ(eq.error().what(), "Value expected to be equal to 5, but got 3."); + + const auto min = rfl::Minimum<0>::validate(-7); + ASSERT_FALSE(min); + EXPECT_EQ(min.error().what(), + "Value expected to be greater than or equal to 0, but got -7."); + + const auto emin = rfl::ExclusiveMinimum<10>::validate(10); + ASSERT_FALSE(emin); + EXPECT_EQ(emin.error().what(), + "Value expected to be greater than 10, but got 10."); + + const auto max = rfl::Maximum<100>::validate(101); + ASSERT_FALSE(max); + EXPECT_EQ(max.error().what(), + "Value expected to be less than or equal to 100, but got 101."); + + const auto emax = rfl::ExclusiveMaximum<50>::validate(50); + ASSERT_FALSE(emax); + EXPECT_EQ(emax.error().what(), + "Value expected to be less than 50, but got 50."); + + const auto neq = rfl::NotEqualTo<42>::validate(42); + ASSERT_FALSE(neq); + EXPECT_EQ(neq.error().what(), + "Value expected not to be equal to 42, but got 42."); + + const auto u64 = + rfl::Minimum::validate(uint64_t{999}); + ASSERT_FALSE(u64); + EXPECT_EQ( + u64.error().what(), + "Value expected to be greater than or equal to 1000000000000, but got " + "999."); +} + +TEST(generic, comparisons_error_messages_floating_point) { + const auto d1 = rfl::Minimum<1.5>::validate(0.25); + ASSERT_FALSE(d1); + EXPECT_EQ(d1.error().what(), + "Value expected to be greater than or equal to 1.5, but got 0.25."); + + const auto d2 = rfl::Maximum<1.0>::validate(2.0); + ASSERT_FALSE(d2); + EXPECT_EQ(d2.error().what(), + "Value expected to be less than or equal to 1, but got 2."); + + const auto f1 = rfl::ExclusiveMinimum<0.0f>::validate(-3.5f); + ASSERT_FALSE(f1); + EXPECT_EQ(f1.error().what(), + "Value expected to be greater than 0, but got -3.5."); + + const auto ld1 = rfl::Maximum<2.5L>::validate(3.25L); + ASSERT_FALSE(ld1); + EXPECT_EQ(ld1.error().what(), + "Value expected to be less than or equal to 2.5, but got 3.25."); +} + +TEST(generic, comparisons_error_messages_char_bool_enum) { + // Plain char formats as a character (matching prior std::stringstream). + const auto c = rfl::Minimum<'b'>::validate('a'); + ASSERT_FALSE(c); + EXPECT_EQ(c.error().what(), + "Value expected to be greater than or equal to b, but got a."); + + // signed char / unsigned char (and int8_t / uint8_t) intentionally format as + // decimal integers rather than raw characters. + const auto sc = + rfl::Minimum(66)>::validate( + static_cast(65)); + ASSERT_FALSE(sc); + EXPECT_EQ(sc.error().what(), + "Value expected to be greater than or equal to 66, but got 65."); + + const auto uc = + rfl::Maximum(96)>::validate( + static_cast(97)); + ASSERT_FALSE(uc); + EXPECT_EQ(uc.error().what(), + "Value expected to be less than or equal to 96, but got 97."); + + const auto i8 = rfl::Minimum::validate(int8_t{-5}); + ASSERT_FALSE(i8); + EXPECT_EQ(i8.error().what(), + "Value expected to be greater than or equal to 10, but got -5."); + + const auto u8 = rfl::Maximum::validate(uint8_t{200}); + ASSERT_FALSE(u8); + EXPECT_EQ(u8.error().what(), + "Value expected to be less than or equal to 100, but got 200."); + + const auto b = rfl::EqualTo::validate(false); + ASSERT_FALSE(b); + EXPECT_EQ(b.error().what(), "Value expected to be equal to 1, but got 0."); + + const auto e = rfl::Minimum::validate(Level::low); + ASSERT_FALSE(e); + EXPECT_EQ(e.error().what(), + "Value expected to be greater than or equal to 10, but got 1."); +} + +TEST(generic, any_of_and_one_of_error_messages) { + using Any = rfl::AnyOf, rfl::EqualTo<2>>; + const auto any_res = Any::validate(3); + ASSERT_FALSE(any_res); + EXPECT_EQ( + any_res.error().what(), + "Expected at least one of the following validations to pass, but none of " + "them did:\n" + "1) Value expected to be equal to 1, but got 3.\n" + "2) Value expected to be equal to 2, but got 3."); + + using One = rfl::OneOf, rfl::EqualTo<2>>; + const auto one_res = One::validate(3); + ASSERT_FALSE(one_res); + EXPECT_EQ(one_res.error().what(), + "Expected exactly 1 out of 2 validations to pass, but 0 of them " + "did. The following errors were generated: \n" + "1) Value expected to be equal to 1, but got 3.\n" + "2) Value expected to be equal to 2, but got 3."); +} + +TEST(generic, pattern_validator_and_size_error_messages) { + using Digits = rfl::PatternValidator; + const auto pat_res = Digits::validate("abc"); + ASSERT_FALSE(pat_res); + EXPECT_EQ(pat_res.error().what(), + "String 'abc' did not match format 'Digits': '^[0-9]+$'."); + + using NonEmpty = rfl::Size>; + const auto size_res = NonEmpty::validate(std::string{}); + ASSERT_FALSE(size_res); + EXPECT_EQ(size_res.error().what(), + "Size validation failed: Value expected to be greater than or " + "equal to 1, but got 0."); +} + +TEST(generic, validator_and_literal_std_hash) { + using Positive = rfl::Validator>; + const Positive p(42); + EXPECT_EQ(std::hash{}(p), std::hash{}(42)); + + using Color = rfl::Literal<"red", "green", "blue">; + const Color c = Color::make<"green">(); + EXPECT_EQ(std::hash{}(c), + std::hash{}(static_cast(c.value()))); +} + +TEST(generic, result_transform_error) { + const rfl::Result err_lval = rfl::error("boom"); + const auto t1 = err_lval.transform_error(prefix_error); + ASSERT_FALSE(t1); + EXPECT_EQ(t1.error().what(), "wrapped: boom"); + + const auto t2 = rfl::Result(rfl::error("boom")) + .transform_error([](const rfl::Error& _e) { + return rfl::Error("lambda: " + _e.what()); + }); + ASSERT_FALSE(t2); + EXPECT_EQ(t2.error().what(), "lambda: boom"); + + const rfl::Result ok_lval(7); + const auto t3 = ok_lval.transform_error(prefix_error); + ASSERT_TRUE(t3); + EXPECT_EQ(*t3, 7); + + const auto t4 = rfl::Result(9).transform_error(prefix_error); + ASSERT_TRUE(t4); + EXPECT_EQ(*t4, 9); +} + +} // namespace test_validator_formatting diff --git a/tests/json/test_all_of.cpp b/tests/json/test_all_of.cpp index 512ec446c..fd54052e9 100644 --- a/tests/json/test_all_of.cpp +++ b/tests/json/test_all_of.cpp @@ -1,4 +1,6 @@ +#include #include +#include #include // Make sure things still compile when @@ -24,4 +26,67 @@ TEST(json, test_all_of) { write_and_read(homer, R"({"firstName":"Homer","lastName":"Simpson","age":45})"); } + +struct ThrowingStdValidator { + template + static rfl::Result validate(const T& _v) { + if (_v < 0) { + throw std::runtime_error("negative value rejected"); + } + return _v; + } +}; + +struct ThrowingNonStdValidator { + template + static rfl::Result validate(const T& _v) { + if (_v == 999) { + throw 42; + } + return _v; + } +}; + +struct ThrowingKeyValidator { + static rfl::Result validate(const std::string& _s) { + if (_s == "bad_std") { + throw std::runtime_error("bad map key"); + } + if (_s == "bad_nonstd") { + throw 7; + } + return _s; + } +}; + +struct AllOfThrowingStruct { + rfl::Validator value; +}; + +struct MapThrowingKeyStruct { + std::map, int> items; +}; + +TEST(json, test_all_of_and_map_key_noexcept_boundaries) { + // Multi-validator AllOf throwing std::runtime_error must return Error, not terminate. + const auto res_std = rfl::json::read(R"({"value":-1})"); + ASSERT_FALSE(res_std.has_value()); + EXPECT_NE(res_std.error().what().find("negative value rejected"), + std::string::npos); + + // Multi-validator AllOf throwing a non-std::exception must return Error, not terminate. + const auto res_nonstd = + rfl::json::read(R"({"value":999})"); + ASSERT_FALSE(res_nonstd.has_value()); + + // Validated map keys must route through from_value() and catch non-std::exception. + const auto map_std = + rfl::json::read(R"({"items":{"bad_std":1}})"); + ASSERT_FALSE(map_std.has_value()); + EXPECT_NE(map_std.error().what().find("bad map key"), std::string::npos); + + const auto map_nonstd = + rfl::json::read(R"({"items":{"bad_nonstd":1}})"); + ASSERT_FALSE(map_nonstd.has_value()); +} } // namespace test_all_of diff --git a/tests/json/test_default_val_without_default_construction.cpp b/tests/json/test_default_val_without_default_construction.cpp index d56b69030..ced07db4d 100644 --- a/tests/json/test_default_val_without_default_construction.cpp +++ b/tests/json/test_default_val_without_default_construction.cpp @@ -70,7 +70,7 @@ TEST(json, test_default_val_tagged_union_schema) { EXPECT_EQ( (rfl::json::to_schema< rfl::TaggedUnion<"type", DefaultAlternative, OtherAlternative>>()), - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/test_default_val_without_default_construction__DefaultAlternative__tagged"},{"$ref":"#/$defs/test_default_val_without_default_construction__OtherAlternative__tagged"}],"$defs":{"test_default_val_without_default_construction__DefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["DefaultAlternative"]},"output":{"type":"string","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]},"test_default_val_without_default_construction__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]}}})"); + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/test_default_val_without_default_construction__DefaultAlternative__tagged"},{"$ref":"#/$defs/test_default_val_without_default_construction__OtherAlternative__tagged"}],"$defs":{"test_default_val_without_default_construction__DefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["DefaultAlternative"]},"output":{"type":"string","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]},"test_default_val_without_default_construction__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]}}})"); } } // namespace test_default_val_without_default_construction diff --git a/tests/json/test_enum_names.cpp b/tests/json/test_enum_names.cpp new file mode 100644 index 000000000..810b31521 --- /dev/null +++ b/tests/json/test_enum_names.cpp @@ -0,0 +1,471 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_enum_names { + +enum class OptimizationLevel { + no_opt, + size_opt, + speed_opt, + cxx_standard, +}; + +enum class OutputMode { + plain_text, + json_pretty, + xml_compact, +}; + +enum class CustomPrefixEnum { + fast_path, + slow_path, +}; + +enum class MixedCaseEnum { + Fast_Path, + Read, +}; + +enum class StringViewTransformEnum { + first_item, + second_item, +}; + +enum class SpanOverridesEnum { + alpha_val, + beta_val, + gamma_val, +}; + +enum class DupOverrideEnum { + first, + second, +}; + +enum class ThrowingTransformEnum { + ok, +}; + +enum class ThrowingNonStdTransformEnum { + ok, +}; + +enum class DescribedWireEnum { + fast_mode, + safe_mode, +}; + +enum UnscopedWireEnum : uint8_t { + unscoped_one = 1, + unscoped_two = 2, +}; + +enum class WideWireEnum : int64_t { + small_val = 1, + big_val = 1000000, +}; + +enum class WireFlags : uint32_t { + none = 0, + read_access = 1u << 0, + write_access = 1u << 1, + exec_access = 1u << 2, +}; + +inline WireFlags operator|(WireFlags _a, WireFlags _b) { + return static_cast(static_cast(_a) | + static_cast(_b)); +} + +struct CompilerConfig { + OptimizationLevel opt = OptimizationLevel::speed_opt; + OutputMode output = OutputMode::plain_text; + CustomPrefixEnum mode = CustomPrefixEnum::fast_path; +}; + +struct CliEnumConfig { + rfl::DefaultVal opt = OptimizationLevel::speed_opt; + rfl::DefaultVal output = OutputMode::json_pretty; +}; + +enum class HttpStatus { + ok = 200, + not_found = 404, +}; + +struct StatusPayload { + HttpStatus status = HttpStatus::ok; +}; + +struct DescribedPayload { + DescribedWireEnum mode = DescribedWireEnum::fast_mode; +}; + +} // namespace test_enum_names + +namespace rfl { + +// Combine snake_to_kebab transform with an explicit per-enumerator override +// (for identifiers like C++ keywords or non-identifier wire names like "c++20"). +template <> +struct EnumNames { + static constexpr EnumNameTransform transform = + EnumNameTransform::snake_to_kebab; + static constexpr std::array< + EnumOverride, 1> + overrides = {{ + {test_enum_names::OptimizationLevel::cxx_standard, "c++20"}, + }}; +}; + +// Custom transform function returning std::string. +template <> +struct EnumNames { + static std::string transform(const std::string_view _raw) { + return "x-" + apply_enum_name_transform(_raw, EnumNameTransform::snake_to_kebab); + } +}; + +// Custom transform function returning std::string_view. +template <> +struct EnumNames { + static std::string_view transform(const std::string_view _raw) { + return _raw == "first_item" ? std::string_view("one") + : std::string_view("two"); + } +}; + +// Borrowed-range function form of overrides() without transform (non-overridden +// enumerators still inherit processor transforms). +template <> +struct EnumNames { + static std::span> + overrides() { + static constexpr std::array< + EnumOverride, 1> + kOverrides = {{ + {test_enum_names::SpanOverridesEnum::alpha_val, "custom-alpha"}, + }}; + return kOverrides; + } +}; + +// Duplicate override entries for the same enumerator: first entry wins everywhere. +template <> +struct EnumNames { + static constexpr std::array< + EnumOverride, 2> + overrides = {{ + {test_enum_names::DupOverrideEnum::first, "primary"}, + {test_enum_names::DupOverrideEnum::first, "shadowed"}, + }}; +}; + +// Throwing custom transform must return rfl::Error rather than terminating. +template <> +struct EnumNames { + static std::string transform(const std::string_view) { + throw std::runtime_error("transform boom"); + } +}; + +// Non-std::exception throw must also be caught inside the noexcept boundary. +template <> +struct EnumNames { + static std::string transform(const std::string_view) { + throw 42; + } +}; + +// Out-of-range enum overrides (outside default enchantum range). +template <> +struct EnumNames { + static constexpr std::array, 2> + overrides = {{ + {test_enum_names::HttpStatus::ok, "ok"}, + {test_enum_names::HttpStatus::not_found, "not-found"}, + }}; +}; + +template <> +struct EnumNames { + static constexpr std::array, 1> + overrides = {{ + {test_enum_names::WideWireEnum::big_val, "one-million"}, + }}; +}; + +template <> +struct config::enum_descriptions { + static constexpr bool has_descriptions = true; + static std::string_view get(const test_enum_names::DescribedWireEnum _e) { + return _e == test_enum_names::DescribedWireEnum::fast_mode + ? "Fast execution" + : "Safe execution"; + } +}; + +} // namespace rfl + +namespace test_enum_names { + +TEST(json, test_enum_names_trait_overrides_and_transform) { + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::no_opt), "no-opt"); + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::size_opt), "size-opt"); + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::speed_opt), "speed-opt"); + EXPECT_EQ(rfl::enum_to_string(OptimizationLevel::cxx_standard), "c++20"); + + ASSERT_EQ(*rfl::string_to_enum("no-opt"), + OptimizationLevel::no_opt); + ASSERT_EQ(*rfl::string_to_enum("c++20"), + OptimizationLevel::cxx_standard); + // Raw C++ identifier and wrong case should not match. + EXPECT_FALSE(rfl::string_to_enum("no_opt")); + EXPECT_FALSE(rfl::string_to_enum("NO-OPT")); + EXPECT_FALSE(rfl::string_to_enum("cxx_standard")); + + // Custom transform function returning std::string and std::string_view. + EXPECT_EQ(rfl::enum_to_string(CustomPrefixEnum::fast_path), "x-fast-path"); + ASSERT_EQ(*rfl::string_to_enum("x-slow-path"), + CustomPrefixEnum::slow_path); + + EXPECT_EQ(rfl::enum_to_string(StringViewTransformEnum::first_item), "one"); + ASSERT_EQ(*rfl::string_to_enum("two"), + StringViewTransformEnum::second_item); + + // Borrowed-range overrides() function form + processor fallback. + EXPECT_EQ(rfl::enum_to_string(SpanOverridesEnum::alpha_val), "custom-alpha"); + EXPECT_EQ(rfl::enum_to_string(SpanOverridesEnum::beta_val), "beta_val"); + EXPECT_EQ((rfl::enum_to_string( + SpanOverridesEnum::alpha_val)), + "custom-alpha"); + EXPECT_EQ((rfl::enum_to_string( + SpanOverridesEnum::beta_val)), + "beta-val"); + ASSERT_EQ(*(rfl::string_to_enum("beta-val")), + SpanOverridesEnum::beta_val); + + // Duplicate override entries: first wins consistently across read/write/schema. + EXPECT_EQ(rfl::enum_to_string(DupOverrideEnum::first), "primary"); + ASSERT_EQ((*(rfl::string_to_enum("primary"))), + DupOverrideEnum::first); + EXPECT_FALSE((rfl::string_to_enum("shadowed"))); + + // Throwing custom transform returns rfl::Error instead of terminating, both + // through rfl::json::read and direct rfl::string_to_enum. + const auto thrown = + rfl::json::read(R"("ok")"); + EXPECT_FALSE(thrown); + EXPECT_NE(thrown.error().what().find("transform boom"), std::string::npos); + + const auto thrown_direct = rfl::string_to_enum("ok"); + EXPECT_FALSE(thrown_direct); + EXPECT_NE(thrown_direct.error().what().find("transform boom"), + std::string::npos); + + const auto thrown_non_std = + rfl::json::read(R"("ok")"); + EXPECT_FALSE(thrown_non_std); + EXPECT_FALSE(thrown_non_std.error().what().empty()); + + const auto thrown_non_std_direct = + rfl::string_to_enum("ok"); + EXPECT_FALSE(thrown_non_std_direct); + EXPECT_FALSE(thrown_non_std_direct.error().what().empty()); +} + +TEST(json, test_enum_names_processor_transforms_and_nested_processors) { + static_assert(rfl::internal::enum_name_transform_v< + rfl::EnumSnakeCaseToKebabCase> == + rfl::EnumNameTransform::snake_to_kebab); + static_assert( + rfl::internal::enum_name_transform_v< + rfl::Processors>> == + rfl::EnumNameTransform::snake_to_kebab); + + // Direct calls with bare processor, variadic multi-processor packs, and + // nested Processors<...>. + EXPECT_EQ((rfl::enum_to_string( + OutputMode::json_pretty)), + "json-pretty"); + const auto direct_wire = + rfl::get_enum_wire_names(); + ASSERT_EQ(direct_wire.size(), 3u); + EXPECT_EQ(direct_wire[1].first, "json-pretty"); + + const auto variadic_wire = + rfl::get_enum_wire_names(); + ASSERT_EQ(variadic_wire.size(), 3u); + EXPECT_EQ(variadic_wire[1].first, "json-pretty"); + + // OutputMode has no EnumNames specialization; processor applies. + const CompilerConfig cfg{ + .opt = OptimizationLevel::cxx_standard, + .output = OutputMode::json_pretty, + .mode = CustomPrefixEnum::slow_path, + }; + + const auto kebab_json = rfl::json::write(cfg); + EXPECT_EQ( + kebab_json, + R"({"opt":"c++20","output":"json-pretty","mode":"x-slow-path"})"); + + const auto parsed = + rfl::json::read(kebab_json); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->opt, OptimizationLevel::cxx_standard); + EXPECT_EQ(parsed->output, OutputMode::json_pretty); + EXPECT_EQ(parsed->mode, CustomPrefixEnum::slow_path); + + // CamelCase lowercases the leading character too. + EXPECT_EQ((rfl::enum_to_string( + MixedCaseEnum::Fast_Path)), + "fastPath"); + EXPECT_EQ((rfl::enum_to_string( + MixedCaseEnum::Read)), + "read"); + EXPECT_EQ((rfl::enum_to_string( + MixedCaseEnum::Fast_Path)), + "fast_path"); + + const auto camel_json = rfl::json::write(cfg); + EXPECT_NE(camel_json.find(R"("output":"jsonPretty")"), std::string::npos) + << camel_json; + + const auto pascal_json = rfl::json::write(cfg); + EXPECT_NE(pascal_json.find(R"("output":"JsonPretty")"), std::string::npos) + << pascal_json; + + const auto upper_json = rfl::json::write(cfg); + EXPECT_NE(upper_json.find(R"("output":"JSON_PRETTY")"), std::string::npos) + << upper_json; + + // EnumNamesOnly rejects numeric strings, while UnderlyingEnums uses integers. + EXPECT_FALSE( + (rfl::json::read(R"("1")"))); + EXPECT_EQ( + (rfl::json::write( + OutputMode::json_pretty)), + "1"); +} + +TEST(json, test_enum_names_json_schema_and_default_val) { + const auto schema = + rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("enum":["no-opt","size-opt","speed-opt","c++20"])"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("enum":["plain-text","json-pretty","xml-compact"])"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("enum":["x-fast-path","x-slow-path"])"), + std::string::npos) + << schema; + + // DefaultVal must emit the transformed wire name matching its enum schema. + const auto default_schema = + rfl::json::to_schema(); + EXPECT_NE(default_schema.find( + R"("enum":["plain-text","json-pretty","xml-compact"])"), + std::string::npos) + << default_schema; + EXPECT_NE(default_schema.find(R"("default":"json-pretty")"), + std::string::npos) + << default_schema; + EXPECT_NE(default_schema.find(R"("default":"speed-opt")"), + std::string::npos) + << default_schema; + + // DescribedLiteral respects enum wire transforms too. + const auto desc_schema = + rfl::json::to_schema(); + EXPECT_NE(desc_schema.find(R"("fast-mode")"), std::string::npos) + << desc_schema; + EXPECT_NE(desc_schema.find(R"("Fast execution")"), std::string::npos) + << desc_schema; +} + +TEST(json, test_enum_names_flags_unscoped_and_wide_underlying) { + // Flag enum with TransformEnumNames: zero flag and combined flags. + EXPECT_EQ((rfl::enum_to_string( + WireFlags::none)), + "none"); + const auto combined = WireFlags::read_access | WireFlags::exec_access; + EXPECT_EQ((rfl::enum_to_string( + combined)), + "read-access|exec-access"); + const auto parsed_flags = + rfl::string_to_enum( + "read-access|write-access"); + ASSERT_TRUE(parsed_flags) << parsed_flags.error().what(); + EXPECT_EQ(*parsed_flags, WireFlags::read_access | WireFlags::write_access); + + // Unscoped uint8_t enum. + EXPECT_EQ((rfl::enum_to_string( + unscoped_two)), + "unscoped-two"); + ASSERT_EQ(*(rfl::string_to_enum( + "unscoped-one")), + unscoped_one); + + // Non-int int64_t enum with out-of-range override + processor transform. + EXPECT_EQ((rfl::enum_to_string( + WideWireEnum::small_val)), + "small-val"); + EXPECT_EQ((rfl::enum_to_string( + WideWireEnum::big_val)), + "one-million"); + ASSERT_EQ(*(rfl::string_to_enum( + "one-million")), + WideWireEnum::big_val); +} + +TEST(json, test_enum_names_cli_read) { + const std::vector args = { + "--opt=c++20", "--output=xml-compact"}; + const auto parsed = + rfl::cli::read(args); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->opt.value(), OptimizationLevel::cxx_standard); + EXPECT_EQ(parsed->output.value(), OutputMode::xml_compact); +} + +TEST(json, test_enum_names_out_of_range_overrides_in_schema_and_errors) { + const auto names = rfl::get_enum_wire_names(); + ASSERT_EQ(names.size(), 2u); + EXPECT_EQ(names[0].first, "ok"); + EXPECT_EQ(names[1].first, "not-found"); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("enum":["ok","not-found"])"), std::string::npos) + << schema; + + const auto parsed = rfl::json::read(R"({"status":"not-found"})"); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed->status, HttpStatus::not_found); + + const auto bad = rfl::string_to_enum("bogus"); + ASSERT_FALSE(bad); + EXPECT_NE(bad.error().what().find("ok, not-found"), std::string::npos) + << bad.error().what(); +} + +} // namespace test_enum_names diff --git a/tests/json/test_error_details.cpp b/tests/json/test_error_details.cpp index ac5c16809..17f323210 100644 --- a/tests/json/test_error_details.cpp +++ b/tests/json/test_error_details.cpp @@ -173,4 +173,32 @@ TEST(json, test_error_details_of_tagged_unions_and_variants) { << details[2].message; } +TEST(json, test_error_details_of_field_variant_and_discriminator_failures) { + using ShapeVariant = + rfl::Variant, rfl::Field<"square", Square>>; + + // FieldVariantReader must preserve nested field path segments. + const auto fv_res = + rfl::json::read(R"({"circle":{"radius":-5}})"); + ASSERT_FALSE(fv_res); + ASSERT_EQ(fv_res.error().details().size(), 1u); + EXPECT_EQ(fv_res.error().details()[0].path, (Path{"circle", "radius"})); + + // ParserTaggedUnion unknown discriminator must report discriminator path. + const auto tu_unknown = + rfl::json::read>( + R"({"shape":"Triangle","radius":1})"); + ASSERT_FALSE(tu_unknown); + ASSERT_EQ(tu_unknown.error().details().size(), 1u); + EXPECT_EQ(tu_unknown.error().details()[0].path, (Path{"shape"})); + + // ParserTaggedUnion missing discriminator must report discriminator path. + const auto tu_missing = + rfl::json::read>( + R"({"radius":1})"); + ASSERT_FALSE(tu_missing); + ASSERT_EQ(tu_missing.error().details().size(), 1u); + EXPECT_EQ(tu_missing.error().details()[0].path, (Path{"shape"})); +} + } // namespace test_error_details diff --git a/tests/json/test_expected.cpp b/tests/json/test_expected.cpp index 7d9bc39ff..c0d007f3a 100644 --- a/tests/json/test_expected.cpp +++ b/tests/json/test_expected.cpp @@ -2,10 +2,12 @@ #include #include #include +#include #include "write_and_read.hpp" -#if __has_include() +#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L && \ + __has_include() #include #endif diff --git a/tests/json/test_extra_fields_key_collision.cpp b/tests/json/test_extra_fields_key_collision.cpp new file mode 100644 index 000000000..945b0a144 --- /dev/null +++ b/tests/json/test_extra_fields_key_collision.cpp @@ -0,0 +1,81 @@ +#include + +#include +#include +#include + +namespace test_extra_fields_key_collision { + +struct GenericExtraFields { + int a = 0; + rfl::ExtraFields extra_fields; +}; + +struct GenericExtraFieldsWithDefault { + rfl::DefaultVal a = 7; + rfl::ExtraFields extra_fields; +}; + +struct WideWithExtra { + int f0 = 0; + int f1 = 1; + int f2 = 2; + int f3 = 3; + int f4 = 4; + int f5 = 5; + int f6 = 6; + int f7 = 7; + int f8 = 8; + int f9 = 9; + rfl::ExtraFields extra; +}; + +TEST(json, test_extra_fields_literal_key_collision) { + // ViewReader (no defaults): an input key literally matching the C++ member + // name of the ExtraFields slot must be captured into ExtraFields. + const auto parsed = rfl::json::read( + R"({"a":42,"extra_fields":"literal_value","other":9})") + .value(); + EXPECT_EQ(parsed.a, 42); + EXPECT_EQ(parsed.extra_fields.at("extra_fields").to_string().value(), + "literal_value"); + EXPECT_EQ(parsed.extra_fields.at("other").to_int().value(), 9); + + // ViewReaderWithDefault via DefaultVal. + const auto parsed_def = + rfl::json::read( + R"({"extra_fields":"from_default_reader","k":true})") + .value(); + EXPECT_EQ(parsed_def.a.value(), 7); + EXPECT_EQ(parsed_def.extra_fields.at("extra_fields").to_string().value(), + "from_default_reader"); + EXPECT_EQ(parsed_def.extra_fields.at("k").to_bool().value(), true); + + // ViewReaderWithDefault via DefaultIfMissing. + const auto parsed_dim = + rfl::json::read( + R"({"extra_fields":123})") + .value(); + EXPECT_EQ(parsed_dim.a, 0); + EXPECT_EQ(parsed_dim.extra_fields.at("extra_fields").to_int().value(), 123); + + // Wide struct (> 4 fields): literal key "extra" captured into ExtraFields. + const auto parsed_wide = + rfl::json::read( + R"({"f0":0,"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"extra":42,"other":99})") + .value(); + EXPECT_EQ(parsed_wide.f0, 0); + EXPECT_EQ(parsed_wide.f9, 9); + EXPECT_EQ(parsed_wide.extra.at("extra"), 42); + EXPECT_EQ(parsed_wide.extra.at("other"), 99); + + const auto parsed_wide_dim = + rfl::json::read( + R"({"f3":33,"extra":77,"other":88})") + .value(); + EXPECT_EQ(parsed_wide_dim.f3, 33); + EXPECT_EQ(parsed_wide_dim.extra.at("extra"), 77); + EXPECT_EQ(parsed_wide_dim.extra.at("other"), 88); +} + +} // namespace test_extra_fields_key_collision diff --git a/tests/json/test_field_name_lookup.cpp b/tests/json/test_field_name_lookup.cpp new file mode 100644 index 000000000..0bb110491 --- /dev/null +++ b/tests/json/test_field_name_lookup.cpp @@ -0,0 +1,154 @@ +#include + +#include +#include +#include +#include + +namespace test_field_name_lookup { + +struct SmallWithExtra { + int a = 1; + rfl::ExtraFields extra; +}; + +struct SmallStrict { + int a = 1; + int b = 2; +}; + +struct MediumStrict { + int f0 = 0; + int f1 = 1; + int f2 = 2; + int f3 = 3; + int f4 = 4; + int f5 = 5; +}; + +struct WideWithExtra { + int f0 = 0; + int f1 = 1; + int f2 = 2; + int f3 = 3; + int f4 = 4; + int f5 = 5; + int f6 = 6; + int f7 = 7; + int f8 = 8; + int f9 = 9; + rfl::ExtraFields extra; +}; + +struct WideStrict { + int f0 = 0; + int f1 = 1; + int f2 = 2; + int f3 = 3; + int f4 = 4; + int f5 = 5; + int f6 = 6; + int f7 = 7; + int f8 = 8; + int f9 = 9; +}; + +struct VariedKeyLengths { + int a = 0; + int ab = 0; + int abc = 0; + int abcd = 0; + int abcdefg = 0; + int abcdefgh = 0; + int abcdefghi = 0; + int abcdefghijklmnop = 0; + int abcdefghijklmnopqrstuvwxyz = 0; +}; + +TEST(json, test_view_reader_duplicate_keys_small_and_wide) { + // Small struct (<= 4 fields, inline linear fold path) + const auto dup_strict_small = + rfl::json::read( + R"({"a":10,"b":20,"a":30})"); + EXPECT_FALSE(dup_strict_small.has_value()); + + const auto dup_def_small = + rfl::json::read( + R"({"a":10,"a":30})"); + EXPECT_FALSE(dup_def_small.has_value()); + + const auto dup_extra_small = + rfl::json::read(R"({"a":10,"a":30})").value(); + EXPECT_EQ(dup_extra_small.a, 10); + EXPECT_EQ(dup_extra_small.extra.at("a"), 30); + + // Medium struct (5..8 fields, FieldNameLookup linear scan path) + const auto ooo_medium = + rfl::json::read( + R"({"f5":50,"f0":1,"f2":20,"f1":10,"f4":40,"f3":30})") + .value(); + EXPECT_EQ(ooo_medium.f0, 1); + EXPECT_EQ(ooo_medium.f3, 30); + EXPECT_EQ(ooo_medium.f5, 50); + + // Wide struct (> 8 fields, FieldNameLookup sorted binary-search path) + const auto dup_strict_wide = rfl::json::read( + R"({"f0":0,"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f5":55})"); + EXPECT_FALSE(dup_strict_wide.has_value()); + + const auto dup_def_wide = + rfl::json::read( + R"({"f5":5,"f5":55})"); + EXPECT_FALSE(dup_def_wide.has_value()); + + const auto dup_extra_wide = + rfl::json::read( + R"({"f5":5,"f5":55,"z":99})") + .value(); + EXPECT_EQ(dup_extra_wide.f5, 5); + EXPECT_EQ(dup_extra_wide.extra.at("f5"), 55); + EXPECT_EQ(dup_extra_wide.extra.at("z"), 99); + + // Out-of-order and interleaved unknown keys exercising cursor hint fallback. + const auto ooo_wide = + rfl::json::read( + R"({"f9":90,"f0":1,"unknown":123,"f1":10,"f2":20,"f8":80,"f3":30,"f4":40,"f5":50,"f6":60,"f7":70})") + .value(); + EXPECT_EQ(ooo_wide.f0, 1); + EXPECT_EQ(ooo_wide.f1, 10); + EXPECT_EQ(ooo_wide.f5, 50); + EXPECT_EQ(ooo_wide.f9, 90); +} + +TEST(json, test_field_name_lookup_varied_key_lengths) { + const auto in_order = + rfl::json::read( + R"({"a":1,"ab":2,"abc":3,"abcd":4,"abcdefg":7,"abcdefgh":8,"abcdefghi":9,"abcdefghijklmnop":16,"abcdefghijklmnopqrstuvwxyz":26})") + .value(); + EXPECT_EQ(in_order.a, 1); + EXPECT_EQ(in_order.ab, 2); + EXPECT_EQ(in_order.abc, 3); + EXPECT_EQ(in_order.abcd, 4); + EXPECT_EQ(in_order.abcdefg, 7); + EXPECT_EQ(in_order.abcdefgh, 8); + EXPECT_EQ(in_order.abcdefghi, 9); + EXPECT_EQ(in_order.abcdefghijklmnop, 16); + EXPECT_EQ(in_order.abcdefghijklmnopqrstuvwxyz, 26); + + const auto reversed = + rfl::json::read( + R"({"abcdefghijklmnopqrstuvwxyz":126,"abcdefghijklmnop":116,"abcdefghi":109,"abcdefgh":108,"abcdefg":107,"abcd":104,"abc":103,"ab":102,"a":101})") + .value(); + EXPECT_EQ(reversed.a, 101); + EXPECT_EQ(reversed.abcdefgh, 108); + EXPECT_EQ(reversed.abcdefghijklmnopqrstuvwxyz, 126); + + // Empty Literal<> specialization compiles cleanly without warnings. + std::size_t hint = 0; + EXPECT_EQ(rfl::parsing::FieldNameLookup>::find("a"), -1); + EXPECT_EQ( + rfl::parsing::FieldNameLookup>::find_with_hint("a", hint), + -1); +} + +} // namespace test_field_name_lookup diff --git a/tests/json/test_has_default_val.cpp b/tests/json/test_has_default_val.cpp new file mode 100644 index 000000000..91482388a --- /dev/null +++ b/tests/json/test_has_default_val.cpp @@ -0,0 +1,290 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct AnonPlain { + int a; + double b; +}; +struct AnonDefault { + int a; + rfl::DefaultVal b = 1; +}; +} // namespace + +namespace test_has_default_val { + +struct Incomplete; + +struct Empty {}; + +struct Plain { + int a; + std::string b; +}; + +struct DirectDefault { + int a; + rfl::DefaultVal b = 7; +}; + +struct RenamedDefault { + rfl::Rename<"val", rfl::DefaultVal> b = 9; +}; + +struct FieldWrapperDefault { + rfl::Field<"a", int> a; + rfl::Field<"b", rfl::DefaultVal> b; +}; + +struct FieldWrapperRenamedDefault { + rfl::Field<"a", rfl::Rename<"val", rfl::DefaultVal>> a; +}; + +struct FieldWrapperNoDefault { + rfl::Field<"a", int> a; + rfl::Field<"b", std::string> b; +}; + +struct RawPointerToDefault { + rfl::DefaultVal* p = nullptr; +}; + +struct FieldWrappingRawPtrToDefault { + rfl::Field<"p", rfl::DefaultVal*> p; +}; + +struct RawPointerToField { + rfl::Field<"a", rfl::DefaultVal>* p = nullptr; +}; + +struct RawPointerToFlatten { + rfl::Flatten* p = nullptr; +}; + +struct RawPointerToIncompleteFlatten { + rfl::Flatten* p = nullptr; +}; + +struct RawPointerToIncompleteField { + rfl::Field<"a", Incomplete>* p = nullptr; +}; + +struct FieldWrappingFlatten { + rfl::Field<"a", rfl::Flatten> f; +}; + +struct NestedFieldWrapper { + rfl::Field<"a", rfl::Field<"b", rfl::DefaultVal>> f; +}; + +struct NonFlattenedNested { + DirectDefault inner; +}; + +struct FlattenedWithDefault { + int x; + rfl::Flatten inner; +}; + +struct DeepFlattenedWithDefault { + rfl::Flatten outer; +}; + +struct FlattenedPtrWithDefault { + rfl::Flatten inner; +}; + +struct FlattenedNoDefault { + rfl::Flatten inner; +}; + +struct FlattenedNamedTupleWithDefault { + rfl::Flatten>>> nt; +}; + +struct WithExtraFields { + int a; + rfl::ExtraFields extra; +}; + +struct WithExtraFieldsAndDefault { + rfl::DefaultVal a = 1; + rfl::ExtraFields extra; +}; + +struct NonDefaultConstructible { + int x; + explicit NonDefaultConstructible(int _x) : x(_x) {} +}; + +struct WithNonDefaultConstructible { + NonDefaultConstructible ndc; + std::unique_ptr ptr; +}; + +struct WithConst { + const int c; + std::array arr; + rfl::DefaultVal d = 5; +}; + +struct BaseWithDefault { + rfl::DefaultVal b = 42; +}; + +struct DerivedEmpty : BaseWithDefault {}; + +class NonAggregate { + int x_ = 0; + + public: + int x() const { return x_; } +}; + +union SimpleUnion { + int a; + double b; +}; + +struct RvalueOnlyVisitor { + int& operator()(int& _a, std::string&) && { return _a; } +}; + +TEST(json, test_has_default_val_trait_and_apply_to_fields) { + using rfl::internal::apply_to_fields; + using rfl::internal::has_default_val_v; + + struct LocalPlain { + int a; + }; + struct LocalDefault { + rfl::DefaultVal a = 3; + }; + + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v); + static_assert(!has_default_val_v>>); + static_assert(!has_default_val_v>); + static_assert(!has_default_val_v); + + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v); + static_assert(has_default_val_v>); + static_assert(has_default_val_v); + static_assert(has_default_val_v< + rfl::NamedTuple>>>); + static_assert(!has_default_val_v>>); + + // TaggedUnion wrappers (both pointer and value forms). + static_assert(has_default_val_v, "d", true>>); + static_assert(has_default_val_v, "d", false>>); + static_assert(!has_default_val_v, "p", true>>); + static_assert(has_default_val_v, "d", true>>); + static_assert(has_default_val_v, "d", false>>); + static_assert(!has_default_val_v, "p", true>>); + static_assert(!has_default_val_v, "p", false>>); + + // Verify apply_to_fields directly on empty, mutable, const, reference return, + // and rvalue-only callable cases. + Empty empty{}; + const auto empty_count = + apply_to_fields(empty, [](auto&... _fs) { return sizeof...(_fs); }); + EXPECT_EQ(empty_count, 0U); + + Plain plain{1, "hi"}; + apply_to_fields(plain, [](int& _a, std::string& _b) { + _a = 10; + _b = "bye"; + }); + EXPECT_EQ(plain.a, 10); + EXPECT_EQ(plain.b, "bye"); + + int& a_ref = apply_to_fields(plain, RvalueOnlyVisitor{}); + a_ref = 25; + EXPECT_EQ(plain.a, 25); + + const Plain& cplain = plain; + const auto sum_len = + apply_to_fields(cplain, [](const int& _a, const std::string& _b) { + return _a + static_cast(_b.size()); + }); + EXPECT_EQ(sum_len, 28); + + // End-to-end JSON read using FlattenedWithDefault (exercises DefaultVal + // path). + const auto parsed = + rfl::json::read(R"({"x":3,"a":4})").value(); + EXPECT_EQ(parsed.x, 3); + EXPECT_EQ(parsed.inner.value().a, 4); + EXPECT_EQ(parsed.inner.value().b.value(), 7); +} + +} // namespace test_has_default_val + +namespace rfl::internal { +struct InternalAdlRegressionStruct { + int x = 1; + std::string y = "ok"; +}; +} // namespace rfl::internal + +namespace test_has_default_val { + +TEST(json, test_apply_to_fields_internal_namespace_adl) { + rfl::internal::InternalAdlRegressionStruct s{42, "adl"}; + EXPECT_EQ(rfl::json::write(s), R"({"x":42,"y":"adl"})"); + const auto rt = + rfl::json::read( + R"({"x":7,"y":"ok"})") + .value(); + EXPECT_EQ(rt.x, 7); + EXPECT_EQ(rt.y, "ok"); +} + +} // namespace test_has_default_val diff --git a/tests/json/test_integer_bounds_schema.cpp b/tests/json/test_integer_bounds_schema.cpp new file mode 100644 index 000000000..15bc617f9 --- /dev/null +++ b/tests/json/test_integer_bounds_schema.cpp @@ -0,0 +1,125 @@ +#include + +#include +#include +#include +#include + +namespace test_integer_bounds_schema { + +struct BoundedIntegers { + int8_t i8; + uint8_t u8; + int16_t i16; + uint16_t u16; + int32_t i32; + uint32_t u32; + int64_t i64; + uint64_t u64; + rfl::Validator> port; +}; + +struct CharacterFields { + char c; + char16_t c16; + char32_t c32; + int8_t s8; + uint8_t u8; +}; + +TEST(json, test_schema_integer_bounds_processor) { + // Without IntegerBounds, plain integers have no minimum/maximum. + const auto plain = rfl::json::to_schema(); + EXPECT_NE(plain.find(R"("u8":{"type":"integer"})"), std::string::npos) + << plain; + + const auto bounded = + rfl::json::to_schema(); + EXPECT_NE( + bounded.find(R"("i8":{"type":"integer","minimum":-128,"maximum":127})"), + std::string::npos) + << bounded; + EXPECT_NE(bounded.find(R"("u8":{"type":"integer","minimum":0,"maximum":255})"), + std::string::npos) + << bounded; + EXPECT_NE(bounded.find( + R"("i16":{"type":"integer","minimum":-32768,"maximum":32767})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find(R"("u16":{"type":"integer","minimum":0,"maximum":65535})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("i32":{"type":"integer","minimum":-2147483648,"maximum":2147483647})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("u32":{"type":"integer","minimum":0,"maximum":4294967295})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("i64":{"type":"integer","minimum":-9223372036854775808,"maximum":9223372036854775807})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("u64":{"type":"integer","minimum":0,"maximum":18446744073709551615})"), + std::string::npos) + << bounded; + // Validated integer combines width bounds and validator via allOf. + EXPECT_NE( + bounded.find( + R"("port":{"allOf":[{"type":"integer","minimum":0,"maximum":65535},{"minimum":1,"type":"integer"}]})"), + std::string::npos) + << bounded; +} + +TEST(json, test_schema_integer_bounds_excludes_char_types) { + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(!rfl::parsing::is_bounded_integer_v); + static_assert(rfl::parsing::is_bounded_integer_v); + static_assert(rfl::parsing::is_bounded_integer_v); + static_assert(rfl::parsing::is_bounded_integer_v); + static_assert(rfl::parsing::is_bounded_integer_v); + + const auto schema = + rfl::json::to_schema(); + // Character types have platform-dependent signedness (e.g. char on x86_64 vs + // ARM64), so IntegerBounds must not emit minimum/maximum for them. + EXPECT_NE(schema.find(R"("c":{"type":"integer"})"), std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("c16":{"type":"integer"})"), std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("c32":{"type":"integer"})"), std::string::npos) + << schema; + EXPECT_NE( + schema.find(R"("s8":{"type":"integer","minimum":-128,"maximum":127})"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("u8":{"type":"integer","minimum":0,"maximum":255})"), + std::string::npos) + << schema; + + struct AnnotatedPort { + rfl::DefaultVal> port = 8080; + }; + const auto annotated = + rfl::json::to_schema(); + EXPECT_NE(annotated.find(R"("description":"Listen port")"), std::string::npos) + << annotated; + EXPECT_NE(annotated.find(R"("default":8080)"), std::string::npos) + << annotated; + EXPECT_NE(annotated.find(R"("minimum":0,"maximum":65535)"), std::string::npos) + << annotated; +} + +} // namespace test_integer_bounds_schema diff --git a/tests/json/test_integers.cpp b/tests/json/test_integers.cpp index 0a1ea8a28..ea3db3e8d 100644 --- a/tests/json/test_integers.cpp +++ b/tests/json/test_integers.cpp @@ -23,6 +23,47 @@ TEST(json, test_narrow_integer_bounds) { R"({"signed_value":0,"unsigned_value":100200})")); } +TEST(json, test_signed_overflow_from_large_uint64) { + struct Signed64 { + int64_t value; + }; + struct Signed32 { + int32_t value; + }; + struct Signed8 { + int8_t value; + }; + + // INT64_MAX + 1 (9223372036854775808) and UINT64_MAX (18446744073709551615) + // are parsed by yyjson as YYJSON_SUBTYPE_UINT and must not wrap around to + // negative signed integers (e.g. INT64_MIN or -1). + EXPECT_FALSE( + rfl::json::read(R"({"value":9223372036854775808})")); + EXPECT_FALSE( + rfl::json::read(R"({"value":18446744073709551615})")); + EXPECT_FALSE( + rfl::json::read(R"({"value":18446744073709551615})")); + EXPECT_FALSE( + rfl::json::read(R"({"value":18446744073709551615})")); + + // Boundary values must still succeed. + const auto max_i64 = + rfl::json::read(R"({"value":9223372036854775807})"); + ASSERT_TRUE(max_i64.has_value()); + EXPECT_EQ(max_i64->value, INT64_MAX); + + const auto min_i64 = + rfl::json::read(R"({"value":-9223372036854775808})"); + ASSERT_TRUE(min_i64.has_value()); + EXPECT_EQ(min_i64->value, INT64_MIN); + + // rfl::Generic must not wrap UINT64_MAX into int64_t(-1). + const auto generic_val = + rfl::json::read("18446744073709551615"); + ASSERT_TRUE(generic_val.has_value()); + EXPECT_FALSE(generic_val->to_int64().has_value()); +} + TEST(json, test_integers) { struct Integers { diff --git a/tests/json/test_json_flags.cpp b/tests/json/test_json_flags.cpp new file mode 100644 index 000000000..1396f5135 --- /dev/null +++ b/tests/json/test_json_flags.cpp @@ -0,0 +1,137 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_json_flags { + +struct Config { + std::string name; + int port; + std::vector hosts; +}; + +struct FloatingValues { + double pos_inf; + double nan_val; +}; + +struct OptionalFloatingValues { + std::optional pos_inf; + std::optional nan_val; +}; + +TEST(json, test_json_flags_values_disambiguated) { + static_assert(rfl::json::pretty == YYJSON_WRITE_PRETTY); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000700 + static_assert(rfl::json::pretty_two_spaces == YYJSON_WRITE_PRETTY_TWO_SPACES); +#endif + static_assert(rfl::json::escape_unicode == YYJSON_WRITE_ESCAPE_UNICODE); + static_assert(rfl::json::escape_slashes == YYJSON_WRITE_ESCAPE_SLASHES); + static_assert(rfl::json::write_allow_inf_and_nan == + YYJSON_WRITE_ALLOW_INF_AND_NAN); + static_assert(rfl::json::inf_and_nan_as_null == + YYJSON_WRITE_INF_AND_NAN_AS_NULL); + static_assert(rfl::json::write_allow_invalid_unicode == + YYJSON_WRITE_ALLOW_INVALID_UNICODE); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 + static_assert(rfl::json::newline_at_end == YYJSON_WRITE_NEWLINE_AT_END); +#endif + + static_assert(rfl::json::stop_when_done == YYJSON_READ_STOP_WHEN_DONE); + static_assert(rfl::json::allow_trailing_commas == + YYJSON_READ_ALLOW_TRAILING_COMMAS); + static_assert(rfl::json::allow_comments == YYJSON_READ_ALLOW_COMMENTS); + static_assert(rfl::json::read_allow_inf_and_nan == + YYJSON_READ_ALLOW_INF_AND_NAN); + static_assert(rfl::json::read_allow_invalid_unicode == + YYJSON_READ_ALLOW_INVALID_UNICODE); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000B00 + static_assert(rfl::json::allow_bom == YYJSON_READ_ALLOW_BOM); +#endif + static_assert(rfl::json::jsonc == + (YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS)); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 + static_assert(rfl::json::allow_ext_number == YYJSON_READ_ALLOW_EXT_NUMBER); + static_assert(rfl::json::allow_ext_escape == YYJSON_READ_ALLOW_EXT_ESCAPE); + static_assert(rfl::json::allow_ext_whitespace == + YYJSON_READ_ALLOW_EXT_WHITESPACE); + static_assert(rfl::json::allow_single_quoted_str == + YYJSON_READ_ALLOW_SINGLE_QUOTED_STR); + static_assert(rfl::json::allow_unquoted_key == + YYJSON_READ_ALLOW_UNQUOTED_KEY); + static_assert(rfl::json::json5 == YYJSON_READ_JSON5); +#endif + + static_assert(rfl::json::read_allow_inf_and_nan != + rfl::json::write_allow_inf_and_nan); + static_assert(rfl::json::read_allow_invalid_unicode != + rfl::json::write_allow_invalid_unicode); + SUCCEED(); +} + +TEST(json, test_json_flags_jsonc) { + const std::string input = + "{\n // line comment\n \"name\": \"app\",\n" + " /* block comment */ \"port\": 8080,\n \"hosts\": [\"localhost\",],\n}"; + EXPECT_FALSE(rfl::json::read(input).has_value()); + const auto res = rfl::json::read(input, rfl::json::jsonc); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res->name, "app"); + EXPECT_EQ(res->port, 8080); + EXPECT_EQ(res->hosts, (std::vector{"localhost"})); +} + +TEST(json, test_json_flags_pretty_and_newline) { + const auto cfg = Config{.name = "app", .port = 8080, .hosts = {"a"}}; +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000700 + const std::string expected_two = + "{\n \"name\": \"app\",\n \"port\": 8080,\n \"hosts\": [\n \"a\"\n ]\n}"; + EXPECT_EQ(rfl::json::write(cfg, rfl::json::pretty_two_spaces), expected_two); +#if YYJSON_VERSION_HEX >= 0x000900 + EXPECT_EQ(rfl::json::write( + cfg, rfl::json::pretty_two_spaces | rfl::json::newline_at_end), + expected_two + "\n"); +#endif +#endif +} + +TEST(json, test_json_flags_inf_and_nan) { + const FloatingValues vals{std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}; + const auto written = + rfl::json::write(vals, rfl::json::write_allow_inf_and_nan); + EXPECT_EQ(written, R"({"pos_inf":Infinity,"nan_val":NaN})"); + + const auto reparsed = rfl::json::read( + written, rfl::json::read_allow_inf_and_nan); + ASSERT_TRUE(reparsed.has_value()); + EXPECT_TRUE(std::isinf(reparsed->pos_inf) && reparsed->pos_inf > 0); + EXPECT_TRUE(std::isnan(reparsed->nan_val)); + + const auto as_null = rfl::json::write(vals, rfl::json::inf_and_nan_as_null); + EXPECT_EQ(as_null, R"({"pos_inf":null,"nan_val":null})"); + const auto opt = rfl::json::read(as_null); + ASSERT_TRUE(opt.has_value()); + EXPECT_FALSE(opt->pos_inf.has_value()); + EXPECT_FALSE(opt->nan_val.has_value()); +} + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 +TEST(json, test_json_flags_json5) { + const std::string input = "{name: 'app', port: 0x1F90, hosts: ['a',],}"; + EXPECT_FALSE(rfl::json::read(input).has_value()); + const auto res = rfl::json::read(input, rfl::json::json5); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res->name, "app"); + EXPECT_EQ(res->port, 8080); + EXPECT_EQ(res->hosts, (std::vector{"a"})); +} +#endif + +} // namespace test_json_flags diff --git a/tests/json/test_json_schema.cpp b/tests/json/test_json_schema.cpp index 80a029fe5..292914c52 100644 --- a/tests/json/test_json_schema.cpp +++ b/tests/json/test_json_schema.cpp @@ -67,7 +67,7 @@ TEST(json, test_json_schema) { Person>>(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema__Square__tagged"},{"$ref":"#/$defs/test_json_schema__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema__Circle"}},"required":["circle"]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema__WithExtraFields"}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant","generic","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}},{"type":"null"}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"oneOf":[{"$ref":"#/$defs/test_json_schema__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema__Square__tagged"},{"$ref":"#/$defs/test_json_schema__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema__Circle"}},"required":["circle"]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema__WithExtraFields"}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant","generic","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_json_schema2.cpp b/tests/json/test_json_schema2.cpp index 183379d2b..6407be7dc 100644 --- a/tests/json/test_json_schema2.cpp +++ b/tests/json/test_json_schema2.cpp @@ -62,7 +62,7 @@ TEST(json, test_json_schema2) { rfl::json::to_schema(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema2__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"test_json_schema2__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema2__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema2__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema2__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema2__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema2__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema2__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema2__Square__tagged"},{"$ref":"#/$defs/test_json_schema2__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema2__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema2__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema2__Circle"}},"required":["circle"]}]}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant"]},"test_json_schema2__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema2__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"test_json_schema2__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema2__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema2__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"test_json_schema2__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema2__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema2__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema2__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema2__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema2__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"oneOf":[{"$ref":"#/$defs/test_json_schema2__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema2__Square__tagged"},{"$ref":"#/$defs/test_json_schema2__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema2__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema2__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema2__Circle"}},"required":["circle"]}]}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant"]},"test_json_schema2__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema2__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"test_json_schema2__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema2__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_json_schema3.cpp b/tests/json/test_json_schema3.cpp index 8ddc7959f..d7d792eb3 100644 --- a/tests/json/test_json_schema3.cpp +++ b/tests/json/test_json_schema3.cpp @@ -62,7 +62,7 @@ TEST(json, test_json_schema3) { rfl::json::to_schema(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema3__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"test_json_schema3__Circle":{"type":"array","prefixItems":[{"type":"number"}],"items":false},"test_json_schema3__Circle__tagged":{"type":"array","prefixItems":[{"type":"string","enum":["Circle"]},{"type":"number"}],"items":false},"test_json_schema3__Person":{"type":"array","prefixItems":[{"type":"string"},{"type":"string"},{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},{"type":"string"},{"type":"string","enum":["red","green","blue"]},{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},{"type":"number"},{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema3__Person"}},{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema3__Person"}},{"type":"integer"}]},{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema3__Person"}},{"type":"integer"}],"items":false},{"anyOf":[{"$ref":"#/$defs/test_json_schema3__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema3__Square__tagged"},{"$ref":"#/$defs/test_json_schema3__Circle__tagged"}]},{"anyOf":[{"type":"array","prefixItems":[{"$ref":"#/$defs/test_json_schema3__Rectangle"}],"items":false},{"type":"array","prefixItems":[{"$ref":"#/$defs/test_json_schema3__Square"}],"items":false},{"type":"array","prefixItems":[{"$ref":"#/$defs/test_json_schema3__Circle"}],"items":false}]}],"items":false},"test_json_schema3__Rectangle":{"type":"array","prefixItems":[{"type":"number"},{"type":"number"}],"items":false},"test_json_schema3__Rectangle__tagged":{"type":"array","prefixItems":[{"type":"string","enum":["Rectangle"]},{"type":"number"},{"type":"number"}],"items":false},"test_json_schema3__Square":{"type":"array","prefixItems":[{"type":"number"}],"items":false},"test_json_schema3__Square__tagged":{"type":"array","prefixItems":[{"type":"string","enum":["Square"]},{"type":"number"}],"items":false}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema3__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"test_json_schema3__Circle":{"type":"array","prefixItems":[{"type":"number"}],"items":false},"test_json_schema3__Circle__tagged":{"type":"array","prefixItems":[{"type":"string","enum":["Circle"]},{"type":"number"}],"items":false},"test_json_schema3__Person":{"type":"array","prefixItems":[{"type":"string"},{"type":"string"},{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},{"type":"string"},{"type":"string","enum":["red","green","blue"]},{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},{"type":"number"},{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema3__Person"}},{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema3__Person"}},{"type":"integer"}]},{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema3__Person"}},{"type":"integer"}],"items":false},{"oneOf":[{"$ref":"#/$defs/test_json_schema3__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema3__Square__tagged"},{"$ref":"#/$defs/test_json_schema3__Circle__tagged"}]},{"anyOf":[{"type":"array","prefixItems":[{"$ref":"#/$defs/test_json_schema3__Rectangle"}],"items":false},{"type":"array","prefixItems":[{"$ref":"#/$defs/test_json_schema3__Square"}],"items":false},{"type":"array","prefixItems":[{"$ref":"#/$defs/test_json_schema3__Circle"}],"items":false}]}],"items":false},"test_json_schema3__Rectangle":{"type":"array","prefixItems":[{"type":"number"},{"type":"number"}],"items":false},"test_json_schema3__Rectangle__tagged":{"type":"array","prefixItems":[{"type":"string","enum":["Rectangle"]},{"type":"number"},{"type":"number"}],"items":false},"test_json_schema3__Square":{"type":"array","prefixItems":[{"type":"number"}],"items":false},"test_json_schema3__Square__tagged":{"type":"array","prefixItems":[{"type":"string","enum":["Square"]},{"type":"number"}],"items":false}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_json_schema4.cpp b/tests/json/test_json_schema4.cpp index 6ff498eca..ed489ecd9 100644 --- a/tests/json/test_json_schema4.cpp +++ b/tests/json/test_json_schema4.cpp @@ -65,7 +65,7 @@ TEST(json, test_json_schema4) { rfl::json::to_schema(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema4__Person","$defs":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema4__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":[]},"test_json_schema4__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":[]},"test_json_schema4__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema4__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema4__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema4__Square__tagged"},{"$ref":"#/$defs/test_json_schema4__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema4__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema4__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema4__Circle"}},"required":[]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema4__WithExtraFields"}},"required":[]},"test_json_schema4__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":[]},"test_json_schema4__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":[]},"test_json_schema4__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":[],"additionalProperties":{"type":"string"}}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema4__Person","$defs":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}},{"type":"null"}]},"test_json_schema4__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":[]},"test_json_schema4__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":[]},"test_json_schema4__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema4__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"oneOf":[{"$ref":"#/$defs/test_json_schema4__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema4__Square__tagged"},{"$ref":"#/$defs/test_json_schema4__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema4__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema4__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema4__Circle"}},"required":[]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema4__WithExtraFields"}},"required":[]},"test_json_schema4__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":[]},"test_json_schema4__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":[]},"test_json_schema4__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":[],"additionalProperties":{"type":"string"}}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_json_schema_one_of.cpp b/tests/json/test_json_schema_one_of.cpp new file mode 100644 index 000000000..3bd17653a --- /dev/null +++ b/tests/json/test_json_schema_one_of.cpp @@ -0,0 +1,165 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_json_schema_one_of { + +struct Circle { + double radius; +}; + +struct Square { + double width; +}; + +struct Rectangle { + double width; + double height; +}; + +TEST(json, test_json_schema_one_of_tagged_union) { + // The tags make the alternatives mutually exclusive, so oneOf is safe. + const auto json_schema = + rfl::json::to_schema>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/test_json_schema_one_of__Circle__tagged"},{"$ref":"#/$defs/test_json_schema_one_of__Square__tagged"}],"$defs":{"test_json_schema_one_of__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema_one_of__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_tagged_union_with_add_tags_to_variants) { + const auto json_schema = + rfl::json::to_schema, + rfl::AddTagsToVariants>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/test_json_schema_one_of__Circle__tagged"},{"$ref":"#/$defs/test_json_schema_one_of__Square__tagged"}],"$defs":{"test_json_schema_one_of__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema_one_of__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_untagged_variant) { + // 1 is both an integer and a number, so oneOf would reject it. + const auto json_schema = rfl::json::to_schema>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"number"}],"$defs":{}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_overlapping_structs) { + // {"width":1,"height":2} matches both, because additional properties are + // allowed, so oneOf would reject it. + const auto json_schema = + rfl::json::to_schema>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/test_json_schema_one_of__Square"},{"$ref":"#/$defs/test_json_schema_one_of__Rectangle"}],"$defs":{"test_json_schema_one_of__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema_one_of__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_optional) { + const auto json_schema = rfl::json::to_schema>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"null"}],"$defs":{}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_processor_rfl_variant) { + const auto json_schema = rfl::json::to_schema, + rfl::VariantsAsOneOf>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"type":"integer"},{"type":"string"}],"$defs":{}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_processor_std_variant) { + const auto json_schema = rfl::json::to_schema, + rfl::VariantsAsOneOf>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/test_json_schema_one_of__Circle"},{"$ref":"#/$defs/test_json_schema_one_of__Square"}],"$defs":{"test_json_schema_one_of__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema_one_of__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_processor_field_variant) { + using FieldVariant = + rfl::Variant, rfl::Field<"square", Square>>; + + const auto json_schema = + rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema_one_of__Circle"}},"required":["circle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema_one_of__Square"}},"required":["square"]}],"$defs":{"test_json_schema_one_of__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema_one_of__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_processor_leaves_tagged_union) { + const auto json_schema = + rfl::json::to_schema, + rfl::VariantsAsOneOf>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/test_json_schema_one_of__Circle__tagged"},{"$ref":"#/$defs/test_json_schema_one_of__Square__tagged"}],"$defs":{"test_json_schema_one_of__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema_one_of__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_processor_leaves_optional) { + const auto json_schema = + rfl::json::to_schema, rfl::VariantsAsOneOf>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"null"}],"$defs":{}})"; + + EXPECT_EQ(json_schema, expected); +} + +TEST(json, test_json_schema_one_of_processor_leaves_generic) { + // 1 is both an integer and a number, so rfl::Generic must stay anyOf. + const auto json_schema = + rfl::json::to_schema(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/rfl__Generic","$defs":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}},{"type":"null"}]}}})"; + + EXPECT_EQ(json_schema, expected); +} + +struct VariantAndGeneric { + rfl::Variant value; + rfl::Generic extra; +}; + +TEST(json, test_json_schema_one_of_processor_composition) { + const auto composed = + rfl::json::to_schema(); + EXPECT_NE(composed.find(R"("value":{"oneOf":[{"type":"integer"},{"type":"string"}]})"), + std::string::npos) + << composed; + EXPECT_NE(composed.find(R"("rfl__Generic":{"anyOf":[)"), std::string::npos) + << composed; + EXPECT_NE(composed.find(R"("additionalProperties":false)"), std::string::npos) + << composed; + + const auto tagged_var = + rfl::json::to_schema, rfl::AddTagsToVariants, + rfl::VariantsAsOneOf>(); + EXPECT_NE(tagged_var.find(R"("oneOf":[)"), std::string::npos) << tagged_var; +} + +} // namespace test_json_schema_one_of diff --git a/tests/json/test_named_tuple_parser_isolation.cpp b/tests/json/test_named_tuple_parser_isolation.cpp new file mode 100644 index 000000000..f4942db0c --- /dev/null +++ b/tests/json/test_named_tuple_parser_isolation.cpp @@ -0,0 +1,75 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_named_tuple_parser_isolation { + +struct DefaultValEdgeScalars { + rfl::DefaultVal big_u64 = + static_cast(std::numeric_limits::max()) + 42ULL; + rfl::DefaultVal tag_char = 'Z'; + rfl::DefaultVal flag = true; + rfl::DefaultVal ratio = 1.5f; + rfl::DefaultVal label = "hello"; + rfl::DefaultVal> tags = + std::vector{"a", "b"}; + rfl::DefaultVal> opt_set = 9; + rfl::DefaultVal> opt_empty = std::nullopt; + rfl::Rename<"renamedCount", rfl::DefaultVal> renamed_count = 7; +}; + +struct AddStructNameWithDefault { + rfl::DefaultVal count = 7; + std::string name = "ok"; +}; + +TEST(json, test_add_struct_name_with_default_val_schema_and_read) { + const auto asn_schema = rfl::json::to_schema>(); + EXPECT_NE(asn_schema.find("\"type\":{\"type\":\"string\",\"enum\":[" + "\"AddStructNameWithDefault\"]}"), + std::string::npos); + EXPECT_NE(asn_schema.find("\"default\":7"), std::string::npos); + + const auto parsed = + rfl::json::read>( + R"({"type":"AddStructNameWithDefault","name":"hi"})") + .value(); + EXPECT_EQ(parsed.count.get(), 7); + EXPECT_EQ(parsed.name, "hi"); +} + +TEST(json, test_to_default_generic_edge_values) { + const auto schema = rfl::json::to_schema(); + const auto root = + rfl::json::read(schema).value().to_object().value(); + const auto defs = root.get("$defs").value().to_object().value(); + ASSERT_EQ(defs.size(), 1u); + const auto def_obj = defs.begin()->second.to_object().value(); + const auto props = def_obj.get("properties").value().to_object().value(); + const auto default_json = [&](const std::string& _field) { + const auto f = props.get(_field).value().to_object().value(); + return rfl::json::write(f.get("default").value()); + }; + + EXPECT_EQ(default_json("tag_char"), "90"); + EXPECT_EQ(default_json("flag"), "true"); + EXPECT_EQ(default_json("ratio"), "1.5"); + EXPECT_EQ(default_json("label"), "\"hello\""); + EXPECT_EQ(default_json("tags"), "[\"a\",\"b\"]"); + EXPECT_EQ(default_json("opt_set"), "9"); + EXPECT_EQ(default_json("opt_empty"), "null"); + EXPECT_EQ(default_json("renamedCount"), "7"); + // uint64_t > INT64_MAX must match rfl::to_generic fallback: + const auto expected_u64 = rfl::json::write(rfl::to_generic( + static_cast(std::numeric_limits::max()) + 42ULL)); + EXPECT_EQ(default_json("big_u64"), expected_u64); +} + +} // namespace test_named_tuple_parser_isolation diff --git a/tests/json/test_num_fields.cpp b/tests/json/test_num_fields.cpp new file mode 100644 index 000000000..c33d8ab4d --- /dev/null +++ b/tests/json/test_num_fields.cpp @@ -0,0 +1,106 @@ +#include + +#include +#include +#include + +namespace test_num_fields { + +struct Empty {}; + +struct OneChar { + char a; +}; + +struct TwoChars { + char a; + char b; +}; + +struct ThreeFields { + int a; + double b; + std::string c; +}; + +struct FourChars { + char c0, c1, c2, c3; +}; + +struct SevenChars { + char c0, c1, c2, c3, c4, c5, c6; +}; + +struct EightChars { + char c0, c1, c2, c3, c4, c5, c6, c7; +}; + +struct FifteenFields { + int f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14; +}; + +struct SixteenChars { + char c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15; +}; + +struct ThirtyTwoFields { + int f0, f1, f2, f3, f4, f5, f6, f7; + int f8, f9, f10, f11, f12, f13, f14, f15; + int f16, f17, f18, f19, f20, f21, f22, f23; + int f24, f25, f26, f27, f28, f29, f30, f31; +}; + +struct SixtyFourChars { + char c00, c01, c02, c03, c04, c05, c06, c07; + char c08, c09, c10, c11, c12, c13, c14, c15; + char c16, c17, c18, c19, c20, c21, c22, c23; + char c24, c25, c26, c27, c28, c29, c30, c31; + char c32, c33, c34, c35, c36, c37, c38, c39; + char c40, c41, c42, c43, c44, c45, c46, c47; + char c48, c49, c50, c51, c52, c53, c54, c55; + char c56, c57, c58, c59, c60, c61, c62, c63; +}; + +struct NonDefaultConstructible { + int v; + explicit NonDefaultConstructible(int _v) : v(_v) {} +}; + +struct LeadingNonDefault { + NonDefaultConstructible a; + NonDefaultConstructible b; + int c; + std::string d; +}; + +struct AllNonDefault { + NonDefaultConstructible a; + NonDefaultConstructible b; + NonDefaultConstructible c; +}; + +struct WithNestedAndArray { + ThreeFields nested; + std::array arr; + char tail; +}; + +TEST(json, test_num_fields_binary_search) { + static_assert(rfl::num_fields == 0); + static_assert(rfl::num_fields == 1); + static_assert(rfl::num_fields == 2); + static_assert(rfl::num_fields == 3); + static_assert(rfl::num_fields == 4); + static_assert(rfl::num_fields == 7); + static_assert(rfl::num_fields == 8); + static_assert(rfl::num_fields == 15); + static_assert(rfl::num_fields == 16); + static_assert(rfl::num_fields == 32); + static_assert(rfl::num_fields == 64); + static_assert(rfl::num_fields == 4); + static_assert(rfl::num_fields == 3); + static_assert(rfl::num_fields == 3); + SUCCEED(); +} + +} // namespace test_num_fields diff --git a/tests/json/test_one_of.cpp b/tests/json/test_one_of.cpp index 0c104cbbc..ae94cddfd 100644 --- a/tests/json/test_one_of.cpp +++ b/tests/json/test_one_of.cpp @@ -24,4 +24,24 @@ TEST(json, test_one_of) { write_and_read(homer, R"({"firstName":"Homer","lastName":"Simpson","age":45})"); } + +TEST(json, test_one_of_first_branch_and_overlap) { + // First (non-last) branch matches: must succeed. + const auto maggie = + Person{.first_name = "Maggie", .last_name = "Simpson", .age = 5}; + write_and_read(maggie, + R"({"firstName":"Maggie","lastName":"Simpson","age":5})"); + + // Neither branch matches: must fail. + const auto invalid_none = rfl::json::read( + R"({"firstName":"Bart","lastName":"Simpson","age":20})"); + EXPECT_FALSE(invalid_none.has_value()); + + // Multiple branches match simultaneously: must fail. + using Overlapping = + rfl::Validator, rfl::Maximum<10>>>; + EXPECT_FALSE(Overlapping::from_value(5).has_value()); + EXPECT_TRUE(Overlapping::from_value(-5).has_value()); + EXPECT_TRUE(Overlapping::from_value(15).has_value()); +} } // namespace test_one_of diff --git a/tests/json/test_optional_variant_schema.cpp b/tests/json/test_optional_variant_schema.cpp new file mode 100644 index 000000000..312c21da6 --- /dev/null +++ b/tests/json/test_optional_variant_schema.cpp @@ -0,0 +1,51 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_optional_variant_schema { + +struct WithOptionalVariants { + std::optional> std_var; + std::optional> rfl_var; + rfl::Description<"A described optional variant", + std::optional>> + described; + std::optional> nested_opt; +}; + +TEST(json, optional_std_variant_flattens_any_of) { + const auto schema = + rfl::json::to_schema>>(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}],"$defs":{}})"; + EXPECT_EQ(schema, expected); +} + +TEST(json, optional_rfl_variant_flattens_any_of) { + const auto schema = + rfl::json::to_schema>>(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}],"$defs":{}})"; + EXPECT_EQ(schema, expected); +} + +TEST(json, struct_with_optional_variants_and_description) { + const auto schema = rfl::json::to_schema(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_optional_variant_schema__WithOptionalVariants","$defs":{"test_optional_variant_schema__WithOptionalVariants":{"type":"object","properties":{"std_var":{"anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}]},"rfl_var":{"anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}]},"described":{"description":"A described optional variant","anyOf":[{"type":"boolean"},{"type":"number"},{"type":"null"}]},"nested_opt":{"anyOf":[{"type":"integer"},{"type":"null"}]}},"required":[]}}})"; + EXPECT_EQ(schema, expected); +} + +TEST(json, optional_preserves_inner_annotated_variant) { + const auto schema = rfl::json::to_schema< + std::optional>>>(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"description":"inner","anyOf":[{"type":"integer"},{"type":"string"}]},{"type":"null"}],"$defs":{}})"; + EXPECT_EQ(schema, expected); +} + +} // namespace test_optional_variant_schema diff --git a/tests/json/test_raw.cpp b/tests/json/test_raw.cpp new file mode 100644 index 000000000..8028191f4 --- /dev/null +++ b/tests/json/test_raw.cpp @@ -0,0 +1,242 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_raw { + +struct Envelope { + std::string type; + rfl::json::Raw payload; +}; + +struct OptionalEnvelope { + int id; + std::optional payload; +}; + +TEST(json, test_raw_factories_and_accessors) { + const rfl::json::Raw def; + EXPECT_EQ(def.str(), "null"); + EXPECT_EQ(def.value(), "null"); + EXPECT_EQ(def.get(), "null"); + EXPECT_EQ(*def, "null"); + EXPECT_EQ(def(), "null"); + EXPECT_STREQ(def.c_str(), "null"); + + // Unchecked string constructors must remain private; callers go through + // from_string() (validated) or from_trusted_string() (explicit opt-in). + static_assert(!std::is_constructible_v); + static_assert(!std::is_constructible_v); + static_assert(!std::is_constructible_v); + + const auto from_cstr = rfl::json::Raw::from_trusted_string(R"({"a":1})"); + const auto from_sv = + rfl::json::Raw::from_trusted_string(std::string_view{R"({"a":1})"}); + const auto from_str = + rfl::json::Raw::from_trusted_string(std::string{R"({"a":1})"}); + EXPECT_EQ(from_cstr, from_sv); + EXPECT_EQ(from_sv, from_str); + EXPECT_NE(from_cstr, def); + + const auto empty_raw = rfl::json::Raw::from_trusted_string(""); + EXPECT_EQ(empty_raw.str(), "null"); + EXPECT_EQ(empty_raw, def); + EXPECT_EQ(rfl::json::write(empty_raw), "null"); + EXPECT_EQ(rfl::json::write(def), "null"); + EXPECT_EQ(rfl::json::write(std::vector{empty_raw, def}), + "[null,null]"); + EXPECT_EQ(rfl::json::write(Envelope{.type = "empty", .payload = empty_raw}), + R"({"type":"empty","payload":null})"); + + // Validating factory enforces strict RFC 8259 JSON and preserves valid JSON verbatim. + const auto valid = rfl::json::Raw::from_string(R"({ "k" : [1, 2] })"); + ASSERT_TRUE(valid.has_value()); + EXPECT_EQ(valid->str(), R"({ "k" : [1, 2] })"); + for (const std::string_view bad_input : + {std::string_view{""}, std::string_view{"{not json"}, + std::string_view{"1 2"}, std::string_view{"123 garbage"}, + std::string_view{"// comment\n1"}, std::string_view{"/* comment */1"}, + std::string_view{"\xEF\xBB\xBF{}"}, std::string_view{"[1,2,]"}, + std::string_view{"{a:'b'}"}, std::string_view{"NaN"}, + std::string_view{"Infinity"}}) { + EXPECT_FALSE(rfl::json::Raw::from_string(bad_input).has_value()) + << "Expected rejection for: " << bad_input; + } + + // Moved-from Raw::to_generic() degrades gracefully to null Generic. + auto movable = + rfl::json::Raw::from_string( + R"({"long_key_to_avoid_small_string_optimization":1234567890})") + .value(); + auto moved_to = std::move(movable); + EXPECT_EQ(moved_to.get(), + R"({"long_key_to_avoid_small_string_optimization":1234567890})"); + const auto moved_from_generic = movable.to_generic(); + ASSERT_TRUE(moved_from_generic.has_value()); + EXPECT_TRUE(moved_from_generic->is_null()); +} + +TEST(json, test_raw_root_values) { + for (const char* sample : + {R"({"a":1,"b":[true,false,null,"hi"]})", R"([1,2,3])", R"("hello")", + "42", "3.5", "true", "false", "null"}) { + write_and_read(rfl::json::Raw::from_string(sample).value(), sample); + } + const auto bad = + rfl::json::Raw::from_json_obj(rfl::json::Reader::YYJSONInputVar{}); + EXPECT_FALSE(bad.has_value()); + + // Non-standard NaN rejected by yyjson_val_write_opts with descriptive message. + const auto nan_read = + rfl::json::read("NaN", YYJSON_READ_ALLOW_INF_AND_NAN); + EXPECT_FALSE(nan_read.has_value()); + EXPECT_NE(nan_read.error().what().find("Could not serialize JSON value"), + std::string::npos); +} + +TEST(json, test_raw_struct_field) { + const Envelope env{ + .type = "event", + .payload = + rfl::json::Raw::from_string(R"({"nested":{"k":[1,"two",true,null]}})") + .value()}; + write_and_read( + env, + R"({"type":"event","payload":{"nested":{"k":[1,"two",true,null]}}})"); + + const auto null_field = + rfl::json::read(R"({"type":"nil","payload":null})"); + ASSERT_TRUE(null_field.has_value()); + EXPECT_EQ(null_field->payload, rfl::json::Raw::from_string("null").value()); + + const auto missing = rfl::json::read(R"({"type":"missing"})"); + EXPECT_FALSE(missing.has_value()); +} + +TEST(json, test_raw_optional_field) { + const auto missing = rfl::json::read(R"({"id":1})"); + ASSERT_TRUE(missing.has_value()); + EXPECT_FALSE(missing->payload.has_value()); + EXPECT_EQ(rfl::json::write(*missing), R"({"id":1})"); + + const auto explicit_null = + rfl::json::read(R"({"id":2,"payload":null})"); + ASSERT_TRUE(explicit_null.has_value()); + EXPECT_FALSE(explicit_null->payload.has_value()); + + const auto present = + rfl::json::read(R"({"id":3,"payload":{"x":[1,2]}})"); + ASSERT_TRUE(present.has_value()); + ASSERT_TRUE(present->payload.has_value()); + EXPECT_EQ(*present->payload, + rfl::json::Raw::from_string(R"({"x":[1,2]})").value()); + EXPECT_EQ(rfl::json::write(*present), R"({"id":3,"payload":{"x":[1,2]}})"); +} + +TEST(json, test_raw_containers) { + const std::vector vec{ + rfl::json::Raw::from_string("1").value(), + rfl::json::Raw::from_string(R"("two")").value(), + rfl::json::Raw::from_string(R"({"three":3})").value(), + rfl::json::Raw::from_string("[4,5]").value(), + rfl::json::Raw::from_string("true").value(), + rfl::json::Raw::from_string("null").value(), + }; + write_and_read(vec, R"([1,"two",{"three":3},[4,5],true,null])"); + + const std::map mp{ + {"a", rfl::json::Raw::from_string("123").value()}, + {"b", rfl::json::Raw::from_string(R"({"nested":true})").value()}, + {"c", rfl::json::Raw::from_string(R"(["x","y"])").value()}, + }; + write_and_read(mp, R"({"a":123,"b":{"nested":true},"c":["x","y"]})"); +} + +TEST(json, test_raw_passthrough_and_pretty) { + // Non-canonical whitespace and key order must pass through untouched on write. + const std::string unformatted = R"({ "z" : 2, "a" : [ 1, 2 ] })"; + const Envelope env{ + .type = "pass", + .payload = rfl::json::Raw::from_string(unformatted).value()}; + EXPECT_EQ(rfl::json::write(env), + R"({"type":"pass","payload":)" + unformatted + "}"); + EXPECT_EQ( + rfl::json::write(rfl::json::Raw::from_string(unformatted).value()), + unformatted); + + const auto pretty_out = rfl::json::write(env, rfl::json::pretty); + EXPECT_NE(pretty_out.find('\n'), std::string::npos); + EXPECT_NE(pretty_out.find(unformatted), std::string::npos); + + const auto reparsed = rfl::json::read(pretty_out); + ASSERT_TRUE(reparsed.has_value()); + EXPECT_EQ(reparsed->type, "pass"); + EXPECT_EQ(reparsed->payload, + rfl::json::Raw::from_string(R"({"z":2,"a":[1,2]})").value()); +} + +struct DefaultValEnvelope { + int id = 0; + rfl::DefaultVal payload = + rfl::json::Raw::from_trusted_string(R"({"a":1})"); +}; + +TEST(json, test_raw_default_val_and_schema) { + const auto defaulted = rfl::json::read(R"({"id":7})"); + ASSERT_TRUE(defaulted.has_value()); + EXPECT_EQ(defaulted->id, 7); + EXPECT_EQ(defaulted->payload.value(), + rfl::json::Raw::from_string(R"({"a":1})").value()); + + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("default":{"a":1})"), std::string::npos); + EXPECT_NE(schema.find(R"("required":["id"])"), std::string::npos); + + const auto gen = rfl::to_generic(*defaulted); + const auto round_tripped = rfl::from_generic(gen); + ASSERT_TRUE(round_tripped.has_value()); + EXPECT_EQ(round_tripped->payload.value(), + rfl::json::Raw::from_string(R"({"a":1})").value()); +} + +TEST(json, test_raw_to_schema) { + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("rfl__Generic"), std::string::npos); + EXPECT_NE(schema.find(R"("required":["id"])"), std::string::npos); + + const auto req_schema = rfl::json::to_schema(); + EXPECT_NE(req_schema.find("rfl__Generic"), std::string::npos); + EXPECT_NE(req_schema.find(R"("required":["type","payload"])"), + std::string::npos); +} + +TEST(json, test_raw_bignum_and_nested_reparse) { + // With YYJSON_READ_BIGNUM_AS_RAW, integers wider than 64 bits survive verbatim. + const std::string big = "1234567890123456789012345678901234567890"; + const auto big_env = rfl::json::read( + R"({"type":"bignum","payload":{"amount":)" + big + "}}", + YYJSON_READ_BIGNUM_AS_RAW); + ASSERT_TRUE(big_env.has_value()); + EXPECT_EQ(big_env->payload.str(), R"({"amount":)" + big + "}"); + + // Nested Raw inside a Raw payload can be re-parsed into a typed struct. + const auto outer = rfl::json::read( + R"({"type":"outer","payload":{"type":"inner","payload":[1,2,3]}})"); + ASSERT_TRUE(outer.has_value()); + const auto inner = rfl::json::read(outer->payload.str()); + ASSERT_TRUE(inner.has_value()); + EXPECT_EQ(inner->type, "inner"); + EXPECT_EQ(inner->payload.str(), "[1,2,3]"); +} + +} // namespace test_raw diff --git a/tests/json/test_regression_bugs.cpp b/tests/json/test_regression_bugs.cpp index a9c07e1c5..3c22c322f 100644 --- a/tests/json/test_regression_bugs.cpp +++ b/tests/json/test_regression_bugs.cpp @@ -2,8 +2,10 @@ #include #include +#include #include +#include #include // transform_camel_case prepends '_' to names starting with uppercase @@ -83,6 +85,33 @@ TEST(regression, json_writer_handles_non_null_terminated_field_names) { } // namespace test_writer_strcpy_non_null_terminated +// rfl::internal::get_type_name_str_view() previously returned +// get_type_name().string_view(), which dangled into the temporary +// StringLiteral returned by value and failed constant evaluation. +namespace test_get_type_name_str_view { + +struct SampleType { + int value = 0; +}; + +constexpr std::string_view kIntName = rfl::internal::get_type_name_str_view(); +constexpr std::string_view kStructName = + rfl::internal::get_type_name_str_view(); + +static_assert(kIntName == "int"); +static_assert(kIntName == rfl::internal::get_type_name().string_view()); +static_assert(kStructName == + rfl::internal::get_type_name().string_view()); + +TEST(regression, get_type_name_str_view_is_valid_constexpr) { + EXPECT_EQ(kIntName, "int"); + EXPECT_EQ(kStructName, + rfl::internal::get_type_name().string_view()); + EXPECT_NE(kStructName.find("SampleType"), std::string_view::npos); +} + +} // namespace test_get_type_name_str_view + // Parser_string_view / Parser_span memory leak bugs are tested // in tests/alloc/ — a separate executable with custom operator new[]/delete[] // that tracks allocations to detect leaks without ASAN. diff --git a/tests/json/test_string_literal.cpp b/tests/json/test_string_literal.cpp new file mode 100644 index 000000000..78c9f2fa9 --- /dev/null +++ b/tests/json/test_string_literal.cpp @@ -0,0 +1,128 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace test_string_literal { + +static_assert( + std::same_as, rfl::internal::StringLiteral<6>>); +static_assert( + std::same_as, rfl::internal::StringLiteral<1>>); + +template +struct PublicNttpHolder { + static constexpr std::string_view value = _name.string_view(); +}; + +template +struct InternalNttpHolder { + static constexpr std::string_view value = _name.string_view(); +}; + +template +struct ExtractLiteralName; + +template +struct ExtractLiteralName> { + static constexpr std::string_view value = _name.string_view(); +}; + +constexpr rfl::StringLiteral kHello("hello"); +constexpr rfl::StringLiteral kSpace(" "); +constexpr rfl::StringLiteral kWorld("world"); +constexpr rfl::StringLiteral kEmpty(""); + +static_assert(noexcept(kHello.string_view())); +static_assert(kHello.string_view() == "hello"); +static_assert(kHello.length == 5); +static_assert(kEmpty.length == 0); +static_assert(kEmpty.string_view().empty()); + +// Concatenation via operator+ +constexpr auto kGreeting = kHello + kSpace + kWorld; +static_assert(std::same_as>); +static_assert(kGreeting.string_view() == "hello world"); +static_assert(kGreeting.arr_[11] == '\0'); +static_assert(kGreeting == rfl::StringLiteral("hello world")); +static_assert(kGreeting != kHello); +static_assert((kEmpty + kHello) == kHello); +static_assert((kHello + kEmpty) == kHello); +static_assert((kEmpty + kEmpty) == kEmpty); +static_assert((kEmpty + kEmpty).arr_[0] == '\0'); + +// StringLiteral(std::string_view) clamping and null-termination +constexpr rfl::StringLiteral<6> kSvExact(std::string_view("hello")); +static_assert(kSvExact.string_view() == "hello"); +static_assert(kSvExact.arr_[5] == '\0'); + +constexpr rfl::StringLiteral<6> kSvShort(std::string_view("hi")); +static_assert(kSvShort.arr_[0] == 'h'); +static_assert(kSvShort.arr_[1] == 'i'); +static_assert(kSvShort.arr_[2] == '\0'); +static_assert(kSvShort.arr_[5] == '\0'); + +constexpr rfl::StringLiteral<5> kSvClamped(std::string_view("hello")); +static_assert(kSvClamped.string_view() == "hell"); +static_assert(kSvClamped.arr_[4] == '\0'); + +constexpr rfl::StringLiteral<4> kSvOversized(std::string_view("hello world")); +static_assert(kSvOversized.string_view() == "hel"); +static_assert(kSvOversized.arr_[3] == '\0'); + +// Compatibility with rfl::internal::StringLiteral ADL & CTAD +constexpr rfl::internal::StringLiteral kInternalHello("hello"); +static_assert(kHello == kInternalHello); +static_assert((kInternalHello + kWorld) == rfl::StringLiteral("helloworld")); +static_assert(PublicNttpHolder<"abc">::value == "abc"); +static_assert(InternalNttpHolder<"abc">::value == "abc"); +static_assert(ExtractLiteralName>::value == "tag"); + +// Single-value rfl::Literal::name_view() +template +concept HasNameView = requires { T::name_view(); }; + +using SingleLit = rfl::Literal<"only">; +using MultiLit = rfl::Literal<"first", "second">; +static_assert(HasNameView); +static_assert(!HasNameView); +static_assert(SingleLit::name_view() == "only"); +static_assert(noexcept(SingleLit::name_view())); +static_assert(MultiLit::name_of<1>().name_view() == "second"); + +constexpr rfl::StringLiteral kPrefix("user_"); +constexpr rfl::StringLiteral kSuffix("name"); +constexpr rfl::StringLiteral kDesc = + rfl::StringLiteral("Display ") + rfl::StringLiteral("name"); + +struct Composed { + rfl::Rename> name; + rfl::Literal tag; +}; + +TEST(json, test_string_literal) { + EXPECT_EQ(kGreeting.str(), "hello world"); + EXPECT_EQ(SingleLit().name_view(), "only"); + + const auto field = rfl::Field(42); + EXPECT_EQ(field.name(), "user_name"); + EXPECT_EQ(field.value(), 42); + + const Composed input{.name = std::string("Alice"), + .tag = rfl::Literal()}; + const auto json_str = rfl::json::write(input); + EXPECT_EQ(json_str, R"({"user_name":"Alice","tag":"helloworld"})"); + + const auto parsed = rfl::json::read(json_str); + ASSERT_TRUE(parsed.has_value()) << parsed.error().what(); + EXPECT_EQ(parsed->name.value().value(), "Alice"); + EXPECT_EQ(parsed->tag.name_view(), "helloworld"); +} + +} // namespace test_string_literal diff --git a/tests/json/test_transform_enum_names.cpp b/tests/json/test_transform_enum_names.cpp new file mode 100644 index 000000000..a81be370a --- /dev/null +++ b/tests/json/test_transform_enum_names.cpp @@ -0,0 +1,135 @@ +#include + +#include +#include +#include + +namespace test_transform_enum_names { + +enum class CostModel { + t_count, + two_qubit_gate_count, + gate_count, +}; + +enum class QuicStack { + Mvfst, + Picoquic, + ProxygenQmux, +}; + +enum class HttpMethod { + GET, + POST, + DELETE, +}; + +enum class Permissions { + read_only = 1, + write_all = 2, +}; + +inline Permissions operator|(Permissions _a, Permissions _b) { + return static_cast(static_cast(_a) | static_cast(_b)); +} + +struct Config { + CostModel cost_model; + QuicStack stack; + HttpMethod method; +}; + +struct FlagConfig { + Permissions perms; +}; + +} // namespace test_transform_enum_names + +template <> +struct rfl::config::enum_descriptions { + static constexpr bool has_descriptions = true; + static std::string_view get(test_transform_enum_names::CostModel _v) { + switch (_v) { + case test_transform_enum_names::CostModel::t_count: + return "T-gate count"; + case test_transform_enum_names::CostModel::two_qubit_gate_count: + return "Two-qubit gate count"; + case test_transform_enum_names::CostModel::gate_count: + return "Total gate count"; + } + return ""; + } +}; + +namespace test_transform_enum_names { + +TEST(json, test_transform_enum_names_roundtrip) { + const auto cfg = Config{.cost_model = CostModel::two_qubit_gate_count, + .stack = QuicStack::ProxygenQmux, + .method = HttpMethod::POST}; + + const auto kebab = rfl::json::write(cfg); + EXPECT_NE(kebab.find("\"two-qubit-gate-count\""), std::string::npos); + const auto back_kebab = + rfl::json::read(kebab).value(); + EXPECT_EQ(back_kebab.cost_model, CostModel::two_qubit_gate_count); + + const auto snake = rfl::json::write(cfg); + EXPECT_NE(snake.find("\"proxygen_qmux\""), std::string::npos); + const auto back_snake = + rfl::json::read(snake).value(); + EXPECT_EQ(back_snake.stack, QuicStack::ProxygenQmux); + + const auto lower = rfl::json::write(cfg); + EXPECT_NE(lower.find("\"post\""), std::string::npos); + const auto back_lower = + rfl::json::read(lower).value(); + EXPECT_EQ(back_lower.method, HttpMethod::POST); + + EXPECT_EQ((rfl::enum_to_string( + CostModel::two_qubit_gate_count)), + "twoQubitGateCount"); + EXPECT_EQ((rfl::enum_to_string( + CostModel::two_qubit_gate_count)), + "TwoQubitGateCount"); + EXPECT_EQ((rfl::enum_to_string( + CostModel::t_count)), + "T_COUNT"); + + const auto parsed_sv = + rfl::string_to_enum( + "two-qubit-gate-count"); + ASSERT_TRUE(parsed_sv.has_value()); + EXPECT_EQ(*parsed_sv, CostModel::two_qubit_gate_count); + + // EnumNamesOnly rejects raw C++ spelling when processor transforms it. + const auto rejected = + rfl::string_to_enum( + "two_qubit_gate_count"); + EXPECT_FALSE(rejected.has_value()); + EXPECT_NE(rejected.error().what().find("two-qubit-gate-count"), + std::string::npos); +} + +TEST(json, test_transform_enum_names_flags_and_schema) { + const auto fcfg = + FlagConfig{.perms = Permissions::read_only | Permissions::write_all}; + const auto js = rfl::json::write(fcfg); + EXPECT_EQ(js, R"({"perms":"read-only|write-all"})"); + const auto back = + rfl::json::read(js).value(); + EXPECT_EQ(static_cast(back.perms), + static_cast(Permissions::read_only | Permissions::write_all)); + + // Schema honors transformed names including described enums. + const auto schema = + rfl::json::to_schema(); + EXPECT_NE(schema.find("\"two-qubit-gate-count\""), std::string::npos); + EXPECT_NE(schema.find("Two-qubit gate count"), std::string::npos); + + const auto snake_schema = + rfl::json::to_schema(); + EXPECT_NE(snake_schema.find("\"proxygen_qmux\""), std::string::npos); +} + +} // namespace test_transform_enum_names diff --git a/tests/json/test_type_name.cpp b/tests/json/test_type_name.cpp new file mode 100644 index 000000000..587311395 --- /dev/null +++ b/tests/json/test_type_name.cpp @@ -0,0 +1,28 @@ +#include + +#include +#include +#include + +namespace test_type_name { + +struct SampleStruct { + int a; + double b; +}; + +enum class Color { red, green, blue }; + +static_assert(!rfl::type_name_v.empty()); +static_assert(rfl::type_name() == rfl::type_name_v); +static_assert(rfl::type_name_v.find("SampleStruct") != + std::string_view::npos); +static_assert(rfl::type_name_v.find("Color") != std::string_view::npos); + +TEST(json, test_type_name_matches_type_name_t) { + EXPECT_EQ(rfl::type_name(), + rfl::type_name_t().str()); + EXPECT_EQ(rfl::type_name_v, rfl::type_name_t().str()); +} + +} // namespace test_type_name diff --git a/tests/json_c_arrays_and_inheritance/test_c_array_has_default_val.cpp b/tests/json_c_arrays_and_inheritance/test_c_array_has_default_val.cpp new file mode 100644 index 000000000..3470fefce --- /dev/null +++ b/tests/json_c_arrays_and_inheritance/test_c_array_has_default_val.cpp @@ -0,0 +1,33 @@ +#include + +#include +#include +#include + +namespace test_c_array_has_default_val { + +struct WithCArrayDefault { + const int c = 1; + int arr[3] = {1, 2, 3}; + rfl::DefaultVal d = 5; +}; + +struct WithCArrayPlain { + int arr[3] = {1, 2, 3}; + int b = 2; +}; + +TEST(json, test_c_array_has_default_val) { + using rfl::internal::has_default_val_v; + static_assert(has_default_val_v); + static_assert(!has_default_val_v); + + const auto parsed = + rfl::json::read(R"({"c":9,"arr":[4,5,6]})").value(); + EXPECT_EQ(parsed.c, 9); + EXPECT_EQ(parsed.arr[0], 4); + EXPECT_EQ(parsed.arr[2], 6); + EXPECT_EQ(parsed.d.value(), 5); +} + +} // namespace test_c_array_has_default_val diff --git a/tests/xml/test_array_and_indent_fix.cpp b/tests/xml/test_array_and_indent_fix.cpp new file mode 100644 index 000000000..de468f196 --- /dev/null +++ b/tests/xml/test_array_and_indent_fix.cpp @@ -0,0 +1,50 @@ +#include + +#include +#include +#include +#include + +namespace test_xml_array_and_indent_fix { + +struct Person { + std::string name; + int age; +}; + +TEST(xml, test_get_field_from_array_index) { + pugi::xml_document doc; + ASSERT_TRUE(doc.load_string("abc")); + + const rfl::xml::Reader reader; + const auto arr = + reader.to_array(rfl::xml::Reader::InputVarType(doc.child("root").child("item"))); + ASSERT_TRUE(arr.has_value()); + + const auto f0 = reader.get_field_from_array(0, *arr); + const auto f1 = reader.get_field_from_array(1, *arr); + const auto f2 = reader.get_field_from_array(2, *arr); + const auto f3 = reader.get_field_from_array(3, *arr); + + ASSERT_TRUE(f0.has_value()); + ASSERT_TRUE(f1.has_value()); + ASSERT_TRUE(f2.has_value()); + EXPECT_FALSE(f3.has_value()); + + EXPECT_EQ(reader.to_basic_type(*f0).value(), "a"); + EXPECT_EQ(reader.to_basic_type(*f1).value(), "b"); + EXPECT_EQ(reader.to_basic_type(*f2).value(), "c"); + EXPECT_NE(f3.error().what().find("out of bounds"), std::string::npos); +} + +TEST(xml, test_write_forwards_indent) { + const Person p{.name = "Homer", .age = 45}; + const std::string two_spaces = rfl::xml::write(p, " "); + const std::string compact = rfl::xml::write(p, ""); + + EXPECT_NE(two_spaces.find("\n Homer"), std::string::npos) + << two_spaces; + EXPECT_EQ(compact.find(" "), std::string::npos) << compact; +} + +} // namespace test_xml_array_and_indent_fix diff --git a/tests/yaml/test_integers.cpp b/tests/yaml/test_integers.cpp new file mode 100644 index 000000000..67e1d7581 --- /dev/null +++ b/tests/yaml/test_integers.cpp @@ -0,0 +1,222 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_yaml_integers { + +using namespace std::string_view_literals; + +template +struct Holder { + T value; +}; + +template +void expect_round_trip(const T _val) { + const auto yaml = rfl::yaml::write(Holder{.value = _val}); + const auto parsed = rfl::yaml::read>(yaml); + ASSERT_TRUE(parsed.has_value()) + << "yaml='" << yaml << "' error='" << parsed.error().what() << "'"; + EXPECT_EQ(parsed->value, _val); +} + +TEST(yaml, test_negative_to_unsigned_rejected) { + EXPECT_FALSE(rfl::yaml::read>("value: -1\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: -1\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: -1\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: -1\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: \"-1\"\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: \" -1\"\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: -0\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: -0x0\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: -0x1\n"sv).has_value()); +} + +TEST(yaml, test_non_scalar_and_char_integers) { + // Non-scalar nodes must fail cleanly for both signed and unsigned targets. + EXPECT_FALSE(rfl::yaml::read>("value: [1]\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: {a: 1}\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: null\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: [1]\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: {a: 1}\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: null\n"sv).has_value()); + + // Leading '+' remains accepted for both unsigned and signed scalars. + const auto plus_u32 = rfl::yaml::read>("value: +42\n"sv); + ASSERT_TRUE(plus_u32.has_value()); + EXPECT_EQ(plus_u32->value, 42U); + const auto plus_i32 = rfl::yaml::read>("value: +42\n"sv); + ASSERT_TRUE(plus_i32.has_value()); + EXPECT_EQ(plus_i32->value, 42); + + // signed char / unsigned char / char bounds. + EXPECT_FALSE( + rfl::yaml::read>("value: -129\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: 128\n"sv).has_value()); + const auto sc = rfl::yaml::read>("value: -128\n"sv); + ASSERT_TRUE(sc.has_value()); + EXPECT_EQ(sc->value, static_cast(-128)); + + EXPECT_FALSE( + rfl::yaml::read>("value: -1\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: 256\n"sv).has_value()); + const auto uc = rfl::yaml::read>("value: 255\n"sv); + ASSERT_TRUE(uc.has_value()); + EXPECT_EQ(uc->value, static_cast(255)); + + const auto ch = rfl::yaml::read>("value: 65\n"sv); + ASSERT_TRUE(ch.has_value()); + EXPECT_EQ(ch->value, static_cast(65)); +} + +TEST(yaml, test_integer_round_trip) { + expect_round_trip(std::numeric_limits::min()); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(0); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(std::numeric_limits::min()); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(std::numeric_limits::min()); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(std::numeric_limits::min()); + expect_round_trip(std::numeric_limits::max()); + expect_round_trip(0); + expect_round_trip(9223372036854775808ULL); + expect_round_trip(std::numeric_limits::max()); + + // Sequence elements exercise Writer::insert_value(const T&). + const std::vector seq{0ULL, 9223372036854775808ULL, + std::numeric_limits::max()}; + const auto seq_yaml = rfl::yaml::write(seq); + const auto seq_parsed = rfl::yaml::read>(seq_yaml); + ASSERT_TRUE(seq_parsed.has_value()) + << "yaml='" << seq_yaml << "' error='" << seq_parsed.error().what() + << "'"; + EXPECT_EQ(*seq_parsed, seq); +} + +TEST(yaml, test_narrow_integer_bounds) { + // int8_t [-128, 127] + EXPECT_FALSE(rfl::yaml::read>("value: -129\n"sv).has_value()); + EXPECT_FALSE(rfl::yaml::read>("value: 128\n"sv).has_value()); + const auto min_i8 = rfl::yaml::read>("value: -128\n"sv); + ASSERT_TRUE(min_i8.has_value()); + EXPECT_EQ(min_i8->value, std::numeric_limits::min()); + const auto max_i8 = rfl::yaml::read>("value: 127\n"sv); + ASSERT_TRUE(max_i8.has_value()); + EXPECT_EQ(max_i8->value, std::numeric_limits::max()); + + // uint8_t [0, 255] + EXPECT_FALSE(rfl::yaml::read>("value: 256\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: 0x100\n"sv).has_value()); + const auto max_u8 = rfl::yaml::read>("value: 255\n"sv); + ASSERT_TRUE(max_u8.has_value()); + EXPECT_EQ(max_u8->value, std::numeric_limits::max()); + + // int16_t [-32768, 32767] + EXPECT_FALSE( + rfl::yaml::read>("value: -32769\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: 32768\n"sv).has_value()); + const auto min_i16 = rfl::yaml::read>("value: -32768\n"sv); + ASSERT_TRUE(min_i16.has_value()); + EXPECT_EQ(min_i16->value, std::numeric_limits::min()); + const auto max_i16 = rfl::yaml::read>("value: 32767\n"sv); + ASSERT_TRUE(max_i16.has_value()); + EXPECT_EQ(max_i16->value, std::numeric_limits::max()); + + // uint16_t [0, 65535] + EXPECT_FALSE( + rfl::yaml::read>("value: 65536\n"sv).has_value()); + const auto max_u16 = rfl::yaml::read>("value: 65535\n"sv); + ASSERT_TRUE(max_u16.has_value()); + EXPECT_EQ(max_u16->value, std::numeric_limits::max()); + + // int32_t [-2147483648, 2147483647] + EXPECT_FALSE( + rfl::yaml::read>("value: -2147483649\n"sv).has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: 2147483648\n"sv).has_value()); + const auto min_i32 = + rfl::yaml::read>("value: -2147483648\n"sv); + ASSERT_TRUE(min_i32.has_value()); + EXPECT_EQ(min_i32->value, std::numeric_limits::min()); + const auto max_i32 = + rfl::yaml::read>("value: 2147483647\n"sv); + ASSERT_TRUE(max_i32.has_value()); + EXPECT_EQ(max_i32->value, std::numeric_limits::max()); + + // uint32_t [0, 4294967295] + EXPECT_FALSE( + rfl::yaml::read>("value: 4294967296\n"sv).has_value()); + const auto max_u32 = + rfl::yaml::read>("value: 4294967295\n"sv); + ASSERT_TRUE(max_u32.has_value()); + EXPECT_EQ(max_u32->value, std::numeric_limits::max()); +} + +TEST(yaml, test_64bit_integer_bounds_and_literals) { + // uint64_t values above INT64_MAX must succeed. + const auto above_i64 = + rfl::yaml::read>("value: 9223372036854775808\n"sv); + ASSERT_TRUE(above_i64.has_value()); + EXPECT_EQ(above_i64->value, 9223372036854775808ULL); + + const auto max_u64 = + rfl::yaml::read>("value: 18446744073709551615\n"sv); + ASSERT_TRUE(max_u64.has_value()); + EXPECT_EQ(max_u64->value, std::numeric_limits::max()); + + // Overflow past UINT64_MAX must fail. + EXPECT_FALSE( + rfl::yaml::read>("value: 18446744073709551616\n"sv) + .has_value()); + + // int64_t boundary values and overflow/underflow. + const auto max_i64 = + rfl::yaml::read>("value: 9223372036854775807\n"sv); + ASSERT_TRUE(max_i64.has_value()); + EXPECT_EQ(max_i64->value, std::numeric_limits::max()); + + const auto min_i64 = + rfl::yaml::read>("value: -9223372036854775808\n"sv); + ASSERT_TRUE(min_i64.has_value()); + EXPECT_EQ(min_i64->value, std::numeric_limits::min()); + + EXPECT_FALSE( + rfl::yaml::read>("value: 9223372036854775808\n"sv) + .has_value()); + EXPECT_FALSE( + rfl::yaml::read>("value: -9223372036854775809\n"sv) + .has_value()); + + // Hex, octal, and bool remain intact. + const auto hex_u8 = rfl::yaml::read>("value: 0xff\n"sv); + ASSERT_TRUE(hex_u8.has_value()); + EXPECT_EQ(hex_u8->value, 255); + + const auto oct_u16 = rfl::yaml::read>("value: 0755\n"sv); + ASSERT_TRUE(oct_u16.has_value()); + EXPECT_EQ(oct_u16->value, 493); + + const auto bool_val = rfl::yaml::read>("value: true\n"sv); + ASSERT_TRUE(bool_val.has_value()); + EXPECT_TRUE(bool_val->value); +} + +} // namespace test_yaml_integers diff --git a/tests/yaml/test_non_scalar_keys.cpp b/tests/yaml/test_non_scalar_keys.cpp new file mode 100644 index 000000000..f7bf6d52b --- /dev/null +++ b/tests/yaml/test_non_scalar_keys.cpp @@ -0,0 +1,122 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_yaml_non_scalar_keys { + +using namespace std::string_view_literals; +using Path = std::vector; + +struct Config { + std::string name; +}; + +struct Outer { + Config nested; +}; + +TEST(yaml, test_sequence_key_rejected) { + const auto res = rfl::yaml::read( + "name: ok\n" + "[1, 2]: foo\n"sv); + ASSERT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("scalar"), std::string::npos); + + const auto complex_seq = rfl::yaml::read>( + "? - a\n" + " - b\n" + ": foo\n"sv); + ASSERT_FALSE(complex_seq.has_value()); + EXPECT_NE(complex_seq.error().what().find("scalar"), std::string::npos); + + const auto strict_res = rfl::yaml::read( + "name: ok\n" + "[1, 2]: foo\n"sv); + ASSERT_FALSE(strict_res.has_value()); + EXPECT_NE(strict_res.error().what().find("scalar"), std::string::npos); +} + +TEST(yaml, test_map_key_rejected) { + const auto res = rfl::yaml::read( + "name: ok\n" + "{a: 1}: bar\n"sv); + ASSERT_FALSE(res.has_value()); + EXPECT_NE(res.error().what().find("scalar"), std::string::npos); + + const auto complex_map = rfl::yaml::read( + "? {a: 1}\n" + ": bar\n"sv); + ASSERT_FALSE(complex_map.has_value()); + EXPECT_NE(complex_map.error().what().find("scalar"), std::string::npos); +} + +TEST(yaml, test_nested_non_scalar_key_reports_path) { + const auto res = rfl::yaml::read( + "nested:\n" + " name: ok\n" + " [1, 2]: bad\n"sv); + ASSERT_FALSE(res.has_value()); + const auto details = res.error().details(); + ASSERT_EQ(details.size(), 1U) << res.error().what(); + EXPECT_EQ(details[0].path, (Path{"nested"})); + EXPECT_EQ(details[0].message, "YAML mapping key must be a scalar."); +} + +TEST(yaml, test_collection_alias_key_rejected) { + // Note: YAML requires whitespace before `:` after an alias (`*s :`) so `:` + // is not scanned as part of the anchor name. + const auto seq_alias = rfl::yaml::read( + "seq: &s [1, 2]\n" + "*s : bad\n"sv); + ASSERT_FALSE(seq_alias.has_value()); + EXPECT_NE(seq_alias.error().what().find("scalar"), std::string::npos); + + const auto map_alias = rfl::yaml::read( + "map: &m {a: 1}\n" + "*m : bad\n"sv); + ASSERT_FALSE(map_alias.has_value()); + EXPECT_NE(map_alias.error().what().find("scalar"), std::string::npos); + + // Scalar aliases resolve through to scalar keys and remain accepted. + const auto scalar_alias = rfl::yaml::read( + "k: &k name\n" + "*k : ok\n"sv); + ASSERT_TRUE(scalar_alias.has_value()) << scalar_alias.error().what(); + EXPECT_EQ(scalar_alias->name, "ok"); +} + +TEST(yaml, test_scalar_null_and_merge_keys_accepted) { + const auto null_key = + rfl::yaml::read>("null: foo\n"sv); + ASSERT_TRUE(null_key.has_value()) << null_key.error().what(); + ASSERT_EQ(null_key->count("null"), 1U); + EXPECT_EQ(null_key->at("null"), "foo"); + + const auto tilde_key = + rfl::yaml::read>("~: bar\n"sv); + ASSERT_TRUE(tilde_key.has_value()) << tilde_key.error().what(); + ASSERT_EQ(tilde_key->count("null"), 1U); + EXPECT_EQ(tilde_key->at("null"), "bar"); + + const auto empty_key = + rfl::yaml::read>(": val\n"sv); + ASSERT_TRUE(empty_key.has_value()) << empty_key.error().what(); + ASSERT_EQ(empty_key->count("null"), 1U); + EXPECT_EQ(empty_key->at("null"), "val"); + + // Merge key (`<<`) is a scalar key and must not fail as a non-scalar key. + const auto merge_key = rfl::yaml::read( + "defaults: &def\n" + " extra: 1\n" + "<<: *def\n" + "name: ok\n"sv); + ASSERT_TRUE(merge_key.has_value()) << merge_key.error().what(); + EXPECT_EQ(merge_key->name, "ok"); +} + +} // namespace test_yaml_non_scalar_keys diff --git a/tests/yaml/test_recursive_alias.cpp b/tests/yaml/test_recursive_alias.cpp new file mode 100644 index 000000000..e434f50ae --- /dev/null +++ b/tests/yaml/test_recursive_alias.cpp @@ -0,0 +1,84 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_yaml_recursive_alias { + +using Path = std::vector; + +struct Endpoint { + std::string host; + int port; +}; + +struct Cluster { + Endpoint defaults; + Endpoint primary; + Endpoint secondary; +}; + +struct TreeNode { + std::string name; + std::optional> child; +}; + +TEST(yaml, test_non_recursive_alias_allowed) { + const std::string yaml_str = + "defaults: &def\n" + " host: localhost\n" + " port: 8080\n" + "primary: *def\n" + "secondary: *def\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result->primary.host, "localhost"); + EXPECT_EQ(result->primary.port, 8080); + EXPECT_EQ(result->secondary.host, "localhost"); + EXPECT_EQ(result->secondary.port, 8080); +} + +TEST(yaml, test_recursive_mapping_alias_rejected) { + const std::string yaml_str = + "&self\n" + "name: loop\n" + "child: *self\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1) << result.error().what(); + EXPECT_EQ(details[0].path, (Path{"child"})); + EXPECT_EQ(details[0].message, "Recursive YAML alias detected."); +} + +TEST(yaml, test_recursive_sequence_alias_rejected) { + const std::string yaml_str = + "&seq\n" + "- *seq\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); +} + +TEST(yaml, test_mutual_recursive_alias_rejected) { + const std::string yaml_str = + "&a\n" + "name: a\n" + "child: &b\n" + " name: b\n" + " child: *a\n"; + + const auto result = rfl::yaml::read(yaml_str); + ASSERT_FALSE(result); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1) << result.error().what(); + EXPECT_EQ(details[0].path, (Path{"child", "child"})); + EXPECT_EQ(details[0].message, "Recursive YAML alias detected."); +} + +} // namespace test_yaml_recursive_alias