From c909e0218565ccb33a5436d8d5c62cdbe9cd1aaf Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:00:19 +0100 Subject: [PATCH 001/472] Add compiler-first Native Web applications on Foco --- README.md | 7 + docs/design/native-web.md | 38 ++ .../native/webscene_native_style_defaults.h | 69 +++ .../native/webscene_v8_runtime.cpp | 1 + .../native/webscene_v8_runtime_support.inc | 60 +-- samples/NativeWeb/Main.css | 17 + samples/NativeWeb/Main.html | 27 + samples/NativeWeb/README.md | 114 ++++ samples/NativeWeb/Resources/about.txt | 1 + samples/NativeWeb/app.hpp | 36 ++ samples/NativeWeb/build.py | 76 +++ samples/NativeWeb/main.mm | 154 ++++++ samples/NativeWeb/measure.py | 34 ++ samples/NativeWeb/measurements.json | 119 +++++ samples/NativeWeb/smoke.cpp | 95 ++++ samples/NativeWeb/validation.md | 66 +++ src/WebScene.NativeWeb/CMakeLists.txt | 74 +++ .../foco/native_web_view.hpp | 121 +++++ .../include/webscene/native_web.hpp | 166 ++++++ src/WebScene.NativeWeb/src/native_web.cpp | 459 ++++++++++++++++ tests/NativeWeb/Contracts.html | 11 + tests/NativeWeb/compiler_tests.py | 33 ++ tests/NativeWeb/contracts.cpp | 106 ++++ tests/NativeWeb/foco_focus.cpp | 42 ++ tests/NativeWeb/parsed_reference.py | 51 ++ tooling/webscene-uic/main.cpp | 500 ++++++++++++++++++ 26 files changed, 2418 insertions(+), 59 deletions(-) create mode 100644 docs/design/native-web.md create mode 100644 experiments/WebScene.NativeEngine.Probe/native/webscene_native_style_defaults.h create mode 100644 samples/NativeWeb/Main.css create mode 100644 samples/NativeWeb/Main.html create mode 100644 samples/NativeWeb/README.md create mode 100644 samples/NativeWeb/Resources/about.txt create mode 100644 samples/NativeWeb/app.hpp create mode 100644 samples/NativeWeb/build.py create mode 100644 samples/NativeWeb/main.mm create mode 100644 samples/NativeWeb/measure.py create mode 100644 samples/NativeWeb/measurements.json create mode 100644 samples/NativeWeb/smoke.cpp create mode 100644 samples/NativeWeb/validation.md create mode 100644 src/WebScene.NativeWeb/CMakeLists.txt create mode 100644 src/WebScene.NativeWeb/foco/native_web_view.hpp create mode 100644 src/WebScene.NativeWeb/include/webscene/native_web.hpp create mode 100644 src/WebScene.NativeWeb/src/native_web.cpp create mode 100644 tests/NativeWeb/Contracts.html create mode 100644 tests/NativeWeb/compiler_tests.py create mode 100644 tests/NativeWeb/contracts.cpp create mode 100644 tests/NativeWeb/foco_focus.cpp create mode 100644 tests/NativeWeb/parsed_reference.py create mode 100644 tooling/webscene-uic/main.cpp diff --git a/README.md b/README.md index 4f942756c..d3bbe7b89 100644 --- a/README.md +++ b/README.md @@ -259,3 +259,10 @@ safe renderer for arbitrary untrusted websites or scripts. The repository uses the terms in [LICENSE](LICENSE), including its Restricted Party Clause. Describe it as a custom source-available license, not unqualified MIT or an OSI-approved open-source license. + +## Native Web: compiled HTML/CSS and C++ + +The [Native Web sample](samples/NativeWeb/README.md) compiles HTML/CSS into C++ and +runs C++ application logic on WebScene's native DOM/layout with Foco's Cocoa/Metal +host, without deploying V8 or runtime UI parsers. This is an initial, explicitly +bounded compiler profile. See the [architecture and future binding note](docs/design/native-web.md). diff --git a/docs/design/native-web.md b/docs/design/native-web.md new file mode 100644 index 000000000..063f82ec8 --- /dev/null +++ b/docs/design/native-web.md @@ -0,0 +1,38 @@ +# Native Web first + +Deliver HTML/CSS compiled to C++, C++ application logic, and no JavaScript runtime, +running on Foco's platform and compositor. WebScene owns the compiler and document +semantics; Foco supplies the host. Start on macOS, reusing the existing native DOM, +layout and scene output. Do not turn HTML into Foco controls. + +Implementation order: native document API; HTML/CSS compiler; working Foco sample; +build/run, diagnostics and packaging. Acceptance includes responsive layout, +native events, dynamic text/classes/nodes, keyboard focus, Canvas, parser-free and +V8-free application linkage, parsed/compiled equivalence and measured costs. + +Generated views have explicit construction/disposal boundaries. Application state +lives outside them. Keep source/named-element metadata for future hot design; +hot replacement and state restoration are not part of the first implementation. + +## Future idea: typed HTML data contexts and bindings + +Consider XAML-like data contexts and `{Binding ...}` expressions in authored HTML, +backed by C++ view models. A future compiler could validate a declared context type +and generate direct typed property/command access and change subscriptions, +without JavaScript, reflection or runtime string-path lookup. Reuse Foco's existing +view-model/property infrastructure where appropriate through optional adapters; +keep WebScene independently embeddable. The syntax, context inheritance, binding +modes and adapter contracts are deliberately not specified or implemented yet. +This is a future feature, not a prerequisite for Native Web. + +Later work: optional JS on the same native document, broader platform/language +coverage, integrated SDK packaging and hot design. + +## Initial implementation + +The first macOS Native Web slice is implemented in `src/WebScene.NativeWeb`, with +`tooling/webscene-uic` and the copyable `samples/NativeWeb` application. The sample +README documents its deliberately bounded HTML/CSS profile; `validation.md` records +actual acceptance results and limitations. Foco integration uses one scene carrier, +its compositor, and an embedded-focus navigation hook. Broader host extraction and +full web API coverage remain subsequent work. diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_native_style_defaults.h b/experiments/WebScene.NativeEngine.Probe/native/webscene_native_style_defaults.h new file mode 100644 index 000000000..888df1719 --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_native_style_defaults.h @@ -0,0 +1,69 @@ +#pragma once +#include "webscene_native_dom.h" +#include + +namespace webscene_native { +inline display_mode native_default_display_for_tag(std::string_view tag) +{ + constexpr std::array non_rendered_tags{ + "base", "head", "link", "meta", "script", "style", "template", "title"}; + if (std::find(non_rendered_tags.begin(), non_rendered_tags.end(), tag) + != non_rendered_tags.end()) { + return display_mode::none; + } + if (tag == "table") return display_mode::table; + if (tag == "thead") return display_mode::table_header_group; + if (tag == "tbody") return display_mode::table_row_group; + if (tag == "tfoot") return display_mode::table_footer_group; + if (tag == "tr") return display_mode::table_row; + if (tag == "td" || tag == "th") return display_mode::table_cell; + if (tag == "colgroup") return display_mode::table_column_group; + if (tag == "col") return display_mode::table_column; + if (tag == "caption") return display_mode::table_caption; + if (tag == "li" || tag == "summary") return display_mode::list_item; + // CSS starts elements at `display:inline`; the HTML UA stylesheet then + // promotes only known structural elements. In particular autonomous + // custom elements and HTMLUnknownElement remain inline. Treating every + // unlisted tag as a block made consumer helpers such as + // split a single metadata line into several overlapping flex rows. + constexpr std::array block_tags{ + "address", "article", "aside", "blockquote", "body", "center", + "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", + "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", + "h5", "h6", "header", "hgroup", "html", "hr", "main", "menu", + "nav", "ol", "p", "pre", "search", "section", "ul", "legend"}; + if (std::find(block_tags.begin(), block_tags.end(), tag) != block_tags.end()) { + return display_mode::block; + } + constexpr std::array inline_block_tags{ + "button", "img", "input", "meter", "progress", "rect", "select", + "textarea", "object"}; + if (std::find(inline_block_tags.begin(), inline_block_tags.end(), tag) + != inline_block_tags.end()) { + return display_mode::inline_block; + } + return display_mode::inline_flow; +} + +inline display_mode native_default_display_for_node(const dom_node& node) +{ + if (node.kind != dom_node_kind::element) { + return node.kind == dom_node_kind::text + ? display_mode::inline_flow + : display_mode::none; + } + if (node.attributes.contains("hidden")) return display_mode::none; + if (node.tag == "input") { + const auto type = node.attributes.find("type"); + if (type != node.attributes.end()) { + auto value = type->second; + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char character) { + return static_cast(std::tolower(character)); + }); + if (value == "hidden") return display_mode::none; + } + } + return native_default_display_for_tag(node.tag); +} + +} diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp index a2e0055e3..650514025 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp @@ -1,6 +1,7 @@ #include "webscene_v8_runtime.h" #include "webscene_native_dom.h" +#include "webscene_native_style_defaults.h" #include "webscene_native_websocket.h" #if defined(WEBSCENE_NATIVE_ENGINE_HTML5EVER) #include "webscene_html_parser.h" diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_support.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_support.inc index c769d9aeb..381115ea1 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_support.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_support.inc @@ -515,48 +515,6 @@ void configure_startup_snapshot(v8::Isolate::CreateParams&) {} constexpr bool bootstrap_snapshot_enabled = false; #endif -display_mode default_display_for_tag(std::string_view tag) -{ - constexpr std::array non_rendered_tags{ - "base", "head", "link", "meta", "script", "style", "template", "title"}; - if (std::find(non_rendered_tags.begin(), non_rendered_tags.end(), tag) - != non_rendered_tags.end()) { - return display_mode::none; - } - if (tag == "table") return display_mode::table; - if (tag == "thead") return display_mode::table_header_group; - if (tag == "tbody") return display_mode::table_row_group; - if (tag == "tfoot") return display_mode::table_footer_group; - if (tag == "tr") return display_mode::table_row; - if (tag == "td" || tag == "th") return display_mode::table_cell; - if (tag == "colgroup") return display_mode::table_column_group; - if (tag == "col") return display_mode::table_column; - if (tag == "caption") return display_mode::table_caption; - if (tag == "li" || tag == "summary") return display_mode::list_item; - // CSS starts elements at `display:inline`; the HTML UA stylesheet then - // promotes only known structural elements. In particular autonomous - // custom elements and HTMLUnknownElement remain inline. Treating every - // unlisted tag as a block made consumer helpers such as - // split a single metadata line into several overlapping flex rows. - constexpr std::array block_tags{ - "address", "article", "aside", "blockquote", "body", "center", - "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", - "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", - "h5", "h6", "header", "hgroup", "html", "hr", "main", "menu", - "nav", "ol", "p", "pre", "search", "section", "ul", "legend"}; - if (std::find(block_tags.begin(), block_tags.end(), tag) != block_tags.end()) { - return display_mode::block; - } - constexpr std::array inline_block_tags{ - "button", "img", "input", "meter", "progress", "rect", "select", - "textarea", "object"}; - if (std::find(inline_block_tags.begin(), inline_block_tags.end(), tag) - != inline_block_tags.end()) { - return display_mode::inline_block; - } - return display_mode::inline_flow; -} - display_mode parse_display_mode(std::string_view value) { if (value == "flex") return display_mode::flex; @@ -687,23 +645,7 @@ void refresh_overflow_state(node_style& style) display_mode default_display_for_node(const dom_node& node) { - if (node.kind != dom_node_kind::element) { - return node.kind == dom_node_kind::text - ? display_mode::inline_flow - : display_mode::none; - } - if (node.attributes.contains("hidden")) return display_mode::none; - if (node.tag == "input") { - const auto type = node.attributes.find("type"); - if (type != node.attributes.end()) { - auto value = type->second; - std::transform(value.begin(), value.end(), value.begin(), [](unsigned char character) { - return static_cast(std::tolower(character)); - }); - if (value == "hidden") return display_mode::none; - } - } - return default_display_for_tag(node.tag); + return native_default_display_for_node(node); } float inherited_font_size(const dom_node& node) diff --git a/samples/NativeWeb/Main.css b/samples/NativeWeb/Main.css new file mode 100644 index 000000000..a4ca92ac0 --- /dev/null +++ b/samples/NativeWeb/Main.css @@ -0,0 +1,17 @@ +body { margin: 0; background: #101923; color: #dce8f0; font-size: 16px; } +main { padding: 32px; } +.eyebrow { color: #78dcc1; font-size: 13px; } +h1 { font-size: 36px; margin: 16px 0; } +h2 { font-size: 21px; margin: 0 0 16px; } +p { margin: 12px 0; } +#workspace { display: flex; gap: 24px; margin-top: 28px; } +.card { background: #1c2a38; border-radius: 16px; padding: 24px; flex-grow: 1; flex-basis: 0; min-width: 0; } +.card.active { background: #254b48; } +.actions { display: flex; gap: 12px; } +button { background: #78dcc1; color: #101923; padding: 12px 18px; border-radius: 8px; margin: 8px 0; } +button.secondary { background: #b0c4d4; } +button:hover { background: #b9f4e4; } +button:focus { background: #ffffff; } +#count { font-size: 30px; } +canvas { width: 300px; height: 120px; } +@media (max-width: 700px) { #workspace { flex-direction: column; } main { padding: 20px; } } diff --git a/samples/NativeWeb/Main.html b/samples/NativeWeb/Main.html new file mode 100644 index 000000000..9da7ca7b8 --- /dev/null +++ b/samples/NativeWeb/Main.html @@ -0,0 +1,27 @@ + +Foco Native Web + + +
+

FOCO / NATIVE WEB

+

HTML. CSS. Native C++.

+

Compiled views. A live DOM. No JavaScript runtime.

+
+
+

Your application, compiled.

+

Count: 0

+
+ + +
+

Use Tab and Enter, or click. Resize the window.

+
+
+

Native Canvas

+ + +
+
+
+
+ diff --git a/samples/NativeWeb/README.md b/samples/NativeWeb/README.md new file mode 100644 index 000000000..8ad8931a4 --- /dev/null +++ b/samples/NativeWeb/README.md @@ -0,0 +1,114 @@ +# Foco Native Web + +A first working Native Web vertical slice: HTML/CSS compiled to C++, C++ application +logic, WebScene native DOM/layout/Canvas, and Foco Cocoa/Skia Graphite/Metal output. +The application contains no V8 or HTML/CSS/selector parser. Those parsers are linked +only into the build-time `webscene-uic` executable. + +## Build and run + +Prerequisites: macOS, Xcode command-line SDKs, CMake, Ninja, Cargo, Python 3, and a +FocoUI checkout with its existing `.deps/skia` native Graphite build. The helper uses +Homebrew LLVM when available and explicitly supplies the Xcode SDK. It does not +modify the Foco checkout or download a replacement graphics stack. + +From the WebScene repository root: + +```sh +python3 samples/NativeWeb/build.py --foco /path/to/FocoUI --run +``` + +This builds the compiler, compiles `Main.html` and `Main.css`, runs the native and +compiler contracts, verifies system-only application dependencies, checks for +V8/parser symbols/assets, captures the rendered application, and tests a relocated +bundle. Outputs live in `artifacts/native-web-foco/`: + +- `FocoNativeWeb.app`: launchable application; its only custom resource is `about.txt`. +- `native-web.png`: actual Foco compositor capture. +- `verification.json`: measurements and verification results. +- `build.log`: configure, compilation and test output. + +Foco needs the accompanying embedded-focus navigation hook and renderer change +that reads WebScene's current +seven-field DOM text record (including font smoothing). A checkout with the older +six-field reader renders the smoothing field instead of the text. + +For just the compiler/runtime contracts, without Foco or Skia: + +```sh +python3 samples/NativeWeb/build.py +``` + +For optional comparison against a V8-enabled WebScene reference engine **built from +the same WebScene revision**, include `--reference-engine /path/to/libwebscene_native_engine.dylib`. +Its ICU/bootstrap assets must be beside that library. V8 is used only by the separate +reference test process and is never linked into or packaged with the application. + +## Authoring + +Edit `Main.html` and `Main.css`, then rerun the build. CMake depfiles track external +stylesheets. `app.hpp` contains native state, handlers and drawing; `main.mm` supplies +the macOS application bootstrap and resource loading. These files form the initial +copyable application template; a unified `foco new` command remains subsequent work. + +Generated code constructs live WebScene DOM nodes and installs selectors plus typed +style-setting functions. Lengths and colors are converted at build time. Selectors +are parsed by WebScene's existing Servo frontend, HTML by html5ever and stylesheet +syntax by cssparser. Dynamic selector matching, cascade, layout and rendering remain +native runtime work. Unsupported authoring fails compilation; nothing falls back to +JavaScript. Native events bubble; subscriptions own callback registrations. + +The C++ `document` API supports creation, text/attribute/class mutation, removal, +named lookup, subscription/disposal, focus/Tab/button activation, hit testing and +Canvas rectangle drawing. Documents enforce creating-thread access. Applications +must dispatch external work to that thread and call the host's `refresh()` after +mutations outside host input handling. The host does not request continuous idle +frames. Node IDs are document-local, are not recycled, and become invalid on removal. + +The Foco adapter uses one control as a scene carrier for the entire native document. +HTML elements are not Foco controls. A wider extraction of Foco's host from its control +assembly is deliberately deferred; this slice reuses its existing application shell. + +## Initial supported compiler profile + +- Structural HTML: body, main, section, div, span, p, h1–h3, button, canvas, ul/li, + header/footer/nav. Head metadata and local stylesheet links are build-time inputs. +- Selectors: tag/universal, ID, classes, compound selectors, descendant/child + combinators, selector lists, `:focus`, `:hover`. +- Cascade: specificity, source order, inline styles and `!important`. +- Responsive conditions: nested `@media (min-width: Npx)` / `(max-width: Npx)`. +- Styles: block/inline/inline-block/flex/none, basic flex direction/alignment/growth, + size and positional lengths, margin/padding/gap/radii, box sizing, color, + background color, pixel font sizes, numeric font weight and opacity. +- Canvas: clear and fill rectangles using the existing native display-list protocol. +- Resources: native app bundle resources, demonstrated by C++ loading `about.txt`. + Image/font URL compilation and general web resource loading are not implemented. + +This is not full HTML/CSS parity or a completed SDK. Grid, CSS variables, animation, +advanced selectors, arbitrary CSS functions, editable text/IME, DOM accessibility +projection and general Canvas/GPU/media native APIs are not exposed by this initial +profile. Existing engines retain their broader capabilities. Optional JS, language +projections, hot design and the proposed typed HTML data contexts/bindings are future +work, recorded in `docs/design/native-web.md`. + +## Lifetime and future hot design + +Each application owns its `document`; generated view metadata contains only node IDs. +Keep view-model state outside generated UI and dispose the document/subscriptions +before releasing captured application state. Destruction unregisters callbacks; +explicit disposal rejects subsequent operations. Generated source mappings and named +references preserve a boundary for a future replaceable-view implementation. No +reload ABI, subtree hot replacement or state-restoration protocol is promised yet. + +## Measurements + +After building, run: + +```sh +python3 samples/NativeWeb/measure.py artifacts/native-web-foco +``` + +This records 20 native construction/interaction runs, build-time UI parsing and C++ +compilation costs, process RSS and bundle size in `measurements.json`. The report +separates native document construction from process/GPU startup and explicitly labels +warm filesystem caches and the Cocoa smoke test's deliberate delay. diff --git a/samples/NativeWeb/Resources/about.txt b/samples/NativeWeb/Resources/about.txt new file mode 100644 index 000000000..f9df9c491 --- /dev/null +++ b/samples/NativeWeb/Resources/about.txt @@ -0,0 +1 @@ +Compiled views. A live DOM. No JavaScript runtime. diff --git a/samples/NativeWeb/app.hpp b/samples/NativeWeb/app.hpp new file mode 100644 index 000000000..c9d0c0408 --- /dev/null +++ b/samples/NativeWeb/app.hpp @@ -0,0 +1,36 @@ +#pragma once +#include +struct app_state { + int count{}, items{}; + std::vector subscriptions; + void attach(webscene::native_web::document &d) { + auto redraw = [this, &d] { + d.set_text(d.find("count"), "Count: " + std::to_string(count)); + d.attribute(d.find("counterCard"), "class", + count ? "card active" : "card"); + auto chart = d.find("chart"); + d.clear_canvas(chart); + for (int i = 0; i < 8; ++i) { + float h = 20 + ((i * 17 + count * 13) % 85); + d.fill_rect(chart, i * 36, 120 - h, 24, h, 0x78dcc1ffu); + } + }; + subscriptions.push_back( + d.on(d.find("increment"), "click", [this, redraw](auto &) { + ++count; + redraw(); + })); + subscriptions.push_back( + d.on(d.find("reset"), "click", [this, redraw](auto &) { + count = 0; + redraw(); + })); + subscriptions.push_back(d.on(d.find("add"), "click", [this, &d](auto &) { + auto item = d.element(d.find("items"), "button"); + d.text(item, "Item " + std::to_string(++items) + " - click to remove"); + subscriptions.push_back( + d.on(item, "click", [&d, item](auto &) { d.remove(item); })); + })); + redraw(); + } +}; diff --git a/samples/NativeWeb/build.py b/samples/NativeWeb/build.py new file mode 100644 index 000000000..fe2df1556 --- /dev/null +++ b/samples/NativeWeb/build.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Build and verify the Native Web sample. No UI parser or JS engine is deployed.""" +import argparse +import json +import pathlib +import shutil +import subprocess +import time + +repo=pathlib.Path(__file__).resolve().parents[2] +p=argparse.ArgumentParser() +p.add_argument('--foco',type=pathlib.Path,help='FocoUI source checkout; builds the Cocoa/Metal app') +p.add_argument('--build-dir',type=pathlib.Path) +p.add_argument('--run',action='store_true',help='Open the packaged app after verification') +p.add_argument('--reference-engine',type=pathlib.Path,help='Optional V8-enabled engine built from this checkout, for parity checks') +args=p.parse_args() +build=(args.build_dir or repo/'artifacts'/('native-web-foco' if args.foco else 'native-web')).resolve() +build.mkdir(parents=True,exist_ok=True) +log=build/'build.log' +def run(command): + with log.open('a') as output: + result=subprocess.run([str(x) for x in command],stdout=output,stderr=subprocess.STDOUT) + if result.returncode:raise RuntimeError(f'Command failed ({result.returncode}); see {log}: {command}') +configure=['cmake','-S',repo/'src/WebScene.NativeWeb','-B',build,'-G','Ninja','-DCMAKE_BUILD_TYPE=Release','-DBUILD_TESTING=ON','-DCMAKE_CXX_SCAN_FOR_MODULES=OFF'] +if args.foco: + sdk=subprocess.check_output(['xcrun','--show-sdk-path'],text=True).strip() + configure += [f'-DFOCO_SOURCE_DIR={args.foco.resolve()}',f'-DCMAKE_OSX_SYSROOT={sdk}'] + llvm=pathlib.Path('/opt/homebrew/opt/llvm/bin/clang++') + if llvm.exists():configure += [f'-DCMAKE_CXX_COMPILER={llvm}',f'-DCMAKE_OBJCXX_COMPILER={llvm}'] +start=time.perf_counter();run(configure) +targets=['webscene-uic','native_web_smoke','native_web_contracts']+(['FocoNativeWeb','native_web_foco_focus'] if args.foco else []) +run(['cmake','--build',build,'--target',*targets,'-j','6']) +build_seconds=time.perf_counter()-start +run(['ctest','--test-dir',build,'--output-on-failure','-R','^native_web_(smoke|contracts|compiler|foco_focus)$']) +result={'build_seconds':build_seconds,'build_timing_note':'Configure plus build; may be incremental.','smoke':subprocess.check_output([build/'native_web_smoke'],text=True).strip()} +if args.reference_engine: + parsed=json.loads(subprocess.check_output(['python3',repo/'tests/NativeWeb/parsed_reference.py',args.reference_engine.resolve(),repo/'samples/NativeWeb/Main.html'],text=True)) + compiled=json.loads(subprocess.check_output([build/'native_web_smoke','--snapshot'],text=True)) + for expected,actual in zip(parsed,compiled,strict=True): + for a,b in zip(expected['nodes'],actual['nodes'],strict=True): + assert a['id']==b['id'] + for key in ('x','y','width','height'): + assert abs(a[key]-b[key])<.01,(expected['width'],a['id'],key,a[key],b[key]) + result['parsed_compiled_geometry']='12 element/viewport comparisons passed, tolerance 0.01 logical pixels' + (build/'parity.json').write_text(json.dumps({'parsed':parsed,'compiled':compiled},indent=2)+'\n') +if args.foco: + app=build/'FocoNativeWeb.app';exe=app/'Contents/MacOS/FocoNativeWeb' + dependencies=subprocess.check_output(['otool','-L',exe],text=True) + for line in dependencies.splitlines()[1:]: + library=line.strip().split(' (')[0] + assert library.startswith(('/System/Library/','/usr/lib/')),library + symbols=subprocess.check_output(['nm','-j',exe],text=True) + for forbidden in ('_webscene_html_parse','_webscene_css_parse','_webscene_selector_parse','_ZN2v8','_ZN9html5ever','_ZN9cssparser'): + assert forbidden not in symbols,forbidden + for name in ('icudtl.dat','snapshot_blob.bin','webscene_bootstrap_snapshot.bin'): + assert not list(app.rglob(name)),name + run([exe,'--capture',build/'native-web.png']) + # Relocation confirms the app does not depend on its source/build working directory. + relocated=build/'relocated';relocated.mkdir(exist_ok=True) + destination=relocated/app.name + if destination.exists():shutil.rmtree(destination) + shutil.copytree(app,destination) + run([destination/'Contents/MacOS/FocoNativeWeb','--smoke']) + resource=destination/'Contents/Resources/about.txt' + resource.unlink() + with log.open('a') as output: + negative=subprocess.run([destination/'Contents/MacOS/FocoNativeWeb','--smoke'],stdout=output,stderr=subprocess.STDOUT) + assert negative.returncode!=0,'missing resource must fail' + shutil.copy2(app/'Contents/Resources/about.txt',resource) + result['missing_resource_negative_test']='passed' + result['app_bytes']=sum(f.stat().st_size for f in app.rglob('*') if f.is_file()) + result['native_only_dependencies']='system libraries only; no V8/parser symbols or deployment assets' + if args.run:subprocess.run(['open',app],check=True) +(build/'verification.json').write_text(json.dumps(result,indent=2)+'\n') +print(json.dumps(result,indent=2)) +print(f'Build log: {log}') diff --git a/samples/NativeWeb/main.mm b/samples/NativeWeb/main.mm new file mode 100644 index 000000000..a7d0fa403 --- /dev/null +++ b/samples/NativeWeb/main.mm @@ -0,0 +1,154 @@ +#include "FocoNativeWeb_ui.hpp" +#include "app.hpp" +#include "native_web_view.hpp" +#import +#import +#include +#include +#include + +static bool smoke = false; +static int verification_exit = 0; +static std::string capture; +class native_app final : public foco::application { + foco::ref window_; + foco::ref view_; + app_state state_; + +public: + foco::result started(foco::application_lifetime &base) override { + auto *lifetime = dynamic_cast(&base); + if (!lifetime) + return foco::error{foco::error_code::invalid_argument, + "desktop lifetime required"}; + window_ = foco::make_ref(); + window_->set_title("Foco · Native Web"); + window_->set_width(1000); + window_->set_height(700); + view_ = foco::make_ref(); + compiled_ui::build(view_->document); + state_.attach(view_->document); + auto resource = [NSBundle mainBundle].resourcePath; + std::ifstream about(std::string([resource UTF8String]) + "/about.txt"); + if (!about) + return foco::error{foco::error_code::unavailable, + "Missing bundled about.txt resource"}; + std::string introduction; + std::getline(about, introduction); + view_->document.set_text(view_->document.find("intro"), introduction); + window_->add_child(view_); + auto result = window_->show(*lifetime); + if (!result) + return result; + if (smoke || !capture.empty()) + dispatch_after( + dispatch_time(DISPATCH_TIME_NOW, 1500 * NSEC_PER_MSEC), + dispatch_get_main_queue(), ^{ + auto finish = [lifetime](int code) { + verification_exit = code; + lifetime->shutdown(code); + }; + auto &d = view_->document; + NSWindow *native = nil; + for (NSWindow *w in NSApp.windows) + if ([w.title isEqualToString:@"Foco · Native Web"]) + native = w; + auto click = [&](const char *id) { + auto b = d.bounds(d.find(id)); + NSPoint point = NSMakePoint( + b.x + 10, native.contentView.bounds.size.height - b.y - 10); + for (auto type : + {NSEventTypeLeftMouseDown, NSEventTypeLeftMouseUp}) { + NSEvent *e = [NSEvent mouseEventWithType:type + location:point + modifierFlags:0 + timestamp:0 + windowNumber:native.windowNumber + context:nil + eventNumber:1 + clickCount:1 + pressure:1]; + if (type == NSEventTypeLeftMouseDown) + [native.contentView mouseDown:e]; + else + [native.contentView mouseUp:e]; + } + }; + if (!native) { + finish(4); + return; + } + click("increment"); + const auto key = [&](NSString *characters, unsigned short code) { + NSEvent *e = [NSEvent keyEventWithType:NSEventTypeKeyDown + location:NSZeroPoint + modifierFlags:0 + timestamp:0 + windowNumber:native.windowNumber + context:nil + characters:characters + charactersIgnoringModifiers:characters + isARepeat:NO + keyCode:code]; + [native.contentView keyDown:e]; + }; + key(@"\r", 36); + if (state_.count != 2) { + std::cerr << "native Enter activation failed\n"; + finish(5); + return; + } + key(@"\t", 48); + if (d.focused() != d.find("reset")) { + std::cerr << "native Tab focus failed\n"; + finish(6); + return; + } + key(@" ", 49); + if (state_.count != 0) { + std::cerr << "native Space activation failed\n"; + finish(7); + return; + } + click("increment"); + click("add"); + view_->refresh(); + if (!capture.empty()) { + auto png = foco::capture_platform_compositor_png(*window_, 1.f); + if (png) { + std::ofstream f(capture, std::ios::binary); + f.write(reinterpret_cast(png.value().data()), + png.value().size()); + } else { + std::cerr << png.failure().message << "\n"; + finish(2); + return; + } + } + std::cout << "Foco Native Web Cocoa/Metal passed; count=" + << state_.count << " items=" << state_.items << "\n"; + finish(state_.count == 1 && state_.items == 1 ? 0 : 3); + }); + return {}; + } +}; +int main(int argc, char **argv) { + for (int i = 1; i < argc; ++i) { + std::string_view arg = argv[i]; + if (arg == "--smoke") + smoke = true; + else if (arg == "--capture" && i + 1 < argc) + capture = argv[++i]; + } + if (smoke || !capture.empty()) + verification_exit = 10; + const auto result = foco::AppBuilder::Configure() + .WithSkia() + .WithCocoa() + .TryStartWithClassicDesktopLifetime(argc, argv); + if (!result) { + std::cerr << result.failure().message << "\n"; + return 1; + } + return result.value() ? result.value() : verification_exit; +} diff --git a/samples/NativeWeb/measure.py b/samples/NativeWeb/measure.py new file mode 100644 index 000000000..c8a379bdf --- /dev/null +++ b/samples/NativeWeb/measure.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Reproducible sample measurements; intentionally makes no browser speedup claim.""" +import json +import pathlib +import re +import statistics +import subprocess +import sys +import time +repo=pathlib.Path(__file__).resolve().parents[2] +build=pathlib.Path(sys.argv[1]).resolve() +measure=build/'measurements';measure.mkdir(exist_ok=True) +samples=[] +for _ in range(20): + output=subprocess.check_output([build/'native_web_smoke'],text=True) + startup,interaction=re.search(r'startup_us=([0-9.]+) interaction_mean_us=([0-9.]+)',output).groups() + samples.append({'construct_and_first_layout_us':float(startup),'mutation_layout_scene_mean_us':float(interaction)}) +def timed(command): + started=time.perf_counter();result=subprocess.run(['/usr/bin/time','-l',*map(str,command)],capture_output=True,text=True,check=True) + rss=int(re.search(r'(\d+)\s+maximum resident set size',result.stderr)[1]) + return {'wall_seconds':time.perf_counter()-started,'peak_rss_bytes':rss} +compiler=timed([build/'webscene-uic',repo/'samples/NativeWeb/Main.html',measure/'native_web_smoke_ui.hpp']) +clang=subprocess.check_output(['xcrun','--find','clang++'],text=True).strip() +sdk=subprocess.check_output(['xcrun','--show-sdk-path'],text=True).strip() +cpp=timed([clang,'-isysroot',sdk,'-std=c++20','-O2','-I'+str(repo/'src/WebScene.NativeWeb/include'),'-I'+str(repo/'experiments/WebScene.NativeEngine.Probe/native'),'-I'+str(measure),'-c',repo/'samples/NativeWeb/smoke.cpp','-o',measure/'sample.o']) +runtime=timed([build/'native_web_smoke']) +result={'sample':'Main.html + Main.css; native counter, dynamic nodes and Canvas rectangles','runs':samples,'median_construct_and_first_layout_us':statistics.median(s['construct_and_first_layout_us'] for s in samples),'median_mutation_layout_scene_mean_us':statistics.median(s['mutation_layout_scene_mean_us'] for s in samples),'ui_compiler':compiler,'generated_ui_and_app_cpp_compile':cpp,'native_headless_process':runtime,'notes':['Construction timing begins inside main and ends at the first layout/scene; it excludes process launch and GPU presentation.','Each interaction mean covers 100 native mutations plus layout/scene generation.','Filesystem caches are not flushed. The C++ compile measures one application translation unit with Apple Clang, excluding the prebuilt engine and Foco SDK.','RSS is the macOS time(1) process resident high-water mark; GPU memory is not included.']} +app=build/'FocoNativeWeb.app' +if app.exists(): + result['packaged_foco_app']=timed([app/'Contents/MacOS/FocoNativeWeb','--smoke']) + result['app_bytes']=sum(p.stat().st_size for p in app.rglob('*') if p.is_file()) + result['notes'].append('Packaged app wall time includes the deliberate 1.5-second delay before Cocoa input verification; it is not a startup-latency metric.') +(build/'measurements.json').write_text(json.dumps(result,indent=2)+'\n') +print(json.dumps({k:v for k,v in result.items() if k!='runs'},indent=2)) diff --git a/samples/NativeWeb/measurements.json b/samples/NativeWeb/measurements.json new file mode 100644 index 000000000..fa3dc3c34 --- /dev/null +++ b/samples/NativeWeb/measurements.json @@ -0,0 +1,119 @@ +{ + "sample": "Main.html + Main.css; native counter, dynamic nodes and Canvas rectangles", + "runs": [ + { + "construct_and_first_layout_us": 161.0, + "mutation_layout_scene_mean_us": 46.81 + }, + { + "construct_and_first_layout_us": 145.0, + "mutation_layout_scene_mean_us": 46.74 + }, + { + "construct_and_first_layout_us": 122.0, + "mutation_layout_scene_mean_us": 45.12 + }, + { + "construct_and_first_layout_us": 121.0, + "mutation_layout_scene_mean_us": 47.28 + }, + { + "construct_and_first_layout_us": 123.0, + "mutation_layout_scene_mean_us": 45.55 + }, + { + "construct_and_first_layout_us": 153.0, + "mutation_layout_scene_mean_us": 48.87 + }, + { + "construct_and_first_layout_us": 132.0, + "mutation_layout_scene_mean_us": 44.99 + }, + { + "construct_and_first_layout_us": 135.0, + "mutation_layout_scene_mean_us": 48.53 + }, + { + "construct_and_first_layout_us": 128.0, + "mutation_layout_scene_mean_us": 44.89 + }, + { + "construct_and_first_layout_us": 130.0, + "mutation_layout_scene_mean_us": 47.24 + }, + { + "construct_and_first_layout_us": 157.0, + "mutation_layout_scene_mean_us": 45.49 + }, + { + "construct_and_first_layout_us": 135.0, + "mutation_layout_scene_mean_us": 47.87 + }, + { + "construct_and_first_layout_us": 160.0, + "mutation_layout_scene_mean_us": 48.71 + }, + { + "construct_and_first_layout_us": 146.0, + "mutation_layout_scene_mean_us": 49.25 + }, + { + "construct_and_first_layout_us": 146.0, + "mutation_layout_scene_mean_us": 45.44 + }, + { + "construct_and_first_layout_us": 131.0, + "mutation_layout_scene_mean_us": 46.23 + }, + { + "construct_and_first_layout_us": 139.0, + "mutation_layout_scene_mean_us": 48.0 + }, + { + "construct_and_first_layout_us": 131.0, + "mutation_layout_scene_mean_us": 45.34 + }, + { + "construct_and_first_layout_us": 125.0, + "mutation_layout_scene_mean_us": 48.49 + }, + { + "construct_and_first_layout_us": 126.0, + "mutation_layout_scene_mean_us": 46.23 + } + ], + "median_construct_and_first_layout_us": 133.5, + "median_mutation_layout_scene_mean_us": 46.775000000000006, + "ui_compiler": { + "wall_seconds": 0.00572104100137949, + "peak_rss_bytes": 3047424 + }, + "generated_ui_and_app_cpp_compile": { + "wall_seconds": 0.7042770839980221, + "peak_rss_bytes": 196411392 + }, + "native_headless_process": { + "wall_seconds": 0.009145459000137635, + "peak_rss_bytes": 2392064 + }, + "notes": [ + "Construction timing begins inside main and ends at the first layout/scene; it excludes process launch and GPU presentation.", + "Each interaction mean covers 100 native mutations plus layout/scene generation.", + "Filesystem caches are not flushed. The C++ compile measures one application translation unit with Apple Clang, excluding the prebuilt engine and Foco SDK.", + "RSS is the macOS time(1) process resident high-water mark; GPU memory is not included.", + "Packaged app wall time includes the deliberate 1.5-second delay before Cocoa input verification; it is not a startup-latency metric." + ], + "packaged_foco_app": { + "wall_seconds": 1.7252232499995444, + "peak_rss_bytes": 104628224 + }, + "app_bytes": 12460638, + "environment": { + "date": "2026-09-10", + "os": "macOS 26.6.2", + "cpu": "Apple M4", + "webscene_base": "937d467244ee2aae5ad135e418cceeb96f78696e", + "foco_base": "d8c4d169d2b65111c1a99645497191907beb4f99", + "changes": "Working-tree Native Web implementation and accompanying Foco adapter fixes." + } +} diff --git a/samples/NativeWeb/smoke.cpp b/samples/NativeWeb/smoke.cpp new file mode 100644 index 000000000..7c02f792f --- /dev/null +++ b/samples/NativeWeb/smoke.cpp @@ -0,0 +1,95 @@ +#include "app.hpp" +#include "native_web_smoke_ui.hpp" +#include +#include +#include +static void require(bool value, const char *message) { + if (!value) + throw std::runtime_error(message); +} +int main(int argc, char **argv) { + const auto start = std::chrono::steady_clock::now(); + webscene::native_web::document d; + auto view = compiled_ui::build(d); + app_state app; + app.attach(d); + if (argc > 1 && std::string_view(argv[1]) == "--snapshot") { + std::cout << "["; + for (int i = 0; i < 2; ++i) { + int width = i ? 500 : 1000, height = i ? 900 : 700; + d.render(width, height); + if (i) + std::cout << ","; + std::cout << "{\"width\":" << width << ",\"height\":" << height + << ",\"nodes\":["; + bool first = true; + for (auto id : + {"app", "workspace", "counterCard", "chart", "increment", "count"}) { + auto b = d.bounds(d.find(id)); + if (!first) + std::cout << ","; + first = false; + std::cout << "{\"id\":\"" << id << "\",\"x\":" << b.x + << ",\"y\":" << b.y << ",\"width\":" << b.width + << ",\"height\":" << b.height << "}"; + } + std::cout << "]}"; + } + std::cout << "]\n"; + return 0; + } + const auto &wide = d.render(1000, 700); + const auto ready = std::chrono::steady_clock::now(); + auto chart = d.bounds(d.find("chart")); + auto counter = d.bounds(d.find("counterCard")); + require(wide.commands.size() > 10, "scene missing"); + require(!wide.layers.empty(), "canvas missing"); + require(chart.x > counter.x, "wide layout"); + d.render(500, 900); + require(d.bounds(d.find("chart")).y > d.bounds(d.find("counterCard")).y, + "responsive layout"); + d.dispatch(view.named("increment"), "click"); + require(app.count == 1, "native click"); + require(d.text_content(d.find("count")) == "Count: 1", "text update"); + d.focus(d.find("increment")); + d.key("Enter"); + require(app.count == 2, "keyboard activation"); + d.key("Tab"); + require(d.focused() == d.find("reset"), "tab focus"); + d.dispatch(d.find("add"), "click"); + require(d.text_content(d.find("items")).find("Item 1") != std::string::npos, + "insert node"); + auto disposable = d.element(d.find("items"), "button"); + bool called = false; + auto sub = d.on(disposable, "click", [&](auto &) { called = true; }); + sub.dispose(); + d.dispatch(disposable, "click"); + require(!called, "disposed callback"); + d.remove(disposable); + bool invalid = false; + try { + d.set_text(disposable, "stale"); + } catch (const std::invalid_argument &) { + invalid = true; + } + require(invalid, "stale node"); + auto t = std::chrono::steady_clock::now(); + for (int i = 0; i < 100; ++i) { + d.dispatch(d.find("increment"), "click"); + d.render(1000, 700); + } + auto end = std::chrono::steady_clock::now(); + std::cout << "Native Web passed: commands=" << wide.commands.size() + << " startup_us=" + << std::chrono::duration_cast(ready - + start) + .count() + << " interaction_mean_us=" + << std::chrono::duration_cast(end - t) + .count() / + 100.0 + << "\n"; + d.dispose(); + sub.dispose(); + return 0; +} diff --git a/samples/NativeWeb/validation.md b/samples/NativeWeb/validation.md new file mode 100644 index 000000000..82e114be7 --- /dev/null +++ b/samples/NativeWeb/validation.md @@ -0,0 +1,66 @@ +# Native Web validation — 2026-09-10 + +Environment: Apple M4, macOS 26.6.2. WebScene base +`937d467244ee2aae5ad135e418cceeb96f78696e`, Foco base +`d8c4d169d2b65111c1a99645497191907beb4f99`, plus the accompanying working-tree changes. + +## Verified + +- Native smoke: compiled construction, responsive layout, text/class changes, + insertion/removal, event disposal, focus and Canvas scene publication. +- Native contracts: child/descendant selectors, specificity, inline and important + declarations, media rules, forward/reverse focus navigation, hit testing, + bubbling/cancellation, removal during delivery, invalid references, owner-thread + checks, Canvas string-table isolation and document shutdown. +- Eight compiler tests: deterministic generated output and typed values, source + diagnostics, unsupported CSS/selectors, duplicate IDs, scripts/handlers, + missing stylesheets and invalid unitless lengths. +- AddressSanitizer and UndefinedBehaviorSanitizer builds: all three native/compiler + test targets pass. +- Foco focus contract: internal forward/reverse navigation and ordinary host focus + movement when the embedded engine declines handling. +- Real Cocoa input: mouse clicks, Enter activation, Tab to the next native DOM + button, Space activation and subsequent DOM updates; process exit is checked. +- Foco compositor PNG capture includes native DOM text, colors and Canvas bars. +- Application relocation succeeds; a missing bundled resource fails with an + actionable error and nonzero exit. +- Application dependency scan finds only system libraries. No V8/parser entrypoints + or V8/ICU/snapshot deployment assets are present in the application bundle. +- Parsed-vs-compiled geometry: six named elements at two viewports (1000×700 and + 500×900), within 0.01 logical pixels. The parsed reference uses a separate V8-enabled + engine built from the same WebScene checkout; V8 is confined to that test process. + +The broader existing native-engine regression executable stops at +`native-enter-keypress-commit.js:3`, reporting `__submitterWasNull is not defined`. +The same failure and message reproduce with the original, unmodified style-default +implementation restored as a control. This broader suite is therefore not reported +as passing. The extracted style defaults compile in the V8-enabled engine. + +## Measurements + +Full run data and qualifications are in [measurements.json](measurements.json). + +| Measurement | Result | +|---|---:| +| Packaged Foco application | 12,460,638 bytes | +| Native construction + first layout, median of 20 runs | 133.5 µs | +| Mutation + layout/scene generation, median of per-run means | 46.78 µs | +| HTML/CSS compiler process wall time | 5.72 ms | +| Generated UI + app C++ translation-unit compilation | 704 ms | +| Native headless process peak RSS | 2,392,064 bytes | +| Packaged Cocoa application peak RSS | 104,628,224 bytes | + +Construction timing starts inside `main`; it excludes process loading and first GPU +presentation. Each interaction mean covers 100 mutations and scene generations. +Filesystem caches were not flushed. C++ compilation excludes the already-built +engine/Foco SDK. RSS excludes GPU memory. The Cocoa smoke's wall time includes a +deliberate 1.5-second delay and is not used as a startup claim. These are measurements +of this small application, not general native-vs-browser speedup claims. + +## Delivery limits + +This implements the initial Native Web slice described in the sample README, not +full HTML/CSS or browser API coverage. Editable text/IME, DOM accessibility projection, +advanced Canvas/GPU/media native authoring and image/font URL compilation remain +outside its current profile. No hot design, optional-JS integration, new language +projection or typed HTML data binding is claimed. diff --git a/src/WebScene.NativeWeb/CMakeLists.txt b/src/WebScene.NativeWeb/CMakeLists.txt new file mode 100644 index 000000000..3eb9e09a1 --- /dev/null +++ b/src/WebScene.NativeWeb/CMakeLists.txt @@ -0,0 +1,74 @@ +cmake_minimum_required(VERSION 3.24) +project(WebSceneNativeWeb LANGUAGES CXX) +include(CTest) +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +get_filename_component(WEBSCENE_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE) +set(NATIVE "${WEBSCENE_ROOT}/experiments/WebScene.NativeEngine.Probe/native") +add_library(webscene_native_web STATIC src/native_web.cpp "${NATIVE}/webscene_native_dom.cpp") +target_include_directories(webscene_native_web PUBLIC include "${NATIVE}") +find_program(CARGO cargo REQUIRED) +set(PARSER "${CMAKE_CURRENT_BINARY_DIR}/parser/release/${CMAKE_STATIC_LIBRARY_PREFIX}webscene_html_parser${CMAKE_STATIC_LIBRARY_SUFFIX}") +file(GLOB_RECURSE PARSER_SOURCES CONFIGURE_DEPENDS "${NATIVE}/html_parser/src/*.rs") +add_custom_command(OUTPUT "${PARSER}" + COMMAND ${CMAKE_COMMAND} -E env "CARGO_TARGET_DIR=${CMAKE_CURRENT_BINARY_DIR}/parser" ${CARGO} build --manifest-path "${NATIVE}/html_parser/Cargo.toml" --release --locked --features cssparser,selectors + DEPENDS ${PARSER_SOURCES} "${NATIVE}/html_parser/Cargo.toml" "${NATIVE}/html_parser/Cargo.lock" VERBATIM) +add_custom_target(native_web_parser_build DEPENDS "${PARSER}") +add_library(native_web_parser STATIC IMPORTED) +set_target_properties(native_web_parser PROPERTIES IMPORTED_LOCATION "${PARSER}") +add_dependencies(native_web_parser native_web_parser_build) +add_executable(webscene-uic "${WEBSCENE_ROOT}/tooling/webscene-uic/main.cpp" "${NATIVE}/webscene_html_parser.cpp" "${NATIVE}/webscene_css_parser.cpp" "${NATIVE}/webscene_selector_parser.cpp") +target_link_libraries(webscene-uic PRIVATE webscene_native_web native_web_parser) +if(APPLE) + target_link_libraries(webscene-uic PRIVATE iconv) +endif() +function(webscene_compile_html target input) + set(output "${CMAKE_CURRENT_BINARY_DIR}/${target}_ui.hpp") + add_custom_command(OUTPUT "${output}" COMMAND webscene-uic "${input}" "${output}" DEPENDS webscene-uic "${input}" DEPFILE "${output}.d" VERBATIM) + target_sources(${target} PRIVATE "${output}") + target_include_directories(${target} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +endfunction() +add_executable(native_web_smoke "${WEBSCENE_ROOT}/samples/NativeWeb/smoke.cpp") +target_link_libraries(native_web_smoke PRIVATE webscene_native_web) +webscene_compile_html(native_web_smoke "${WEBSCENE_ROOT}/samples/NativeWeb/Main.html") +add_test(NAME native_web_smoke COMMAND native_web_smoke) + +set(FOCO_SOURCE_DIR "" CACHE PATH "Optional FocoUI checkout for the macOS Native Web application") +if(FOCO_SOURCE_DIR) + if(NOT APPLE) + message(FATAL_ERROR "Native Web Foco host currently targets macOS") + endif() + enable_language(OBJCXX) + set(FOCO_ENABLE_MODULES OFF CACHE BOOL "" FORCE) + set(FOCO_BUILD_SAMPLE OFF CACHE BOOL "" FORCE) + set(FOCO_BUILD_DEVTOOLS OFF CACHE BOOL "" FORCE) + set(FOCO_BUILD_CDP OFF CACHE BOOL "" FORCE) + set(FOCO_ENABLE_SKIA_GRAPHITE ON CACHE BOOL "" FORCE) + set(FOCO_SKIA_ROOT "${FOCO_SOURCE_DIR}/.deps/skia" CACHE PATH "") + set(NATIVE_WEB_BUILD_TESTING ${BUILD_TESTING}) + set(BUILD_TESTING OFF) + add_subdirectory("${FOCO_SOURCE_DIR}" foco EXCLUDE_FROM_ALL) + set(BUILD_TESTING ${NATIVE_WEB_BUILD_TESTING}) + set(NATIVE_WEB_RESOURCES "${WEBSCENE_ROOT}/samples/NativeWeb/Resources/about.txt") + set_source_files_properties(${NATIVE_WEB_RESOURCES} PROPERTIES MACOSX_PACKAGE_LOCATION Resources) + add_executable(FocoNativeWeb MACOSX_BUNDLE "${WEBSCENE_ROOT}/samples/NativeWeb/main.mm" ${NATIVE_WEB_RESOURCES}) + target_include_directories(FocoNativeWeb PRIVATE foco "${CMAKE_CURRENT_SOURCE_DIR}/foco") + target_compile_options(FocoNativeWeb PRIVATE -fobjc-arc) + target_link_libraries(FocoNativeWeb PRIVATE webscene_native_web FocoUI::PlatformCocoa) + webscene_compile_html(FocoNativeWeb "${WEBSCENE_ROOT}/samples/NativeWeb/Main.html") + set_target_properties(FocoNativeWeb PROPERTIES MACOSX_BUNDLE_GUI_IDENTIFIER "dev.focoui.nativeweb" MACOSX_BUNDLE_BUNDLE_NAME "Foco Native Web") + add_test(NAME native_web_foco COMMAND $ --smoke) + if(BUILD_TESTING) + add_executable(native_web_foco_focus "${WEBSCENE_ROOT}/tests/NativeWeb/foco_focus.cpp") + target_link_libraries(native_web_foco_focus PRIVATE FocoUI::PlatformCocoa) + add_test(NAME native_web_foco_focus COMMAND native_web_foco_focus) + endif() +endif() +if(BUILD_TESTING) + add_executable(native_web_contracts "${WEBSCENE_ROOT}/tests/NativeWeb/contracts.cpp") + target_link_libraries(native_web_contracts PRIVATE webscene_native_web) + webscene_compile_html(native_web_contracts "${WEBSCENE_ROOT}/tests/NativeWeb/Contracts.html") + add_test(NAME native_web_contracts COMMAND native_web_contracts) + find_package(Python3 COMPONENTS Interpreter REQUIRED) + add_test(NAME native_web_compiler COMMAND ${Python3_EXECUTABLE} "${WEBSCENE_ROOT}/tests/NativeWeb/compiler_tests.py" $) +endif() diff --git a/src/WebScene.NativeWeb/foco/native_web_view.hpp b/src/WebScene.NativeWeb/foco/native_web_view.hpp new file mode 100644 index 000000000..68f8bdb9f --- /dev/null +++ b/src/WebScene.NativeWeb/foco/native_web_view.hpp @@ -0,0 +1,121 @@ +#pragma once +#include +#include +#include +#include + +namespace webscene::foco_host { +// One composition surface hosts the entire native DOM; no per-element Foco +// controls. +class view final : public foco::control { +public: + native_web::document document; + view() { + set_clip_to_bounds(true); + set_focusable(true); + } + void refresh() { + auto b = bounds(); + if (b.width <= 0 || b.height <= 0) + return; + const auto &scene = document.render(b.width, b.height); + if (scene.revision == revision_) + return; + namespace packet = foco::webscene_packet; + static_assert(sizeof(webscene_scene_command) == + sizeof(packet::dom_command)); + static_assert(sizeof(webscene_canvas_command) == + sizeof(packet::canvas_command)); + static_assert(sizeof(webscene_scene_string) == sizeof(packet::string_ref)); + std::vector layers; + for (const auto &l : scene.layers) + layers.push_back({l.node_id, packet::layer_replace, l.command_offset, + l.command_count, l.string_offset, l.string_count, + l.flags, l.x, l.y, l.width, l.height, l.bitmap_width, + l.bitmap_height, l.generation}); + packet::header h{}; + h.magic_value = packet::magic; + h.version_value = packet::version; + h.flags = packet::checkpoint | packet::dom_replacement; + h.revision = scene.revision; + h.viewport_width = scene.width; + h.viewport_height = scene.height; + packet_.assign(sizeof(h), std::byte{}); + const auto append = [&](const auto &data) -> uint32_t { + using T = typename std::decay_t::value_type; + packet_.resize((packet_.size() + alignof(T) - 1) & ~(alignof(T) - 1)); + auto offset = packet_.size(); + packet_.resize(offset + data.size() * sizeof(T)); + if (!data.empty()) + std::memcpy(packet_.data() + offset, data.data(), + data.size() * sizeof(T)); + return static_cast(offset); + }; + h.dom_command_count = scene.commands.size(); + h.dom_command_offset = append(scene.commands); + h.layer_count = layers.size(); + h.layer_offset = append(layers); + h.canvas_command_count = scene.canvas.size(); + h.canvas_command_offset = append(scene.canvas); + h.string_count = scene.strings.size(); + h.string_offset = append(scene.strings); + h.string_byte_count = scene.bytes.size(); + h.string_byte_offset = append(scene.bytes); + h.byte_count = packet_.size(); + std::memcpy(packet_.data(), &h, sizeof(h)); + revision_ = scene.revision; + invalidate_render(); + } + std::optional + composition_command_stream() const noexcept override { + if (packet_.empty()) + return std::nullopt; + return foco::composition_command_stream_view{ + packet_, revision_, + static_cast(foco::command_stream_format::webscene_scene_v1), + static_cast(std::max(1.f, bounds().width)), + static_cast(std::max(1.f, bounds().height))}; + } + foco::size measure_override(foco::size available) override { + return {std::isfinite(available.width) ? available.width : 1000.f, + std::isfinite(available.height) ? available.height : 700.f}; + } + void arrange_override(foco::size size) override { + document.render(std::max(1.f, size.width), std::max(1.f, size.height)); + refresh(); + } + void pointer_event_received(foco::pointer_event &e) override { + auto type = e.kind == foco::pointer_event_kind::pressed ? "pointerdown" + : e.kind == foco::pointer_event_kind::released ? "pointerup" + : "pointermove"; + document.pointer(type, e.position.x - bounds().x, + e.position.y - bounds().y); + refresh(); + e.handled = true; + } + bool try_move_focus_within(bool reverse) override { + document.key("Tab", reverse); + refresh(); + return document.focused() != 0; + } + void key_event_received(foco::key_event &e) override { + std::string_view key = e.value == foco::key::tab ? "Tab" + : e.value == foco::key::enter ? "Enter" + : e.value == foco::key::space ? " " + : ""; + if (!key.empty()) { + document.key(key, + foco::has_modifier(e.modifiers, foco::key_modifiers::shift)); + refresh(); + e.handled = true; + } + } + std::string_view type_name() const noexcept override { + return "NativeWebView"; + } + +private: + std::vector packet_; + uint64_t revision_{}; +}; +} // namespace webscene::foco_host diff --git a/src/WebScene.NativeWeb/include/webscene/native_web.hpp b/src/WebScene.NativeWeb/include/webscene/native_web.hpp new file mode 100644 index 000000000..1f8d901a7 --- /dev/null +++ b/src/WebScene.NativeWeb/include/webscene/native_web.hpp @@ -0,0 +1,166 @@ +#pragma once +#include "webscene_native_dom.h" +#include +#include +#include + +namespace webscene::native_web { +using node_id = uint32_t; +using length = webscene_native::css_length; +using length_unit = webscene_native::length_unit; +using display_mode = webscene_native::display_mode; +using flex_direction = webscene_native::flex_direction; +using align_mode = webscene_native::align_mode; +using justify_mode = webscene_native::justify_mode; +using position_mode = webscene_native::position_mode; +// Supported compiled-style writer. Generated code never accesses engine fields. +// A writer is borrowed only for the duration of declaration application. +class style { + friend class document; + webscene_native::node_style &value_; + explicit style(webscene_native::node_style &value) : value_(value) {} + +public: + void set_width(length value) { value_.width = value; } + void set_height(length value) { value_.height = value; } + void set_min_width(length value) { value_.min_width = value; } + void set_min_height(length value) { value_.min_height = value; } + void set_max_width(length value) { value_.max_width = value; } + void set_max_height(length value) { value_.max_height = value; } + void set_left(length value) { value_.left = value; } + void set_top(length value) { value_.top = value; } + void set_right(length value) { value_.right = value; } + void set_bottom(length value) { value_.bottom = value; } + void set_padding_left(length value) { value_.padding_left = value; } + void set_padding_top(length value) { value_.padding_top = value; } + void set_padding_right(length value) { value_.padding_right = value; } + void set_padding_bottom(length value) { value_.padding_bottom = value; } + void set_margin_left(length value) { value_.margin_left = value; } + void set_margin_top(length value) { value_.margin_top = value; } + void set_margin_right(length value) { value_.margin_right = value; } + void set_margin_bottom(length value) { value_.margin_bottom = value; } + void set_row_gap(length value) { value_.row_gap = value; } + void set_column_gap(length value) { value_.column_gap = value; } + void set_flex_basis(length value) { value_.flex_basis = value; } + void set_border_top_left_radius(length value) { + value_.border_top_left_radius = value; + } + void set_border_top_right_radius(length value) { + value_.border_top_right_radius = value; + } + void set_border_bottom_left_radius(length value) { + value_.border_bottom_left_radius = value; + } + void set_border_bottom_right_radius(length value) { + value_.border_bottom_right_radius = value; + } + void set_font_size(float value) { value_.font_size = value; } + void set_flex_grow(float value) { value_.flex_grow = value; } + void set_flex_shrink(float value) { value_.flex_shrink = value; } + void set_opacity(float value) { value_.opacity = value; } + void set_border_box(bool value) { value_.border_box = value; } + void set_margin_left_auto(bool value) { value_.margin_left_auto = value; } + void set_margin_top_auto(bool value) { value_.margin_top_auto = value; } + void set_margin_right_auto(bool value) { value_.margin_right_auto = value; } + void set_margin_bottom_auto(bool value) { value_.margin_bottom_auto = value; } + void set_background_rgba(uint32_t value) { value_.background_rgba = value; } + void set_foreground_rgba(uint32_t value) { value_.foreground_rgba = value; } + void set_font_weight(int32_t value) { value_.font_weight = value; } + void set_display(display_mode value) { value_.display = value; } + void set_direction(flex_direction value) { value_.direction = value; } + void set_align_items(align_mode value) { value_.align_items = value; } + void set_justify_content(justify_mode value) { + value_.justify_content = value; + } + void set_position(position_mode value) { value_.position = value; } +}; +struct selector_part { + std::string tag, id; + std::vector classes; + bool focus{}, hover{}; + char relation{}; // relationship to the preceding (ancestor) part: ' ' or '>' +}; +struct selector { + std::vector parts; + uint32_t specificity{}; +}; +struct declaration { + bool important{}; + void (*apply)(style &){}; +}; +struct rule { + selector match; + std::vector declarations; + float min_width{}, max_width{1e9f}; + node_id inline_target{}; +}; +struct event { + std::string type; + node_id target{}, current_target{}; + bool propagation_stopped{}, default_prevented{}; + void stop_propagation() { propagation_stopped = true; } + void prevent_default() { default_prevented = true; } +}; +struct scene { + std::vector commands; + std::vector strings; + std::vector bytes; + std::vector layers; + std::vector canvas; + float width{}, height{}; + uint64_t revision{}; +}; +struct document_state; +class subscription { +public: + subscription() = default; + subscription(subscription &&) noexcept; + subscription &operator=(subscription &&) noexcept; + subscription(const subscription &) = delete; + subscription &operator=(const subscription &) = delete; + ~subscription(); + void dispose() noexcept; + +private: + friend class document; + subscription(std::weak_ptr, uint64_t); + std::weak_ptr state_; + uint64_t id_{}; +}; +// A document is confined to its creating thread. Hosts dispatch work to that +// thread. IDs are local to this document and never recycled during its +// lifetime. +class document { +public: + explicit document(webscene_text_measure_callback = nullptr, void * = nullptr); + ~document(); + document(const document &) = delete; + document &operator=(const document &) = delete; + node_id body() const; + node_id element(node_id parent, std::string tag); + node_id text(node_id parent, std::string value); + void set_text(node_id, std::string); + void attribute(node_id, std::string name, std::string value); + void remove(node_id); + node_id find(std::string_view id) const; + void add_rule(rule); + subscription on(node_id, std::string type, std::function); + // Returns false when a listener prevents the default action or disposes the + // document. + bool dispatch(node_id, std::string type); + void pointer(std::string type, float x, float y); + void focus(node_id); + void key(std::string_view key, bool shift = false); + node_id focused() const; + void clear_canvas(node_id); + void fill_rect(node_id, float x, float y, float width, float height, + uint32_t rgba); + const scene &render(float width, float height); + webscene_native::layout_rect bounds(node_id) const; + std::string text_content(node_id) const; + void dispose(); + +private: + std::shared_ptr state_; +}; +} // namespace webscene::native_web diff --git a/src/WebScene.NativeWeb/src/native_web.cpp b/src/WebScene.NativeWeb/src/native_web.cpp new file mode 100644 index 000000000..43fccf583 --- /dev/null +++ b/src/WebScene.NativeWeb/src/native_web.cpp @@ -0,0 +1,459 @@ +#include "webscene/native_web.hpp" +#include "webscene_native_style_defaults.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webscene::native_web { +using namespace webscene_native; +struct listener { + node_id node; + std::string type; + std::function callback; +}; +struct document_state { + native_document dom; + std::thread::id owner{std::this_thread::get_id()}; + bool alive{true}; + node_id focus{}, hover{}, pressed{}; + uint64_t next_listener{1}; + std::mutex listener_mutex; + std::map listeners; + std::vector rules; + scene output; + document_state(webscene_text_measure_callback cb, void *data) + : dom(cb, data) {} + void check() const { + if (owner != std::this_thread::get_id()) + throw std::logic_error("document accessed off its owner thread"); + if (!alive) + throw std::logic_error("document is disposed"); + } + dom_node &node(node_id id) { + check(); + auto *n = dom.find_by_native_id(id); + if (!n) + throw std::invalid_argument("invalid document node"); + return *n; + } + bool connected(const dom_node &n) const { + for (auto *p = &n; p; p = p->parent) + if (p == &dom.body()) + return true; + return false; + } +}; +subscription::subscription(std::weak_ptr s, uint64_t id) + : state_(s), id_(id) {} +subscription::subscription(subscription &&other) noexcept + : state_(std::move(other.state_)), id_(std::exchange(other.id_, 0)) {} +subscription &subscription::operator=(subscription &&other) noexcept { + if (this != &other) { + dispose(); + state_ = std::move(other.state_); + id_ = std::exchange(other.id_, 0); + } + return *this; +} +subscription::~subscription() { dispose(); } +void subscription::dispose() noexcept { + if (auto s = state_.lock()) { + std::lock_guard lock(s->listener_mutex); + s->listeners.erase(id_); + } + id_ = 0; +} +document::document(webscene_text_measure_callback cb, void *data) + : state_(std::make_shared(cb, data)) {} +document::~document() { state_->alive = false; } +void document::dispose() { + state_->check(); + state_->alive = false; + std::lock_guard lock(state_->listener_mutex); + state_->listeners.clear(); + state_->rules.clear(); + state_->dom.clear(); +} +node_id document::body() const { + state_->check(); + return state_->dom.body().id; +} +node_id document::element(node_id parent, std::string tag) { + auto &p = state_->node(parent); + auto &n = state_->dom.create_element(std::move(tag)); + state_->dom.append_child(p, n); + return n.id; +} +node_id document::text(node_id parent, std::string value) { + const auto id = element(parent, "#text"); + state_->node(id).text_content = std::move(value); + return id; +} +void document::set_text(node_id id, std::string value) { + auto &n = state_->node(id); + if (n.tag == "#text") + n.text_content = std::move(value); + else { + auto children = n.children; + for (auto *child : children) + remove(child->id); + text(id, std::move(value)); + } + state_->dom.mark_dirty(); +} +void document::attribute(node_id id, std::string name, std::string value) { + auto &n = state_->node(id); + if (name == "style" || name.starts_with("on")) + throw std::invalid_argument( + "use compiled styles and native event subscriptions"); + if (name == "id") + n.id_attribute = value; + if (name == "class") + n.class_name = value; + n.attributes[std::move(name)] = std::move(value); + state_->dom.mark_dirty(); +} +void document::remove(node_id id) { + auto &n = state_->node(id); + if (id == body()) + throw std::invalid_argument("cannot remove document body"); + std::vector removed; + const auto collect = [&](auto &&self, dom_node &node) -> void { + removed.push_back(node.id); + for (auto *c : node.children) + self(self, *c); + }; + collect(collect, n); + { + std::lock_guard lock(state_->listener_mutex); + std::erase_if(state_->listeners, [&](const auto &v) { + return std::ranges::find(removed, v.second.node) != removed.end(); + }); + } + if (std::ranges::find(removed, state_->focus) != removed.end()) + state_->focus = 0; + if (std::ranges::find(removed, state_->hover) != removed.end()) + state_->hover = 0; + if (std::ranges::find(removed, state_->pressed) != removed.end()) + state_->pressed = 0; + std::erase_if(state_->rules, [&](const auto &r) { + return r.inline_target && + std::ranges::find(removed, r.inline_target) != removed.end(); + }); + state_->dom.parser_remove_from_parent(n); + state_->dom.erase_detached_subtree(n); + state_->dom.mark_dirty(); +} +node_id document::find(std::string_view id) const { + state_->check(); + auto *n = state_->dom.find_by_id(std::string(id)); + return n ? n->id : 0; +} +void document::add_rule(rule r) { + state_->check(); + state_->rules.push_back(std::move(r)); + state_->dom.mark_dirty(); +} +subscription document::on(node_id node, std::string type, + std::function cb) { + state_->node(node); + std::lock_guard lock(state_->listener_mutex); + auto id = state_->next_listener++; + state_->listeners.emplace(id, listener{node, std::move(type), std::move(cb)}); + return subscription(state_, id); +} +bool document::dispatch(node_id target, std::string type) { + auto &n = state_->node(target); + std::vector path; + for (auto *p = &n; p; p = p->parent) + path.push_back(p->id); + event e{std::move(type), target}; + for (auto id : path) { + if (!state_->alive) + return false; + if (!state_->dom.find_by_native_id(id)) + continue; + e.current_target = id; + std::vector listeners; + { + std::lock_guard lock(state_->listener_mutex); + for (const auto &[token, l] : state_->listeners) + if (l.node == id && l.type == e.type) + listeners.push_back(token); + } + for (auto token : listeners) { + std::function cb; + { + std::lock_guard lock(state_->listener_mutex); + if (auto it = state_->listeners.find(token); + it != state_->listeners.end()) + cb = it->second.callback; + } + if (cb) + cb(e); + if (!state_->alive) + return false; + } + if (e.propagation_stopped) + break; + } + return !e.default_prevented; +} + +static bool focusable(const dom_node &n) { + return (n.tag == "button" || n.attributes.contains("tabindex")) && + !n.attributes.contains("disabled") && + n.style.display != display_mode::none; +} +void document::focus(node_id id) { + state_->check(); + if (id && !focusable(state_->node(id))) + return; + auto old = state_->focus; + if (old == id) + return; + state_->focus = id; + state_->dom.mark_dirty(); + if (old && state_->dom.find_by_native_id(old)) + dispatch(old, "blur"); + if (state_->alive && id && state_->dom.find_by_native_id(id)) + dispatch(id, "focus"); +} +node_id document::focused() const { + state_->check(); + return state_->focus; +} +void document::pointer(std::string type, float x, float y) { + state_->check(); + auto *n = state_->dom.hit_test(state_->dom.body(), x, y); + auto id = n ? n->id : 0; + if (state_->hover != id) { + state_->hover = id; + state_->dom.mark_dirty(); + } + if (type == "pointerdown" || type == "pointerup") { + for (auto *p = n; p; p = p->parent) + if (p->tag == "button" && p->attributes.contains("disabled")) { + state_->pressed = 0; + return; + } + } + if (type == "pointerdown") + state_->pressed = id; + const bool default_allowed = !id || dispatch(id, type); + if (!state_->alive) + return; + if (type == "pointerdown" && default_allowed) { + for (auto *p = state_->dom.find_by_native_id(id); p; p = p->parent) { + if (focusable(*p)) { + focus(p->id); + break; + } + } + } + if (type == "pointerup") { + const auto pressed = std::exchange(state_->pressed, 0); + if (id && id == pressed && state_->dom.find_by_native_id(id)) + dispatch(id, "click"); + } +} +void document::key(std::string_view key, bool shift) { + state_->check(); + if (key == "Tab") { + std::vector nodes; + const auto visit = [&](auto &&self, dom_node &n) -> void { + if (n.style.display == display_mode::none) + return; + if (focusable(n) && (!n.attributes.contains("tabindex") || + n.attributes.at("tabindex") != "-1")) + nodes.push_back(n.id); + for (auto *c : n.children) + self(self, *c); + }; + visit(visit, state_->dom.body()); + if (nodes.empty()) + return; + auto it = std::ranges::find(nodes, state_->focus); + auto index = it == nodes.end() ? (shift ? 0 : -1) + : static_cast(it - nodes.begin()); + focus(nodes[(index + (shift ? -1 : 1) + nodes.size()) % nodes.size()]); + } else if ((key == "Enter" || key == " ") && state_->focus) { + if (state_->node(state_->focus).tag == "button" && + !state_->node(state_->focus).attributes.contains("disabled")) + dispatch(state_->focus, "click"); + } +} +void document::clear_canvas(node_id id) { + auto &n = state_->node(id); + if (n.tag != "canvas") + throw std::invalid_argument("not a canvas"); + auto &c = n.mutable_canvas(); + c.commands.clear(); + c.strings.clear(); + c.string_indices.clear(); + ++c.generation; + state_->dom.mark_dirty(); +} +void document::fill_rect(node_id id, float x, float y, float w, float h, + uint32_t rgba) { + auto &n = state_->node(id); + if (n.tag != "canvas") + throw std::invalid_argument("not a canvas"); + webscene_canvas_command c{}; + c.kind = 22; + c.data.values[0] = x; + c.data.values[1] = y; + c.data.values[2] = w; + c.data.values[3] = h; + auto &canvas = n.mutable_canvas(); + char color[10]; + std::snprintf(color, sizeof(color), "#%08x", rgba); + webscene_canvas_command paint{}; + paint.kind = 40; + paint.resource_id = static_cast(canvas.strings.size()); + canvas.strings.emplace_back(color); + canvas.commands.push_back(paint); + canvas.commands.push_back(c); + ++canvas.generation; + state_->dom.mark_dirty(); +} +static bool class_has(const std::string &list, const std::string &name) { + size_t i = 0; + while (i < list.size()) { + auto b = list.find_first_not_of(" \t\r\n\f", i); + if (b == std::string::npos) + return false; + auto e = list.find_first_of(" \t\r\n\f", b); + if (list.substr(b, e - b) == name) + return true; + if (e == std::string::npos) + return false; + i = e; + } + return false; +} +static bool matches_part(const dom_node &n, const selector_part &p, + document_state &s) { + if (!p.tag.empty() && p.tag != "*" && n.tag != p.tag) + return false; + if (!p.id.empty() && + (!n.attributes.contains("id") || n.attributes.at("id") != p.id)) + return false; + for (const auto &c : p.classes) + if (!n.attributes.contains("class") || + !class_has(n.attributes.at("class"), c)) + return false; + if (p.focus && n.id != s.focus) + return false; + if (p.hover) { + auto *h = s.dom.find_by_native_id(s.hover); + bool found = false; + for (; h; h = h->parent) + if (h->id == n.id) + found = true; + if (!found) + return false; + } + return n.tag != "#text"; +} +static bool matches(const dom_node *n, const selector &sel, size_t i, + document_state &s) { + if (!n || !matches_part(*n, sel.parts[i], s)) + return false; + if (!i) + return true; + if (sel.parts[i].relation == '>') + return matches(n->parent, sel, i - 1, s); + for (auto *p = n->parent; p; p = p->parent) + if (matches(p, sel, i - 1, s)) + return true; + return false; +} +const scene &document::render(float width, float height) { + state_->check(); + if (!std::isfinite(width) || !std::isfinite(height) || width <= 0 || + height <= 0) + throw std::invalid_argument("invalid viewport"); + auto &s = *state_; + auto &out = s.output; + if (!s.dom.dirty() && out.width == width && out.height == height) + return out; + const auto cascade = [&](auto &&self, dom_node &n) -> void { + n.style = node_style{}; + n.style.display = native_default_display_for_node(n); + struct candidate { + bool important; + uint64_t specificity; + size_t order; + void (*apply)(style &); + }; + std::vector declarations; + size_t order = 0; + for (const auto &r : s.rules) { + bool match = width >= r.min_width && width <= r.max_width && + (r.inline_target ? r.inline_target == n.id + : !r.match.parts.empty() && + matches(&n, r.match, + r.match.parts.size() - 1, s)); + for (const auto &d : r.declarations) { + if (match) + declarations.push_back( + {d.important, + r.inline_target ? (1ull << 32) : r.match.specificity, order, + d.apply}); + ++order; + } + } + std::ranges::sort(declarations, {}, [](const auto &d) { + return std::tuple(d.important, d.specificity, d.order); + }); + style writer(n.style); + for (const auto &d : declarations) + d.apply(writer); + for (auto *c : n.children) + self(self, *c); + }; + cascade(cascade, s.dom.body()); + s.dom.mark_dirty(); + s.dom.layout(width, height); + out.commands.clear(); + out.strings.clear(); + out.bytes.clear(); + out.layers.clear(); + out.canvas.clear(); + s.dom.build_scene(out.commands, out.strings, out.bytes); + std::vector canvas_strings; + std::vector canvas_bytes; + s.dom.build_canvas_display_lists(out.layers, out.canvas, canvas_strings, + canvas_bytes); + for (auto &layer : out.layers) + layer.string_offset += static_cast(out.strings.size()); + for (auto ref : canvas_strings) { + ref.byte_offset += static_cast(out.bytes.size()); + out.strings.push_back(ref); + } + out.bytes.insert(out.bytes.end(), canvas_bytes.begin(), canvas_bytes.end()); + out.width = width; + out.height = height; + ++out.revision; + return out; +} +layout_rect document::bounds(node_id id) const { + return state_->node(id).layout; +} +std::string document::text_content(node_id id) const { + std::string result; + const auto visit = [&](auto &&self, dom_node &n) -> void { + result += n.text_content; + for (auto *c : n.children) + self(self, *c); + }; + visit(visit, state_->node(id)); + return result; +} +} // namespace webscene::native_web diff --git a/tests/NativeWeb/Contracts.html b/tests/NativeWeb/Contracts.html new file mode 100644 index 000000000..0f6664df3 --- /dev/null +++ b/tests/NativeWeb/Contracts.html @@ -0,0 +1,11 @@ +
diff --git a/tests/NativeWeb/compiler_tests.py b/tests/NativeWeb/compiler_tests.py new file mode 100644 index 000000000..e6670594e --- /dev/null +++ b/tests/NativeWeb/compiler_tests.py @@ -0,0 +1,33 @@ +import pathlib +import subprocess +import sys +import tempfile +import unittest +UIC=pathlib.Path(sys.argv.pop(1)).resolve() +class CompilerTests(unittest.TestCase): + def compile(self,body,css=''): + folder=tempfile.TemporaryDirectory();self.addCleanup(folder.cleanup) + root=pathlib.Path(folder.name);source=root/'view.html';output=root/'view.hpp' + source.write_text('\n'+body+'') + result=subprocess.run([UIC,source,output],capture_output=True,text=True) + return result,output + def test_compiled_values_and_determinism(self): + result,out=self.compile('','#go { width: 20px; color: #123456; }') + self.assertEqual(result.returncode,0,result.stderr);text=out.read_text();self.assertIn('Hello & goodbye',text);self.assertIn('20.0f',text) + self.assertNotIn('webscene_native::',text);self.assertNotIn('s.width',text);self.assertNotIn('parse_',text);self.assertNotIn('20px',text) + source=out.with_name('view.html');subprocess.run([UIC,source,out],check=True);self.assertEqual(text,out.read_text()) + def test_unsupported_property_has_source_diagnostic(self): + result,out=self.compile('
','div { filter: blur(2px); }');self.assertNotEqual(result.returncode,0);self.assertIn(':2:1: error:',result.stderr);self.assertIn('filter',result.stderr);self.assertFalse(out.exists()) + def test_scripts_rejected(self): + result,_=self.compile('');self.assertNotEqual(result.returncode,0) + def test_js_attributes_rejected(self): + result,_=self.compile('');self.assertNotEqual(result.returncode,0) + def test_duplicate_ids_rejected(self): + result,_=self.compile('
');self.assertNotEqual(result.returncode,0);self.assertIn('duplicate id',result.stderr) + def test_unknown_selector_rejected(self): + result,_=self.compile('
','div:has(button) { width: 1px; }');self.assertNotEqual(result.returncode,0) + def test_missing_resource_rejected(self): + result,_=self.compile('');self.assertNotEqual(result.returncode,0) + def test_nonzero_unitless_length_rejected(self): + result,_=self.compile('
','div { width: 10; }');self.assertNotEqual(result.returncode,0) +if __name__=='__main__':unittest.main() diff --git a/tests/NativeWeb/contracts.cpp b/tests/NativeWeb/contracts.cpp new file mode 100644 index 000000000..712cd0b64 --- /dev/null +++ b/tests/NativeWeb/contracts.cpp @@ -0,0 +1,106 @@ +#include "native_web_contracts_ui.hpp" +#include +#include +#include +#include +static void check(bool value, const char *label) { + if (!value) + throw std::runtime_error(label); +} +int main() { + using namespace webscene::native_web; + document d; + auto refs = compiled_ui::build(d); + auto target = refs.named("target"), other = refs.named("other"); + d.render(800, 600); + check(d.bounds(target).width == 60, "important beats inline"); + check(d.bounds(other).width == 30, "child selector"); + d.attribute(target, "class", ""); + d.render(800, 600); + check(d.bounds(target).width == 70, "inline wins ordinary selector"); + d.focus(target); + d.render(800, 600); + check(d.bounds(target).height == 30, "focus selector"); + d.render(350, 600); + check(d.bounds(target).height == 40, "responsive specificity"); + d.key("Tab"); + check(d.focused() == other, "forward tab"); + d.key("Tab", true); + check(d.focused() == target, "reverse tab"); + d.focus(0); + auto prevent = + d.on(target, "pointerdown", [](event &e) { e.prevent_default(); }); + auto target_bounds = d.bounds(target); + d.pointer("pointerdown", target_bounds.x + 2, target_bounds.y + 2); + check(d.focused() == 0, "prevent default focus"); + prevent.dispose(); + int calls = 0; + auto a = d.on(target, "click", [&](event &) { ++calls; }); + auto bounds = d.bounds(target); + d.pointer("pointerdown", bounds.x + 2, bounds.y + 2); + d.pointer("pointerup", bounds.x + 2, bounds.y + 2); + check(calls == 1, "hit testing / bubble click"); + bool parent_called = false; + auto parent = d.on(d.body(), "click", [&](event &) { parent_called = true; }); + auto stop = d.on(target, "click", [](event &e) { e.stop_propagation(); }); + d.dispatch(target, "click"); + check(!parent_called, "stop propagation"); + auto deleting = d.on(other, "click", [&](event &) { d.remove(other); }); + d.dispatch(other, "click"); + bool stale = false; + try { + d.bounds(other); + } catch (const std::invalid_argument &) { + stale = true; + } + check(stale, "remove during callback"); + std::atomic wrong_thread = false; + std::thread worker([&] { + try { + d.element(d.body(), "div"); + } catch (const std::logic_error &) { + wrong_thread = true; + } + }); + worker.join(); + check(wrong_thread, "thread confinement"); + auto canvas = refs.named("canvas"); + d.fill_rect(canvas, 1, 2, 3, 4, 0x123456ff); + const auto &scene = d.render(350, 600); + check(scene.layers.size() == 1, "canvas layer"); + check(scene.canvas.size() == 2 && scene.canvas[0].kind == 40 && + scene.canvas[1].kind == 22, + "native canvas protocol"); + bool found_text = false; + for (const auto &command : scene.commands) + if (command.kind == 3) { + check(command.flags < scene.strings.size(), "DOM string index"); + auto ref = scene.strings[command.flags]; + std::string text(scene.bytes.data() + ref.byte_offset, ref.byte_length); + if (text.ends_with("\tGo")) + found_text = true; + } + check(found_text, "canvas preserves DOM text table"); + auto layer = scene.layers[0]; + auto color = scene.strings[layer.string_offset]; + check(std::string(scene.bytes.data() + color.byte_offset, + color.byte_length) == "#123456ff", + "canvas color table offset"); + d.clear_canvas(canvas); + check(d.render(350, 600).layers.empty(), "canvas clearing"); + a.dispose(); + int before = calls; + d.dispatch(target, "click"); + check(calls == before, "unsubscribe"); + auto shutdown = d.on(target, "close", [&](event &) { d.dispose(); }); + d.dispatch(target, "close"); + shutdown.dispose(); + bool disposed = false; + try { + d.render(100, 100); + } catch (const std::logic_error &) { + disposed = true; + } + check(disposed, "disposed document"); + std::cout << "Native Web contracts passed\n"; +} diff --git a/tests/NativeWeb/foco_focus.cpp b/tests/NativeWeb/foco_focus.cpp new file mode 100644 index 000000000..bc1eda0fb --- /dev/null +++ b/tests/NativeWeb/foco_focus.cpp @@ -0,0 +1,42 @@ +#include +#include +#include +class document_surface final : public foco::control { +public: + bool accept{true}, reverse{}; + int moves{}; + document_surface() { set_focusable(true); } + bool try_move_focus_within(bool backwards) override { + ++moves; + reverse = backwards; + return accept; + } +}; +static void check(bool value) { + if (!value) + throw std::runtime_error("embedded focus contract"); +} +int main() { + auto root = foco::make_ref(); + auto first = foco::make_ref(); + auto next = foco::make_ref(); + root->add_child(first); + root->add_child(next); + foco::raw_input_queue queue; + foco::input_router router(*root, queue); + check(router.focus().focus(*first)); + check(router.route_key({.value = foco::key::tab})); + check(first->moves == 1 && !first->reverse && + router.focus().focused() == first.get()); + check(router.route_key( + {.value = foco::key::tab, .modifiers = foco::key_modifiers::shift})); + check(first->moves == 2 && first->reverse && + router.focus().focused() == first.get()); + first->accept = false; + check(router.route_key({.value = foco::key::tab})); + check(router.focus().focused() == next.get()); + check(router.route_key( + {.value = foco::key::tab, .modifiers = foco::key_modifiers::shift})); + check(router.focus().focused() == first.get()); + std::cout << "Foco embedded focus navigation passed\n"; +} diff --git a/tests/NativeWeb/parsed_reference.py b/tests/NativeWeb/parsed_reference.py new file mode 100644 index 000000000..c80181890 --- /dev/null +++ b/tests/NativeWeb/parsed_reference.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Optional comparison against an existing V8-enabled WebScene engine (test process only).""" +import ctypes as c +import json +import pathlib +import sys +import time +class Input(c.Structure): + _fields_=[('kind',c.c_uint32),('flags',c.c_uint32),('sequence',c.c_uint64),('x',c.c_double),('y',c.c_double),('dx',c.c_double),('dy',c.c_double)] +class Request(c.Structure): + _fields_=[('size',c.c_uint32),('version',c.c_uint32),('source',c.c_char_p),('length',c.c_size_t),('name',c.c_char_p),('name_length',c.c_size_t),('flags',c.c_uint32),('reserved',c.c_uint32)] +class Value(c.Structure): + _fields_=[('kind',c.c_uint32),('flags',c.c_uint32),('offset',c.c_uint32),('length',c.c_uint32),('payload',c.c_uint64)] +class Result(c.Structure): + _fields_=[('size',c.c_uint32),('version',c.c_uint32),('status',c.c_uint32),('flags',c.c_uint32),('operation',c.c_uint64),('values',c.POINTER(Value)),('edges',c.c_void_p),('bytes',c.c_void_p),('errors',c.c_void_p),('lease',c.c_uint64),('count',c.c_uint32),('edge_count',c.c_uint32),('byte_count',c.c_uint32),('error_count',c.c_uint32),('root',c.c_uint32),('capacity',c.c_uint32),('reserved0',c.c_uint32),('reserved1',c.c_uint32)] +lib=c.CDLL(sys.argv[1]); engine_type=c.c_void_p +lib.webscene_engine_create.argtypes=[c.c_uint32];lib.webscene_engine_create.restype=engine_type +lib.webscene_engine_destroy.argtypes=[engine_type] +lib.webscene_engine_enqueue.argtypes=[engine_type,c.POINTER(Input)] +lib.webscene_engine_begin_evaluate_v3.argtypes=[engine_type,c.POINTER(Request),c.c_void_p,c.c_void_p];lib.webscene_engine_begin_evaluate_v3.restype=c.c_uint64 +lib.webscene_engine_take_invoke_result_v3.argtypes=[engine_type,c.c_uint64];lib.webscene_engine_take_invoke_result_v3.restype=c.POINTER(Result) +lib.webscene_interop_result_release_v3.argtypes=[c.POINTER(Result),c.c_uint64] +callback=c.CFUNCTYPE(None,c.c_void_p,c.c_uint64)(lambda context,operation:None) +engine=lib.webscene_engine_create(0) +def evaluate(source): + data=source.encode();r=Request(c.sizeof(Request),3,data,len(data),None,0,0,0) + operation=lib.webscene_engine_begin_evaluate_v3(engine,c.byref(r),callback,None) + if not operation:raise RuntimeError('evaluation rejected') + deadline=time.monotonic()+15 + while time.monotonic()')[1].split('')[0] + evaluate('document.body.innerHTML='+json.dumps(body)+';var style=document.createElement("style");style.textContent='+json.dumps(css)+';document.head.appendChild(style);"ready"') + results=[] + for width,height in [(1000,700),(500,900)]: + ev=Input(6,0,1,width,height,1,0);lib.webscene_engine_enqueue(engine,c.byref(ev)) + data=evaluate('JSON.stringify(["app","workspace","counterCard","chart","increment","count"].map(id=>{const e=document.getElementById(id),r=e.getBoundingClientRect();return {id,x:r.x,y:r.y,width:r.width,height:r.height};}))') + results.append({'width':width,'height':height,'nodes':json.loads(data)}) + print(json.dumps(results,indent=2)) +finally:lib.webscene_engine_destroy(engine) diff --git a/tooling/webscene-uic/main.cpp b/tooling/webscene-uic/main.cpp new file mode 100644 index 000000000..470d30175 --- /dev/null +++ b/tooling/webscene-uic/main.cpp @@ -0,0 +1,500 @@ +#include "webscene/native_web.hpp" +#include "webscene_css_parser.h" +#include "webscene_html_parser.h" +#include "webscene_selector_parser.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace webscene_native; +namespace fs = std::filesystem; +static std::string read(const fs::path &path) { + std::ifstream f(path); + if (!f) + throw std::runtime_error("cannot read " + path.string()); + return {std::istreambuf_iterator(f), {}}; +} +static std::string quote(std::string_view value) { + std::ostringstream out; + out << '"'; + for (unsigned char c : value) { + if (c == '"' || c == '\\') + out << '\\' << c; + else if (c >= 32 && c < 127) + out << c; + else + out << '\\' << std::oct << std::setw(3) << std::setfill('0') + << unsigned(c) << std::dec; + } + out << '"'; + return out.str(); +} +static std::string number(float value) { + std::ostringstream out; + out << std::setprecision(9) << value; + auto s = out.str(); + if (s.find_first_of(".eE") == s.npos) + s += ".0"; + return s + "f"; +} +static std::string trim(std::string value) { + auto b = value.find_first_not_of(" \t\r\n\f"); + if (b == value.npos) + return {}; + return value.substr(b, value.find_last_not_of(" \t\r\n\f") - b + 1); +} +static std::string length(const std::string &value) { + static const std::regex valid( + R"(^(-?[0-9]+(\.[0-9]+)?(px|%|em|rem|vw|vh)?|auto)$)"); + if (!std::regex_match(value, valid) || + (value != "auto" && value.back() >= '0' && value.back() <= '9' && + std::stof(value) != 0)) + throw std::runtime_error("unsupported length: " + value); + auto v = native_document::parse_length(value); + return "{" + number(v.value) + + ", static_cast(" + + std::to_string(int(v.unit)) + "), " + number(v.pixel_offset) + "}"; +} +static std::string assignments(const std::string &name, + const std::string &value) { + static const std::set lengths = {"width", + "height", + "min-width", + "min-height", + "max-width", + "max-height", + "left", + "top", + "right", + "bottom", + "padding-left", + "padding-top", + "padding-right", + "padding-bottom", + "margin-left", + "margin-top", + "margin-right", + "margin-bottom", + "row-gap", + "column-gap", + "flex-basis", + "border-top-left-radius", + "border-top-right-radius", + "border-bottom-left-radius", + "border-bottom-right-radius"}; + auto member = name; + std::replace(member.begin(), member.end(), '-', '_'); + if (lengths.contains(name)) { + auto result = "s." + member + " = " + length(value) + ";"; + if (name.starts_with("margin-")) + result += + "s." + member + "_auto = " + (value == "auto" ? "true;" : "false;"); + return result; + } + if (name == "padding" || name == "margin" || name == "border-radius") { + std::istringstream in(value); + std::vector values; + std::string v; + while (in >> v) + values.push_back(v); + if (values.empty() || values.size() > 4) + throw std::runtime_error("invalid box shorthand"); + std::string a = values[0], b = values.size() > 1 ? values[1] : a, + c = values.size() > 2 ? values[2] : a, + d = values.size() > 3 ? values[3] : b; + std::vector names = + name == "border-radius" + ? std::vector{"border-top-left-radius", + "border-top-right-radius", + "border-bottom-right-radius", + "border-bottom-left-radius"} + : std::vector{name + "-top", name + "-right", + name + "-bottom", name + "-left"}; + return assignments(names[0], a) + assignments(names[1], b) + + assignments(names[2], c) + assignments(names[3], d); + } + if (name == "gap") { + std::istringstream in(value); + std::string a, b, c; + in >> a; + if (!(in >> b)) + b = a; + if (in >> c) + throw std::runtime_error("invalid gap"); + return assignments("row-gap", a) + assignments("column-gap", b); + } + if (name == "background" || name == "background-color" || name == "color") { + if (!std::regex_match(value, + std::regex("#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?")) && + value != "transparent" && value != "black" && value != "white") + throw std::runtime_error("initial color profile requires #rrggbb, " + "#rrggbbaa, black, white or transparent"); + return std::string("s.") + + (name == "color" ? "foreground_rgba" : "background_rgba") + " = " + + std::to_string(native_document::parse_color(value)) + "u;"; + } + static const std::map< + std::string, std::pair>> + enums = { + {"display", + {"display", + {{"block", "block"}, + {"inline", "inline_flow"}, + {"inline-block", "inline_block"}, + {"flex", "flex"}, + {"none", "none"}}}}, + {"flex-direction", + {"direction", {{"row", "row"}, {"column", "column"}}}}, + {"align-items", + {"align_items", + {{"start", "start"}, + {"flex-start", "start"}, + {"center", "center"}, + {"end", "end"}, + {"flex-end", "end"}, + {"stretch", "stretch"}}}}, + {"justify-content", + {"justify_content", + {{"start", "start"}, + {"flex-start", "start"}, + {"center", "center"}, + {"end", "end"}, + {"flex-end", "end"}, + {"space-between", "space_between"}}}}, + {"position", + {"position", + {{"static", "normal"}, + {"relative", "relative"}, + {"absolute", "absolute"}, + {"fixed", "fixed"}}}}, + {"box-sizing", + {"border_box", {{"border-box", "true"}, {"content-box", "false"}}}}}; + if (auto it = enums.find(name); it != enums.end()) { + auto val = it->second.second.find(value); + if (val == it->second.second.end()) + throw std::runtime_error("unsupported " + name + ": " + value); + auto m = it->second.first; + const std::map enum_types{ + {"display", "display_mode"}, + {"direction", "flex_direction"}, + {"align_items", "align_mode"}, + {"justify_content", "justify_mode"}, + {"position", "position_mode"}}; + return "s." + m + " = " + + (m == "border_box" ? val->second + : "webscene::native_web::" + enum_types.at(m) + + "::" + val->second) + + ";"; + } + if (name == "font-size") { + if (!value.ends_with("px")) + throw std::runtime_error("font-size currently requires px"); + auto l = native_document::parse_length(value); + length(value); + if (l.value < 0) + throw std::runtime_error("negative font size"); + return "s.font_size = " + number(l.value) + ";"; + } + if (name == "font-weight" || name == "opacity" || name == "flex-grow" || + name == "flex-shrink") { + if (!std::regex_match(value, std::regex(R"([0-9]+(\.[0-9]+)?)"))) + throw std::runtime_error("invalid numeric value"); + auto v = std::stof(value); + if ((name == "opacity" && v > 1) || + (name == "font-weight" && (v < 1 || v > 1000 || v != int(v)))) + throw std::runtime_error("numeric value out of range"); + return "s." + member + " = " + number(v) + ";"; + } + throw std::runtime_error("unsupported Native Web CSS property: " + name); +} +static std::string selector_code(const selector_syntax_selector &sel) { + std::string result = "{{"; + for (size_t i = 0; i < sel.compounds.size(); ++i) { + std::string tag, id; + std::vector classes; + bool focus = false, hover = false; + auto input = sel.compounds[i]; + size_t p = 0; + while (p < input.size()) { + char prefix = input[p]; + if (prefix == '.' || prefix == '#' || prefix == ':') + ++p; + else + prefix = 0; + size_t b = p; + while (p < input.size() && + (std::isalnum(static_cast(input[p])) || + input[p] == '_' || input[p] == '-' || input[p] == '*')) + ++p; + if (b == p) + throw std::runtime_error("unsupported selector: " + sel.serialized); + auto name = input.substr(b, p - b); + if (prefix == '.') + classes.push_back(name); + else if (prefix == '#') + id = name; + else if (prefix == ':') { + if (name == "focus") + focus = true; + else if (name == "hover") + hover = true; + else + throw std::runtime_error("unsupported pseudo-class: " + name); + } else + tag = name; + } + char relation = i ? sel.combinators.at(i - 1) : 0; + if (relation && relation != ' ' && relation != '>') + throw std::runtime_error("unsupported combinator"); + if (i) + result += ","; + result += "{" + quote(tag) + "," + quote(id) + ",{"; + for (size_t j = 0; j < classes.size(); ++j) { + if (j) + result += ","; + result += quote(classes[j]); + } + result += "}," + std::string(focus ? "true" : "false") + "," + + (hover ? "true" : "false") + "," + std::to_string(int(relation)) + + "}"; + } + return result + "}," + std::to_string(sel.specificity) + "}"; +} +struct compiler { + std::ostringstream out; + fs::path source; + std::string content; + size_t location{1}; + std::set ids; + std::vector> names; + std::vector dependencies; + unsigned count{}; + void locate(std::string_view text) { + auto at = content.find(text); + location = + at == std::string::npos + ? 1 + : 1 + std::count(content.begin(), content.begin() + at, '\n'); + } + void declarations(const css_syntax_output &css, const css_syntax_rule &r) { + out << "{"; + for (size_t j = 0; j < r.declaration_count; ++j) { + const auto &d = css.declarations.at(r.first_declaration + j); + locate(d.name); + if (j) + out << ","; + out << "{" << (d.important ? "true" : "false") + << ", +[](webscene::native_web::style& s){" + << std::regex_replace(assignments(d.name, trim(d.value)), + std::regex(R"(s\.([a-z_]+) = ([^;]+);)"), + "s.set_$1($2);") + << "}}"; + } + out << "}"; + } + void stylesheet(const std::string &text) { + auto css = parse_css_syntax_stylesheet(text); + if (!css || css.metrics.parse_error_count) + throw std::runtime_error("invalid CSS stylesheet: " + css.error); + std::vector> bounds(css.rules.size(), {0, 1e9f}); + for (size_t i = 0; i < css.rules.size(); ++i) { + const auto &r = css.rules[i]; + auto &range = bounds[i]; + if (r.parent_index != css_syntax_no_parent) + range = bounds.at(r.parent_index); + if (r.kind == css_syntax_at_rule) { + std::smatch match; + if (r.name != "media" || + !std::regex_match( + r.prelude, match, + std::regex(R"(\s*\((min|max)-width\s*:\s*([0-9]+)px\)\s*)"))) + throw std::runtime_error("only @media (min-width: Npx) / (max-width: " + "Npx) supported initially"); + auto v = std::stof(match[2]); + if (match[1] == "min") + range.first = std::max(range.first, v); + else + range.second = std::min(range.second, v); + continue; + } + auto selectors = parse_selector_syntax(r.prelude); + if (!selectors) + throw std::runtime_error(selectors.error); + for (const auto &sel : selectors.selectors) { + out << "d.add_rule({" << selector_code(sel) << ","; + declarations(css, r); + out << "," << number(range.first) << "," << number(range.second) + << "});\n"; + } + } + } + void node(const dom_node &n, const std::string &parent) { + if (n.tag == "#comment" || n.tag == "#doctype") + return; + if (n.tag == "#text") { + if (trim(n.text_content).empty()) + return; + out << "d.text(" << parent << "," << quote(n.text_content) << ");\n"; + return; + } + static const std::set tags = { + "body", "main", "section", "div", "span", "p", "h1", "h2", + "h3", "button", "canvas", "ul", "li", "header", "footer", "nav"}; + if (!tags.contains(n.tag)) + throw std::runtime_error("unsupported Native Web element: " + n.tag); + auto local = "n" + std::to_string(++count); + locate("<" + n.tag); + out << "#line " << location << " " << quote(source.string()) << "\n"; + if (n.tag == "body") + out << "auto " << local << " = d.body();\n"; + else + out << "auto " << local << " = d.element(" << parent << "," + << quote(n.tag) << ");\n"; + std::vector> attrs(n.attributes.begin(), + n.attributes.end()); + std::ranges::sort(attrs); + for (const auto &[k, v] : attrs) { + if (k == "style") { + auto css = parse_css_syntax_declarations(v); + if (!css || css.metrics.parse_error_count) + throw std::runtime_error("invalid inline style"); + css_syntax_rule r{}; + r.first_declaration = 0; + r.declaration_count = css.declarations.size(); + out << "d.add_rule({{},"; + declarations(css, r); + out << ",0,1e9f," << local << "});\n"; + continue; + } + if (k.starts_with("on")) + throw std::runtime_error( + "JavaScript attributes are not supported in Native Web"); + if (k != "id" && k != "class" && k != "width" && k != "height" && + k != "tabindex" && k != "disabled" && k != "type" && k != "role" && + !k.starts_with("aria-") && !k.starts_with("data-")) + throw std::runtime_error("unsupported attribute: " + k); + if (k == "id") { + if (!ids.insert(v).second) + throw std::runtime_error("duplicate id: " + v); + names.emplace_back(v, local); + } + out << "d.attribute(" << local << "," << quote(k) << "," << quote(v) + << ");\n"; + } + for (auto *c : n.children) + node(*c, local); + } + void compile(const fs::path &input, const fs::path &output) { + source = fs::absolute(input); + content = read(source); + dependencies.push_back(source); + native_document dom; + auto &root = dom.create_element("html"); + html_parse_options options; + options.scripting_enabled = false; + auto parsed = parse_html_document(dom, root, content, options); + if (!parsed) + throw std::runtime_error(parsed.error); + out << "// Generated by webscene-uic. Do not edit.\n#pragma once\n#include " + "\nnamespace compiled_ui {\nstruct view " + "{\n"; + // Collect metadata and code separately, so references are returned without + // exposing engine nodes. + std::ostringstream prefix; + prefix.swap(out); + const dom_node *body = nullptr; + const auto walk = [&](auto &&self, const dom_node &n) -> void { + if (n.tag == "script") + throw std::runtime_error("Native Web profile excludes scripts"); + if (n.tag == "body") + body = &n; + if (n.tag == "style") { + std::string css; + for (auto *c : n.children) + css += c->text_content; + stylesheet(css); + } + if (n.tag == "link") { + auto rel = n.attributes.find("rel"), href = n.attributes.find("href"); + if (rel == n.attributes.end() || rel->second != "stylesheet" || + href == n.attributes.end()) + throw std::runtime_error("only local stylesheet links supported"); + auto p = fs::weakly_canonical(source.parent_path() / href->second); + dependencies.push_back(p); + auto saved = content; + auto saved_path = source; + content = read(p); + source = p; + stylesheet(content); + content = saved; + source = saved_path; + } + for (auto *c : n.children) + self(self, *c); + }; + walk(walk, root); + if (!body) + throw std::runtime_error("document has no body"); + node(*body, "d.body()"); + for (size_t i = 0; i < names.size(); ++i) + prefix << "webscene::native_web::node_id element_" << i << "{};\n"; + prefix << "webscene::native_web::node_id named(std::string_view name) " + "const {\n"; + for (size_t i = 0; i < names.size(); ++i) + prefix << "if(name==" << quote(names[i].first) << ") return element_" << i + << ";\n"; + prefix << "return 0; }\n};\ninline view " + "build(webscene::native_web::document& d) {\n" + << out.str() << "return {"; + for (size_t i = 0; i < names.size(); ++i) { + if (i) + prefix << ","; + prefix << names[i].second; + } + prefix << "};\n}\n}\n"; + fs::create_directories(fs::absolute(output).parent_path()); + std::ofstream f(output); + if (!f) + throw std::runtime_error("cannot write output"); + f << prefix.str(); + f.close(); + if (!f) + throw std::runtime_error("failed writing output"); + const auto escape = [](std::string s) { + std::string r; + for (auto c : s) { + if (c == ' ' || c == '#' || c == '\\') + r += '\\'; + if (c == '$') + r += '$'; + r += c; + } + return r; + }; + std::ofstream dep(output.string() + ".d"); + dep << escape(fs::absolute(output).string()) << ":"; + for (auto p : dependencies) + dep << " " << escape(p.string()); + dep << "\n"; + } +}; +int main(int argc, char **argv) { + if (argc != 3) { + std::cerr << "usage: webscene-uic input.html output.hpp\n"; + return 2; + } + compiler c; + try { + c.compile(argv[1], argv[2]); + return 0; + } catch (const std::exception &e) { + std::cerr << c.source.string() << ":" << c.location + << ":1: error: " << e.what() << "\n"; + return 1; + } +} From 760950ea6b825f7d2307ef3a15a37e2d5da358b0 Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:30:27 +0100 Subject: [PATCH 002/472] Compile reusable HTML templates into native construction functions --- samples/NativeWeb/Main.html | 1 + samples/NativeWeb/README.md | 21 +++++++++++ samples/NativeWeb/app.hpp | 5 ++- samples/NativeWeb/build.py | 4 +- samples/NativeWeb/smoke.cpp | 2 +- src/WebScene.NativeWeb/CMakeLists.txt | 4 ++ tests/NativeWeb/Templates.html | 5 +++ tests/NativeWeb/compiler_tests.py | 12 ++++++ tests/NativeWeb/templates.cpp | 33 +++++++++++++++++ tooling/webscene-uic/main.cpp | 53 ++++++++++++++++++++++++++- 10 files changed, 133 insertions(+), 7 deletions(-) create mode 100644 tests/NativeWeb/Templates.html create mode 100644 tests/NativeWeb/templates.cpp diff --git a/samples/NativeWeb/Main.html b/samples/NativeWeb/Main.html index 9da7ca7b8..70fa57bce 100644 --- a/samples/NativeWeb/Main.html +++ b/samples/NativeWeb/Main.html @@ -24,4 +24,5 @@

Native Canvas

+ diff --git a/samples/NativeWeb/README.md b/samples/NativeWeb/README.md index 8ad8931a4..86dc11140 100644 --- a/samples/NativeWeb/README.md +++ b/samples/NativeWeb/README.md @@ -112,3 +112,24 @@ This records 20 native construction/interaction runs, build-time UI parsing and compilation costs, process RSS and bundle size in `measurements.json`. The report separates native document construction from process/GPU startup and explicitly labels warm filesystem caches and the Cocoa smoke test's deliberate delay. + +### Compiled templates + +Reusable dynamic UI can be declared as inert HTML templates: + +```html + +``` + +The compiler emits native construction functions. Application code calls +`compiled_ui::instantiate(document, parent, "item")`, obtains a `template_view` +with `roots` and `named("button")`, and updates text/classes through the native +API. No HTML string is parsed at runtime. Each instance has independent node +handles. Remove its roots explicitly when disposing the instance; dropping the +reference struct alone does not remove the nodes. + +Template children use `data-ref` rather than document-global IDs, so repeated +instances cannot overwrite each other's ID lookup. Styles live in the document's +compiled stylesheet and continue to match dynamic classes. Nested templates, +unwrapped root text, scripts and unsupported elements are rejected at compile +time. The Native Web sample's Add Item command now uses this path. diff --git a/samples/NativeWeb/app.hpp b/samples/NativeWeb/app.hpp index c9d0c0408..01d378ed3 100644 --- a/samples/NativeWeb/app.hpp +++ b/samples/NativeWeb/app.hpp @@ -26,8 +26,9 @@ struct app_state { redraw(); })); subscriptions.push_back(d.on(d.find("add"), "click", [this, &d](auto &) { - auto item = d.element(d.find("items"), "button"); - d.text(item, "Item " + std::to_string(++items) + " - click to remove"); + auto instance = compiled_ui::instantiate(d, d.find("items"), "item"); + auto item = instance.named("button"); + d.set_text(item, "Item " + std::to_string(++items) + " - click to remove"); subscriptions.push_back( d.on(item, "click", [&d, item](auto &) { d.remove(item); })); })); diff --git a/samples/NativeWeb/build.py b/samples/NativeWeb/build.py index fe2df1556..4dd55c03b 100644 --- a/samples/NativeWeb/build.py +++ b/samples/NativeWeb/build.py @@ -28,10 +28,10 @@ def run(command): llvm=pathlib.Path('/opt/homebrew/opt/llvm/bin/clang++') if llvm.exists():configure += [f'-DCMAKE_CXX_COMPILER={llvm}',f'-DCMAKE_OBJCXX_COMPILER={llvm}'] start=time.perf_counter();run(configure) -targets=['webscene-uic','native_web_smoke','native_web_contracts']+(['FocoNativeWeb','native_web_foco_focus'] if args.foco else []) +targets=['webscene-uic','native_web_smoke','native_web_contracts','native_web_templates']+(['FocoNativeWeb','native_web_foco_focus'] if args.foco else []) run(['cmake','--build',build,'--target',*targets,'-j','6']) build_seconds=time.perf_counter()-start -run(['ctest','--test-dir',build,'--output-on-failure','-R','^native_web_(smoke|contracts|compiler|foco_focus)$']) +run(['ctest','--test-dir',build,'--output-on-failure','-R','^native_web_(smoke|contracts|templates|compiler|foco_focus)$']) result={'build_seconds':build_seconds,'build_timing_note':'Configure plus build; may be incremental.','smoke':subprocess.check_output([build/'native_web_smoke'],text=True).strip()} if args.reference_engine: parsed=json.loads(subprocess.check_output(['python3',repo/'tests/NativeWeb/parsed_reference.py',args.reference_engine.resolve(),repo/'samples/NativeWeb/Main.html'],text=True)) diff --git a/samples/NativeWeb/smoke.cpp b/samples/NativeWeb/smoke.cpp index 7c02f792f..a5fb7e69f 100644 --- a/samples/NativeWeb/smoke.cpp +++ b/samples/NativeWeb/smoke.cpp @@ -1,5 +1,5 @@ -#include "app.hpp" #include "native_web_smoke_ui.hpp" +#include "app.hpp" #include #include #include diff --git a/src/WebScene.NativeWeb/CMakeLists.txt b/src/WebScene.NativeWeb/CMakeLists.txt index 3eb9e09a1..ce57540bf 100644 --- a/src/WebScene.NativeWeb/CMakeLists.txt +++ b/src/WebScene.NativeWeb/CMakeLists.txt @@ -65,6 +65,10 @@ if(FOCO_SOURCE_DIR) endif() endif() if(BUILD_TESTING) + add_executable(native_web_templates "${WEBSCENE_ROOT}/tests/NativeWeb/templates.cpp") + target_link_libraries(native_web_templates PRIVATE webscene_native_web) + webscene_compile_html(native_web_templates "${WEBSCENE_ROOT}/tests/NativeWeb/Templates.html") + add_test(NAME native_web_templates COMMAND native_web_templates) add_executable(native_web_contracts "${WEBSCENE_ROOT}/tests/NativeWeb/contracts.cpp") target_link_libraries(native_web_contracts PRIVATE webscene_native_web) webscene_compile_html(native_web_contracts "${WEBSCENE_ROOT}/tests/NativeWeb/Contracts.html") diff --git a/tests/NativeWeb/Templates.html b/tests/NativeWeb/Templates.html new file mode 100644 index 000000000..41ac16062 --- /dev/null +++ b/tests/NativeWeb/Templates.html @@ -0,0 +1,5 @@ + + +
+ + diff --git a/tests/NativeWeb/compiler_tests.py b/tests/NativeWeb/compiler_tests.py index e6670594e..2f9529339 100644 --- a/tests/NativeWeb/compiler_tests.py +++ b/tests/NativeWeb/compiler_tests.py @@ -30,4 +30,16 @@ def test_missing_resource_rejected(self): result,_=self.compile('');self.assertNotEqual(result.returncode,0) def test_nonzero_unitless_length_rejected(self): result,_=self.compile('
','div { width: 10; }');self.assertNotEqual(result.returncode,0) + def test_template_scripts_rejected(self): + result,_=self.compile('') + self.assertNotEqual(result.returncode,0) + def test_template_global_ids_rejected(self): + result,_=self.compile('') + self.assertNotEqual(result.returncode,0);self.assertIn('data-ref',result.stderr) + def test_template_duplicate_references_rejected(self): + result,_=self.compile('') + self.assertNotEqual(result.returncode,0) + def test_nested_templates_rejected(self): + result,_=self.compile('') + self.assertNotEqual(result.returncode,0) if __name__=='__main__':unittest.main() diff --git a/tests/NativeWeb/templates.cpp b/tests/NativeWeb/templates.cpp new file mode 100644 index 000000000..2c24bdbd3 --- /dev/null +++ b/tests/NativeWeb/templates.cpp @@ -0,0 +1,33 @@ +#include "native_web_templates_ui.hpp" +#include +static void check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} +int main() { + webscene::native_web::document d; + const auto view = compiled_ui::build(d); + auto parent = view.named("items"); + check(!d.find("item"), "template must stay inert"); + auto first = compiled_ui::instantiate(d, parent, "item"); + auto second = compiled_ui::instantiate(d, parent, "item"); + check(first.roots.size() == 1 && second.roots.size() == 1, "template roots"); + check(first.named("label") != second.named("label"), "instance-local references"); + d.set_text(first.named("label"), "First"); + d.attribute(second.named("row"), "class", "row selected"); + d.render(500, 400); + check(d.bounds(first.named("row")).height == 30, "first instance style"); + check(d.bounds(second.named("row")).height == 45, "second instance live style"); + int calls = 0; + auto sub = d.on(first.named("remove"), "click", [&](auto&) { + ++calls; + for (auto root : first.roots) d.remove(root); + }); + d.dispatch(first.named("remove"), "click"); + check(calls == 1, "native template event"); + d.render(500, 400); + check(d.bounds(second.named("row")).height == 45, "independent instance survives removal"); + bool missing = false; + try { compiled_ui::instantiate(d, parent, "unknown"); } + catch (const std::invalid_argument&) { missing = true; } + check(missing, "unknown template rejected"); +} diff --git a/tooling/webscene-uic/main.cpp b/tooling/webscene-uic/main.cpp index 470d30175..482ad8843 100644 --- a/tooling/webscene-uic/main.cpp +++ b/tooling/webscene-uic/main.cpp @@ -274,6 +274,8 @@ struct compiler { std::vector> names; std::vector dependencies; unsigned count{}; + bool in_template{}; + std::vector> templates; void locate(std::string_view text) { auto at = content.find(text); location = @@ -334,6 +336,10 @@ struct compiler { } } void node(const dom_node &n, const std::string &parent) { + if (n.tag == "template") { + if (in_template) throw std::runtime_error("nested compiled templates are not supported"); + return; // Inert; emitted as an instantiation function. + } if (n.tag == "#comment" || n.tag == "#doctype") return; if (n.tag == "#text") { @@ -378,7 +384,9 @@ struct compiler { k != "tabindex" && k != "disabled" && k != "type" && k != "role" && !k.starts_with("aria-") && !k.starts_with("data-")) throw std::runtime_error("unsupported attribute: " + k); - if (k == "id") { + if (in_template && k == "id") + throw std::runtime_error("template elements use data-ref instead of document-global id"); + if (k == "id" || (in_template && k == "data-ref")) { if (!ids.insert(v).second) throw std::runtime_error("duplicate id: " + v); names.emplace_back(v, local); @@ -409,6 +417,15 @@ struct compiler { prefix.swap(out); const dom_node *body = nullptr; const auto walk = [&](auto &&self, const dom_node &n) -> void { + if (n.tag == "template") { + auto id = n.attributes.find("id"); + if (id == n.attributes.end() || id->second.empty()) + throw std::runtime_error("compiled template requires a nonempty id"); + for (const auto& entry : templates) + if (entry.first == id->second) throw std::runtime_error("duplicate template: " + id->second); + templates.emplace_back(id->second, &n); + return; + } if (n.tag == "script") throw std::runtime_error("Native Web profile excludes scripts"); if (n.tag == "body") @@ -456,7 +473,39 @@ struct compiler { prefix << ","; prefix << names[i].second; } - prefix << "};\n}\n}\n"; + prefix << "};\n}\n"; + prefix << "struct template_view {\n" + "std::vector roots;\n" + "std::vector> references;\n" + "webscene::native_web::node_id named(std::string_view name) const {\n" + "for(auto [key,value]:references) if(key==name) return value; return 0; }\n};\n" + "inline template_view instantiate(webscene::native_web::document& d, " + "webscene::native_web::node_id parent, std::string_view name) {\n"; + for (const auto& [name, element] : templates) { + in_template = true; + ids.clear(); names.clear(); out.str(""); out.clear(); + std::vector roots; + if (element->template_contents) { + for (auto* child : element->template_contents->children) { + if (child->tag == "template") + throw std::runtime_error("nested compiled templates are not supported"); + if (child->tag == "#text" && !trim(child->text_content).empty()) + throw std::runtime_error("template root text must be wrapped in an element"); + auto before = count; + node(*child, "parent"); + if (count != before) roots.push_back("n" + std::to_string(before + 1)); + } + } + prefix << "if(name==" << quote(name) << ") {\n" << out.str() << "return {{"; + for (size_t i=0;i Date: Thu, 10 Sep 2026 17:34:25 +0100 Subject: [PATCH 003/472] Expose V8-free WebGPU canvas types and native device initialization --- .../graphics/native_webgpu_canvas_context.h | 74 +++++++++ .../native/graphics/native_webgpu_device.h | 67 ++++++++ .../native/graphics/platform_webgpu_canvas.h | 4 +- .../graphics/v8_webgpu_canvas_configuration.h | 9 +- .../graphics/v8_webgpu_canvas_context.h | 12 +- .../graphics/v8_webgpu_dxgi_canvas_host.h | 35 +---- .../v8_webgpu_iosurface_canvas_host.h | 35 +---- .../graphics/v8_webgpu_texture_descriptor.h | 24 +-- .../graphics/webgpu_canvas_configuration.h | 15 ++ .../native/graphics/webgpu_canvas_host.h | 13 ++ .../webgpu_canvas_texture_descriptor.h | 4 +- .../native/graphics/webgpu_dxgi_canvas_host.h | 34 +++++ .../graphics/webgpu_iosurface_canvas_host.h | 34 +++++ .../graphics/webgpu_texture_descriptor.h | 30 ++++ samples/NativeWeb/README.md | 15 ++ src/WebScene.NativeWeb/CMakeLists.txt | 22 +++ tests/NativeWeb/gpu.cpp | 143 ++++++++++++++++++ 17 files changed, 463 insertions(+), 107 deletions(-) create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_canvas_context.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_device.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_configuration.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_host.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_dxgi_canvas_host.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_iosurface_canvas_host.h create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_texture_descriptor.h create mode 100644 tests/NativeWeb/gpu.cpp diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_canvas_context.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_canvas_context.h new file mode 100644 index 000000000..43b76158d --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_canvas_context.h @@ -0,0 +1,74 @@ +#pragma once +#include "webgpu_canvas_host.h" +#include +#include + +namespace webscene::graphics { +// Native authoring counterpart of GPUCanvasContext. The caller owns the device +// service and pumps its completions. Host callbacks retain submitted images until +// GPU completion and compositor retirement; this object never reads them back. +class native_webgpu_canvas_context final { + const std::thread::id thread_ = std::this_thread::get_id(); + webgpu_canvas_host host_; + std::optional configuration_; + wgpu::Texture current_; + uint32_t width_, height_; + void check_thread() const { + if (std::this_thread::get_id() != thread_) + throw std::logic_error("Canvas context requires its owning engine thread"); + } +public: + native_webgpu_canvas_context(uint32_t width, uint32_t height, webgpu_canvas_host host) + : host_(std::move(host)), width_(width), height_(height) { + if (!host_.validate || !host_.acquire || !host_.retire) + throw std::invalid_argument("Canvas requires validation, acquisition and retirement callbacks"); + } + native_webgpu_canvas_context(const native_webgpu_canvas_context&) = delete; + native_webgpu_canvas_context& operator=(const native_webgpu_canvas_context&) = delete; + ~native_webgpu_canvas_context() { + // Destruction on another thread or failed retirement is a violated + // ownership contract; silently abandoning an imported image is unsafe. + check_thread(); + end_frame(false); + } + void configure(webgpu_canvas_configuration configuration) { + check_thread(); + if (!configuration.device) + throw std::invalid_argument("Canvas requires a live device"); + host_.validate(configuration); + validate_webgpu_canvas_format_usage(configuration); + end_frame(false); + if (host_.invalidate) host_.invalidate(); + configuration_ = std::move(configuration); + } + void unconfigure() { + check_thread(); + end_frame(false); + configuration_.reset(); + if (host_.invalidate) host_.invalidate(); + } + void resize(uint32_t width, uint32_t height) { + check_thread(); + if (width == width_ && height == height_) return; + end_frame(false); + width_ = width; height_ = height; + if (host_.invalidate) host_.invalidate(); + } + // An empty texture signals presenter backpressure; callers retry on the + // next rendering opportunity rather than allocating unbounded images. + wgpu::Texture current_texture() { + check_thread(); + if (!configuration_) throw std::logic_error("Canvas is not configured"); + if (!current_) + current_ = host_.acquire(*configuration_, + webgpu_canvas_texture_descriptor(*configuration_, width_, height_)); + return current_; + } + void end_frame(bool present = true) { + check_thread(); + if (!current_) return; + host_.retire(current_, present); + current_ = nullptr; + } +}; +} // namespace webscene::graphics diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_device.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_device.h new file mode 100644 index 000000000..2e7849dad --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_device.h @@ -0,0 +1,67 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webscene::graphics { +// Explicit startup helper for native applications. Blocking discovery is limited +// to initialization; rendering uses the device queue and event service normally. +struct native_webgpu_device { + std::shared_ptr> failed = std::make_shared>(false); + wgpu::Instance instance; + wgpu::Adapter adapter; + wgpu::Device device; + static native_webgpu_device create(wgpu::BackendType backend, + std::vector features = {}) { + native_webgpu_device result; + constexpr auto timed_wait = wgpu::InstanceFeatureName::TimedWaitAny; + wgpu::InstanceDescriptor descriptor{}; + descriptor.requiredFeatureCount = 1; + descriptor.requiredFeatures = &timed_wait; + result.instance = wgpu::CreateInstance(&descriptor); + if (!result.instance) throw std::runtime_error("WebGPU instance creation failed"); + struct discovery { wgpu::Adapter adapter; wgpu::Device device; std::string error; }; + auto state = std::make_shared(); + auto message = [](wgpu::StringView text) { + return !text.data ? std::string{} : text.length == WGPU_STRLEN + ? std::string(text.data) : std::string(text.data, text.length); + }; + wgpu::RequestAdapterOptions options{}; + options.backendType = backend; + auto future = result.instance.RequestAdapter(&options, wgpu::CallbackMode::WaitAnyOnly, + [state, message](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView error) { + if (status == wgpu::RequestAdapterStatus::Success) state->adapter = std::move(adapter); + state->error = message(error); + }); + if (result.instance.WaitAny(future, 30'000'000'000ULL) != wgpu::WaitStatus::Success) + throw std::runtime_error("WebGPU adapter discovery timed out"); + if (!state->adapter) throw std::runtime_error("WebGPU adapter discovery failed: " + state->error); + result.adapter = state->adapter; + wgpu::DeviceDescriptor device_descriptor{}; + device_descriptor.requiredFeatureCount = features.size(); + device_descriptor.requiredFeatures = features.data(); + device_descriptor.SetUncapturedErrorCallback( + [](const wgpu::Device&, wgpu::ErrorType, wgpu::StringView error, std::atomic* failed) { failed->store(true); if (error.data) std::fprintf(stderr, "WebGPU: %.*s\n", int(std::min(4096, error.length == WGPU_STRLEN ? std::char_traits::length(error.data) : error.length)), error.data); }, result.failed.get()); + device_descriptor.SetDeviceLostCallback(wgpu::CallbackMode::AllowSpontaneous, + [failed=result.failed](const wgpu::Device&, wgpu::DeviceLostReason reason, wgpu::StringView) { + if (reason != wgpu::DeviceLostReason::Destroyed && reason != wgpu::DeviceLostReason::CallbackCancelled) + failed->store(true); + }); + future = result.adapter.RequestDevice(&device_descriptor, wgpu::CallbackMode::WaitAnyOnly, + [state, message](wgpu::RequestDeviceStatus status, wgpu::Device device, wgpu::StringView error) { + if (status == wgpu::RequestDeviceStatus::Success) state->device = std::move(device); + state->error = message(error); + }); + if (result.instance.WaitAny(future, 30'000'000'000ULL) != wgpu::WaitStatus::Success) + throw std::runtime_error("WebGPU device creation timed out"); + if (!state->device) throw std::runtime_error("WebGPU device creation failed: " + state->error); + result.device = state->device; + return result; + } +}; +} // namespace webscene::graphics diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/platform_webgpu_canvas.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/platform_webgpu_canvas.h index b0c9fafde..4a92661f4 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/platform_webgpu_canvas.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/platform_webgpu_canvas.h @@ -2,7 +2,7 @@ #include "webgpu_canvas_interop.h" #if defined(__APPLE__) #include "dawn_scene_image_snapshot.h" -#include "v8_webgpu_iosurface_canvas_host.h" +#include "webgpu_iosurface_canvas_host.h" namespace webscene::graphics { using platform_dawn_canvas_host=dawn_iosurface_canvas_host; using platform_dawn_scene_snapshot=dawn_scene_image_snapshot; @@ -13,7 +13,7 @@ inline auto make_platform_webgpu_canvas_host(std::shared_ptr view_formats; - std::string alpha_mode="opaque",color_space="srgb",tone_mapping="standard"; -}; + template bool read_webgpu_canvas_configuration(v8::Isolate* isolate,v8::Local context, v8::Local input,webgpu_canvas_configuration& output,ResolveDevice resolve_device) { webgpu_state_reader reader(isolate,context,input);webgpu_canvas_configuration converted;v8::Local value; diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_canvas_context.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_canvas_context.h index ed8f0e231..83fbd151d 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_canvas_context.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_canvas_context.h @@ -1,17 +1,13 @@ #pragma once +#include "webgpu_canvas_host.h" +#include "v8_webgpu_canvas_configuration.h" +#include "v8_webgpu_texture_descriptor.h" #include "v8_webgpu_devices.h" #include "webgpu_canvas_texture_descriptor.h" #include #include namespace webscene::graphics { -// Host callbacks run on the engine thread, invoke no JavaScript, and must retain -// imported allocations through GPU completion. They never implement CPU copies. -struct webgpu_canvas_host { - std::function validate; - std::function acquire; - std::function retire; - std::function invalidate; -}; + class v8_webgpu_canvas_context { alignas(void*) static inline char brand_{}; v8::Isolate* isolate_;const std::thread::id thread_=std::this_thread::get_id(); diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_dxgi_canvas_host.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_dxgi_canvas_host.h index 4c5600d9c..236fbe2b1 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_dxgi_canvas_host.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_dxgi_canvas_host.h @@ -1,34 +1,3 @@ #pragma once -#include "v8_webgpu_canvas_context.h" -#include "dawn_dxgi_canvas_host.h" -#if defined(_WIN32) -namespace webscene::graphics { -// The document supplies canvas/generation/content and producer timeline identities. This -// adapter supplies bitmap and presentation metadata from the configuration. -inline webgpu_canvas_host make_dxgi_webgpu_canvas_host( - std::shared_ptr provider, - std::function next_metadata,std::shared_ptr device_lifetime={}) { - if(!provider||!next_metadata)throw std::invalid_argument("Canvas provider and frame identity source required"); - webgpu_canvas_host result; - result.validate=[](const webgpu_canvas_configuration& config) { - if(config.format!=wgpu::TextureFormat::BGRA8Unorm||config.color_space!="srgb"||config.tone_mapping!="standard") - throw std::invalid_argument("DXGI presenter currently requires BGRA8 sRGB standard tone mapping"); - if(!config.device.HasFeature(wgpu::FeatureName::SharedTextureMemoryDXGISharedHandle)|| - !config.device.HasFeature(wgpu::FeatureName::SharedFenceDXGISharedHandle)) - throw std::invalid_argument("Canvas device lacks native DXGI sharing capabilities"); - }; - result.acquire=[provider,next_metadata=std::move(next_metadata),device_lifetime=std::move(device_lifetime)]( - const webgpu_canvas_configuration& config,const webgpu_texture_descriptor& descriptor) { - auto metadata=next_metadata();metadata.width=descriptor.size.width;metadata.height=descriptor.size.height; - metadata.format=image_format::bgra8_unorm;metadata.color_space=image_color_space::srgb; - metadata.alpha=config.alpha_mode=="opaque"?image_alpha::opaque:image_alpha::premultiplied; - metadata.orientation=image_orientation::top_left; - wgpu::Texture texture; - descriptor.with_native([&](const auto& native){texture=provider->acquire(metadata,config.device,native,device_lifetime);}); - return texture; - }; - result.retire=[provider](const wgpu::Texture& texture,bool present){provider->retire(texture,present);}; - return result; -} -} // namespace webscene::graphics -#endif +// Compatibility include for existing JavaScript binding consumers. +#include "webgpu_dxgi_canvas_host.h" diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_iosurface_canvas_host.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_iosurface_canvas_host.h index da84c8087..2cf623b47 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_iosurface_canvas_host.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_iosurface_canvas_host.h @@ -1,34 +1,3 @@ #pragma once -#include "v8_webgpu_canvas_context.h" -#include "dawn_iosurface_canvas_host.h" -#if defined(__APPLE__) -namespace webscene::graphics { -// The document supplies canvas/generation/content and producer timeline identities. This -// adapter supplies bitmap and presentation metadata from the configuration. -inline webgpu_canvas_host make_iosurface_webgpu_canvas_host( - std::shared_ptr provider, - std::function next_metadata,std::shared_ptr device_lifetime={}) { - if(!provider||!next_metadata)throw std::invalid_argument("Canvas provider and frame identity source required"); - webgpu_canvas_host result; - result.validate=[](const webgpu_canvas_configuration& config) { - if(config.format!=wgpu::TextureFormat::BGRA8Unorm||config.color_space!="srgb"||config.tone_mapping!="standard") - throw std::invalid_argument("IOSurface presenter currently requires BGRA8 sRGB standard tone mapping"); - if(!config.device.HasFeature(wgpu::FeatureName::SharedTextureMemoryIOSurface)|| - !config.device.HasFeature(wgpu::FeatureName::SharedFenceMTLSharedEvent)) - throw std::invalid_argument("Canvas device lacks native IOSurface sharing capabilities"); - }; - result.acquire=[provider,next_metadata=std::move(next_metadata),device_lifetime=std::move(device_lifetime)]( - const webgpu_canvas_configuration& config,const webgpu_texture_descriptor& descriptor) { - auto metadata=next_metadata();metadata.width=descriptor.size.width;metadata.height=descriptor.size.height; - metadata.format=image_format::bgra8_unorm;metadata.color_space=image_color_space::srgb; - metadata.alpha=config.alpha_mode=="opaque"?image_alpha::opaque:image_alpha::premultiplied; - metadata.orientation=image_orientation::top_left; - wgpu::Texture texture; - descriptor.with_native([&](const auto& native){texture=provider->acquire(metadata,config.device,native,device_lifetime);}); - return texture; - }; - result.retire=[provider](const wgpu::Texture& texture,bool present){provider->retire(texture,present);}; - return result; -} -} // namespace webscene::graphics -#endif +// Compatibility include for existing JavaScript binding consumers. +#include "webgpu_iosurface_canvas_host.h" diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_texture_descriptor.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_texture_descriptor.h index 721f445d8..dea1f29d6 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_texture_descriptor.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/v8_webgpu_texture_descriptor.h @@ -1,28 +1,8 @@ #pragma once +#include "webgpu_texture_descriptor.h" #include "v8_webgpu_vertex_state.h" namespace webscene::graphics { -struct webgpu_texture_descriptor { - std::string label; - wgpu::TextureDimension dimension=wgpu::TextureDimension::e2D; - wgpu::TextureFormat format=wgpu::TextureFormat::Undefined; - uint32_t mip_levels=1,samples=1,usage=0; - wgpu::Extent3D size{0,1,1}; - bool valid_extent_shape=true; - wgpu::TextureViewDimension binding_dimension=wgpu::TextureViewDimension::Undefined; - std::vector view_formats; - template void with_native(Execute execute) const & { - if(!valid_extent_shape)throw std::invalid_argument("Invalid texture extent shape"); - wgpu::TextureDescriptor result{};result.label=wgpu::StringView(label.data(),label.size()); - result.dimension=dimension;result.format=format;result.mipLevelCount=mip_levels;result.sampleCount=samples;result.size=size; - // Exclude host-only usage bits. Invalid browser masks remain invalid - // native descriptors so Dawn reports validation instead of enabling them. - result.usage=(usage&~0x3fu)?wgpu::TextureUsage::None:static_cast(usage); - result.viewFormatCount=view_formats.size();result.viewFormats=view_formats.data(); - wgpu::TextureBindingViewDimension binding{};binding.textureBindingViewDimension=binding_dimension; - if(binding_dimension!=wgpu::TextureViewDimension::Undefined)result.nextInChain=&binding; - execute(result); - } -}; + inline bool read_webgpu_texture_descriptor(v8::Isolate* isolate,v8::Local context,v8::Local input,webgpu_texture_descriptor& output) { webgpu_state_reader reader(isolate,context,input);webgpu_texture_descriptor converted;v8::Local value; if(!reader.get("label",value))return false; diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_configuration.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_configuration.h new file mode 100644 index 000000000..1a248f955 --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_configuration.h @@ -0,0 +1,15 @@ +#pragma once +#include +#include +#include +#include +#include +namespace webscene::graphics { +struct webgpu_canvas_configuration { + wgpu::Device device; + wgpu::TextureFormat format=wgpu::TextureFormat::Undefined; + uint32_t usage=0x10; + std::vector view_formats; + std::string alpha_mode="opaque",color_space="srgb",tone_mapping="standard"; +}; +} // namespace webscene::graphics diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_host.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_host.h new file mode 100644 index 000000000..cd1df560b --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_host.h @@ -0,0 +1,13 @@ +#pragma once +#include "webgpu_canvas_texture_descriptor.h" +#include +namespace webscene::graphics { +// Host callbacks run on the engine thread, invoke no JavaScript, and must retain +// imported allocations through GPU completion. They never implement CPU copies. +struct webgpu_canvas_host { + std::function validate; + std::function acquire; + std::function retire; + std::function invalidate; +}; +} // namespace webscene::graphics diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_texture_descriptor.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_texture_descriptor.h index 13d916baa..c5d589a5a 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_texture_descriptor.h +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_canvas_texture_descriptor.h @@ -1,6 +1,6 @@ #pragma once -#include "v8_webgpu_canvas_configuration.h" -#include "v8_webgpu_texture_descriptor.h" +#include "webgpu_canvas_configuration.h" +#include "webgpu_texture_descriptor.h" namespace webscene::graphics { // Content-side checks specific to canvas formats/usage. Required-format feature // checks must precede these in configure; native texture validation follows. diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_dxgi_canvas_host.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_dxgi_canvas_host.h new file mode 100644 index 000000000..89476e46c --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_dxgi_canvas_host.h @@ -0,0 +1,34 @@ +#pragma once +#include "webgpu_canvas_host.h" +#include "dawn_dxgi_canvas_host.h" +#if defined(_WIN32) +namespace webscene::graphics { +// The document supplies canvas/generation/content and producer timeline identities. This +// adapter supplies bitmap and presentation metadata from the configuration. +inline webgpu_canvas_host make_dxgi_webgpu_canvas_host( + std::shared_ptr provider, + std::function next_metadata,std::shared_ptr device_lifetime={}) { + if(!provider||!next_metadata)throw std::invalid_argument("Canvas provider and frame identity source required"); + webgpu_canvas_host result; + result.validate=[](const webgpu_canvas_configuration& config) { + if(config.format!=wgpu::TextureFormat::BGRA8Unorm||config.color_space!="srgb"||config.tone_mapping!="standard") + throw std::invalid_argument("DXGI presenter currently requires BGRA8 sRGB standard tone mapping"); + if(!config.device.HasFeature(wgpu::FeatureName::SharedTextureMemoryDXGISharedHandle)|| + !config.device.HasFeature(wgpu::FeatureName::SharedFenceDXGISharedHandle)) + throw std::invalid_argument("Canvas device lacks native DXGI sharing capabilities"); + }; + result.acquire=[provider,next_metadata=std::move(next_metadata),device_lifetime=std::move(device_lifetime)]( + const webgpu_canvas_configuration& config,const webgpu_texture_descriptor& descriptor) { + auto metadata=next_metadata();metadata.width=descriptor.size.width;metadata.height=descriptor.size.height; + metadata.format=image_format::bgra8_unorm;metadata.color_space=image_color_space::srgb; + metadata.alpha=config.alpha_mode=="opaque"?image_alpha::opaque:image_alpha::premultiplied; + metadata.orientation=image_orientation::top_left; + wgpu::Texture texture; + descriptor.with_native([&](const auto& native){texture=provider->acquire(metadata,config.device,native,device_lifetime);}); + return texture; + }; + result.retire=[provider](const wgpu::Texture& texture,bool present){provider->retire(texture,present);}; + return result; +} +} // namespace webscene::graphics +#endif diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_iosurface_canvas_host.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_iosurface_canvas_host.h new file mode 100644 index 000000000..39d5c844e --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_iosurface_canvas_host.h @@ -0,0 +1,34 @@ +#pragma once +#include "webgpu_canvas_host.h" +#include "dawn_iosurface_canvas_host.h" +#if defined(__APPLE__) +namespace webscene::graphics { +// The document supplies canvas/generation/content and producer timeline identities. This +// adapter supplies bitmap and presentation metadata from the configuration. +inline webgpu_canvas_host make_iosurface_webgpu_canvas_host( + std::shared_ptr provider, + std::function next_metadata,std::shared_ptr device_lifetime={}) { + if(!provider||!next_metadata)throw std::invalid_argument("Canvas provider and frame identity source required"); + webgpu_canvas_host result; + result.validate=[](const webgpu_canvas_configuration& config) { + if(config.format!=wgpu::TextureFormat::BGRA8Unorm||config.color_space!="srgb"||config.tone_mapping!="standard") + throw std::invalid_argument("IOSurface presenter currently requires BGRA8 sRGB standard tone mapping"); + if(!config.device.HasFeature(wgpu::FeatureName::SharedTextureMemoryIOSurface)|| + !config.device.HasFeature(wgpu::FeatureName::SharedFenceMTLSharedEvent)) + throw std::invalid_argument("Canvas device lacks native IOSurface sharing capabilities"); + }; + result.acquire=[provider,next_metadata=std::move(next_metadata),device_lifetime=std::move(device_lifetime)]( + const webgpu_canvas_configuration& config,const webgpu_texture_descriptor& descriptor) { + auto metadata=next_metadata();metadata.width=descriptor.size.width;metadata.height=descriptor.size.height; + metadata.format=image_format::bgra8_unorm;metadata.color_space=image_color_space::srgb; + metadata.alpha=config.alpha_mode=="opaque"?image_alpha::opaque:image_alpha::premultiplied; + metadata.orientation=image_orientation::top_left; + wgpu::Texture texture; + descriptor.with_native([&](const auto& native){texture=provider->acquire(metadata,config.device,native,device_lifetime);}); + return texture; + }; + result.retire=[provider](const wgpu::Texture& texture,bool present){provider->retire(texture,present);}; + return result; +} +} // namespace webscene::graphics +#endif diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_texture_descriptor.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_texture_descriptor.h new file mode 100644 index 000000000..068e6c6b0 --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/webgpu_texture_descriptor.h @@ -0,0 +1,30 @@ +#pragma once +#include +#include +#include +#include +#include +namespace webscene::graphics { +struct webgpu_texture_descriptor { + std::string label; + wgpu::TextureDimension dimension=wgpu::TextureDimension::e2D; + wgpu::TextureFormat format=wgpu::TextureFormat::Undefined; + uint32_t mip_levels=1,samples=1,usage=0; + wgpu::Extent3D size{0,1,1}; + bool valid_extent_shape=true; + wgpu::TextureViewDimension binding_dimension=wgpu::TextureViewDimension::Undefined; + std::vector view_formats; + template void with_native(Execute execute) const & { + if(!valid_extent_shape)throw std::invalid_argument("Invalid texture extent shape"); + wgpu::TextureDescriptor result{};result.label=wgpu::StringView(label.data(),label.size()); + result.dimension=dimension;result.format=format;result.mipLevelCount=mip_levels;result.sampleCount=samples;result.size=size; + // Exclude host-only usage bits. Invalid browser masks remain invalid + // native descriptors so Dawn reports validation instead of enabling them. + result.usage=(usage&~0x3fu)?wgpu::TextureUsage::None:static_cast(usage); + result.viewFormatCount=view_formats.size();result.viewFormats=view_formats.data(); + wgpu::TextureBindingViewDimension binding{};binding.textureBindingViewDimension=binding_dimension; + if(binding_dimension!=wgpu::TextureViewDimension::Undefined)result.nextInChain=&binding; + execute(result); + } +}; +} // namespace webscene::graphics diff --git a/samples/NativeWeb/README.md b/samples/NativeWeb/README.md index 86dc11140..4ffa8383a 100644 --- a/samples/NativeWeb/README.md +++ b/samples/NativeWeb/README.md @@ -133,3 +133,18 @@ instances cannot overwrite each other's ID lookup. Styles live in the document's compiled stylesheet and continue to match dynamic classes. Nested templates, unwrapped root text, scripts and unsupported elements are rejected at compile time. The Native Web sample's Add Item command now uses this path. + +### Native WebGPU validation + +Configure `src/WebScene.NativeWeb` with `WEBSCENE_NATIVE_WEB_GPU=ON` and +`WEBSCENE_GRAPHICS_SDK_ROOT` pointing at a verified Dawn SDK RID directory. +Build `native_web_gpu`, then run `ctest -R '^native_web_gpu$' --output-on-failure` +from that build directory. This target links Dawn and system libraries without V8. + +The native headers provide explicit device discovery and Canvas +configure/current-texture/end-frame/resize/unconfigure APIs. The hardware test +renders a clear through the native Canvas context and checks 68 pixels using +diagnostic readback. This is not the production presentation path and does not +prove Foco compositor integration. The native platform host adapters reuse the +existing IOSurface/DXGI providers; their end-to-end connection to the Native Web +Foco carrier remains outstanding. Only macOS Metal has been run for this new test. diff --git a/src/WebScene.NativeWeb/CMakeLists.txt b/src/WebScene.NativeWeb/CMakeLists.txt index ce57540bf..90c487a16 100644 --- a/src/WebScene.NativeWeb/CMakeLists.txt +++ b/src/WebScene.NativeWeb/CMakeLists.txt @@ -76,3 +76,25 @@ if(BUILD_TESTING) find_package(Python3 COMPONENTS Interpreter REQUIRED) add_test(NAME native_web_compiler COMMAND ${Python3_EXECUTABLE} "${WEBSCENE_ROOT}/tests/NativeWeb/compiler_tests.py" $) endif() + +option(WEBSCENE_NATIVE_WEB_GPU "Build the native WebGPU authoring support and hardware test" OFF) +if(WEBSCENE_NATIVE_WEB_GPU) + set(WEBSCENE_GRAPHICS_COMPONENTS dawn) + include("${WEBSCENE_ROOT}/eng/graphics/GraphicsDependencies.cmake") + add_library(webscene_native_web_gpu INTERFACE) + target_include_directories(webscene_native_web_gpu INTERFACE "${NATIVE}/graphics") + target_link_libraries(webscene_native_web_gpu INTERFACE dawn::webgpu_dawn) + if(BUILD_TESTING) + add_executable(native_web_gpu "${WEBSCENE_ROOT}/tests/NativeWeb/gpu.cpp") + target_link_libraries(native_web_gpu PRIVATE webscene_native_web_gpu) + if(APPLE) + set(native_web_gpu_backend metal) + elseif(WIN32) + set(native_web_gpu_backend d3d12) + else() + set(native_web_gpu_backend vulkan) + endif() + add_test(NAME native_web_gpu COMMAND native_web_gpu ${native_web_gpu_backend}) + set_tests_properties(native_web_gpu PROPERTIES TIMEOUT 90) + endif() +endif() diff --git a/tests/NativeWeb/gpu.cpp b/tests/NativeWeb/gpu.cpp new file mode 100644 index 000000000..f75f280b9 --- /dev/null +++ b/tests/NativeWeb/gpu.cpp @@ -0,0 +1,143 @@ +#include "native_webgpu_device.h" +#include "native_webgpu_canvas_context.h" +// Diagnostic readback only. This executable is not a canvas presentation path. +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::string text(wgpu::StringView value) { + if (!value.data) return {}; + return value.length == WGPU_STRLEN ? std::string(value.data) + : std::string(value.data, value.length); +} + +std::string json(std::string_view value) { + constexpr char hex[] = "0123456789abcdef"; + std::string result = "\""; + for (unsigned char c : value) { + if (c == '"' || c == '\\') { result += '\\'; result += c; } + else if (c < 32) { result += "\\u00"; result += hex[c >> 4]; result += hex[c & 15]; } + else result += c; + } + return result + '"'; +} + +int finish(std::string_view status, std::string_view reason, int code) { + std::cout << "{\"schemaVersion\":1,\"probe\":\"dawn\",\"status\":" << json(status) + << ",\"reason\":" << json(reason) << "}\n"; + return code; +} + +bool wait(const wgpu::Instance& instance, wgpu::Future future) { + return instance.WaitAny(future, 30'000'000'000ULL) == wgpu::WaitStatus::Success; +} +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) return finish("failed", "Specify d3d12, metal or vulkan", 1); + const std::string backend = argv[1]; + wgpu::RequestAdapterOptions options{}; + if (backend == "d3d12") options.backendType = wgpu::BackendType::D3D12; + else if (backend == "metal") options.backendType = wgpu::BackendType::Metal; + else if (backend == "vulkan") options.backendType = wgpu::BackendType::Vulkan; + else return finish("failed", "Unsupported backend", 1); + options.forceFallbackAdapter = false; + + auto gpu = webscene::graphics::native_webgpu_device::create(options.backendType); + const auto& instance = gpu.instance; + const auto& device = gpu.device; + auto& error = *gpu.failed; + wgpu::AdapterInfo info{}; + if (gpu.adapter.GetInfo(&info) != wgpu::Status::Success) return 1; + if (info.adapterType != wgpu::AdapterType::DiscreteGPU && info.adapterType != wgpu::AdapterType::IntegratedGPU) return 1; + int retired = 0; + webscene::graphics::webgpu_canvas_host host; + host.validate = [](const auto&) {}; + host.acquire = [](const auto& config, const auto& descriptor) { + wgpu::Texture texture; + descriptor.with_native([&](const auto& native) { texture = config.device.CreateTexture(&native); }); + return texture; + }; + host.retire = [&](const auto&, bool present) { if(present) ++retired; }; + webscene::graphics::native_webgpu_canvas_context canvas(17, 4, std::move(host)); + webscene::graphics::webgpu_canvas_configuration config; + config.device = device; + config.format = wgpu::TextureFormat::RGBA8Unorm; + config.usage = (static_cast(wgpu::TextureUsage::RenderAttachment) | static_cast(wgpu::TextureUsage::CopySrc)); + canvas.configure(config); + // Non-row-aligned width exercises the texture-copy layout, not just the first pixel. + constexpr uint32_t width = 17, height = 4, rowBytes = 256; + constexpr size_t bufferSize = rowBytes * height; + auto texture = canvas.current_texture(); + if (canvas.current_texture().Get() != texture.Get()) return 1; + wgpu::BufferDescriptor bufferDescriptor{}; + bufferDescriptor.size = bufferSize; + bufferDescriptor.usage = wgpu::BufferUsage::MapRead | wgpu::BufferUsage::CopyDst; + auto buffer = device.CreateBuffer(&bufferDescriptor); + wgpu::RenderPassColorAttachment color{}; + wgpu::TextureViewDescriptor view_descriptor{}; + view_descriptor.usage = wgpu::TextureUsage::RenderAttachment; + color.view = texture.CreateView(&view_descriptor); + color.loadOp = wgpu::LoadOp::Clear; + color.storeOp = wgpu::StoreOp::Store; + color.clearValue = {0.2, 0.4, 0.6, 1.0}; + wgpu::RenderPassDescriptor passDescriptor{}; + passDescriptor.colorAttachmentCount = 1; + passDescriptor.colorAttachments = &color; + auto encoder = device.CreateCommandEncoder(); + auto pass = encoder.BeginRenderPass(&passDescriptor); + pass.End(); + wgpu::TexelCopyTextureInfo source{}; + source.texture = texture; + wgpu::TexelCopyBufferInfo destination{}; + destination.buffer = buffer; + destination.layout.bytesPerRow = rowBytes; + destination.layout.rowsPerImage = height; + const wgpu::Extent3D extent{width, height, 1}; + encoder.CopyTextureToBuffer(&source, &destination, &extent); + auto commands = encoder.Finish(); + device.GetQueue().Submit(1, &commands); + + auto mapped = std::make_shared(false); + auto mapFuture = buffer.MapAsync(wgpu::MapMode::Read, 0, bufferSize, + wgpu::CallbackMode::WaitAnyOnly, + [mapped](wgpu::MapAsyncStatus status, wgpu::StringView) { + *mapped = status == wgpu::MapAsyncStatus::Success; + }); + if (!wait(instance, mapFuture) || !*mapped || error.load()) + return finish("failed", "GPU clear/copy/map failed or timed out", 1); + auto pixels = static_cast(buffer.GetConstMappedRange(0, bufferSize)); + if (!pixels) return finish("failed", "Mapped range is null", 1); + constexpr std::array expected{51, 102, 153, 255}; + bool valid = true; + for (uint32_t y = 0; y < height; ++y) + for (uint32_t x = 0; x < width; ++x) + for (uint32_t c = 0; c < 4; ++c) + valid &= std::abs(int(pixels[y * rowBytes + x * 4 + c]) - expected[c]) <= 1; + buffer.Unmap(); + canvas.end_frame(); + if (retired != 1) return 1; + canvas.resize(32, 16); + if (canvas.current_texture().GetWidth() != 32) return 1; + canvas.unconfigure(); + bool rejected = false; + try { canvas.current_texture(); } catch (const std::logic_error&) { rejected = true; } + if (!rejected) return 1; + if (!valid) return finish("failed", "Readback pixels differ from the clear color", 1); + std::cout << "{\"schemaVersion\":1,\"probe\":\"dawn\",\"status\":\"passed\"," + << "\"hardwareAccelerated\":true,\"backend\":" << json(backend) + << ",\"adapter\":" << json(text(info.device)) + << ",\"vendor\":" << json(text(info.vendor)) + << ",\"driver\":" << json(text(info.description)) + << ",\"vendorId\":" << info.vendorID << ",\"deviceId\":" << info.deviceID + << ",\"verifiedPixels\":" << width * height + << ",\"expectedRGBA\":[51,102,153,255],\"tolerance\":1,\"diagnosticReadback\":true}\n"; + return 0; +} From 78ce806fbd324bb1cb4261a1ad07ab80d025dbf5 Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:37:52 +0100 Subject: [PATCH 004/472] Add native WebGPU surface with retained platform image snapshots --- .../native/graphics/native_webgpu_surface.h | 62 +++++++++++++++ samples/NativeWeb/README.md | 9 +++ src/WebScene.NativeWeb/CMakeLists.txt | 4 + tests/NativeWeb/gpu_iosurface.cpp | 76 +++++++++++++++++++ 4 files changed, 151 insertions(+) create mode 100644 experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_surface.h create mode 100644 tests/NativeWeb/gpu_iosurface.cpp diff --git a/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_surface.h b/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_surface.h new file mode 100644 index 000000000..282610a58 --- /dev/null +++ b/experiments/WebScene.NativeEngine.Probe/native/graphics/native_webgpu_surface.h @@ -0,0 +1,62 @@ +#pragma once +#include "native_webgpu_device.h" +#include "native_webgpu_canvas_context.h" +#include "platform_webgpu_canvas.h" +#if defined(__APPLE__) || defined(_WIN32) +namespace webscene::graphics { +// Native application surface using the same imported images and retained +// snapshots as the JS binding. Hosts consume snapshots through their compositor; +// a frame never needs to be copied into CPU Canvas commands. +class native_webgpu_surface final { + std::shared_ptr gpu_; + std::shared_ptr provider_; + uint64_t canvas_id_, generation_=1, serial_=0; + native_webgpu_canvas_context canvas_; + static std::vector features() { +#if defined(__APPLE__) + return {wgpu::FeatureName::SharedTextureMemoryIOSurface, wgpu::FeatureName::SharedFenceMTLSharedEvent}; +#else + return {wgpu::FeatureName::SharedTextureMemoryDXGISharedHandle, wgpu::FeatureName::SharedFenceDXGISharedHandle}; +#endif + } + webgpu_canvas_host host() { + auto metadata=[this] { + image_metadata result; + result.canvas=canvas_id_;result.allocation_generation=generation_; + result.content_serial=++serial_;result.producer_timeline=canvas_id_;result.producer_value=serial_; + return result; + }; +#if defined(__APPLE__) + return make_iosurface_webgpu_canvas_host(provider_, std::move(metadata), gpu_); +#else + return make_dxgi_webgpu_canvas_host(provider_, std::move(metadata), gpu_); +#endif + } +public: + native_webgpu_surface(uint64_t canvas_id, uint32_t width, uint32_t height, + uint64_t byte_budget=64*1024*1024) + : gpu_(std::make_shared(native_webgpu_device::create(platform_canvas_backend,features()))), + provider_(std::make_shared(byte_budget)), + canvas_id_(canvas_id), canvas_(width,height,host()) { + if(!canvas_id_)throw std::invalid_argument("Native GPU surface requires a nonzero canvas identity"); + webgpu_canvas_configuration config; + config.device=gpu_->device;config.format=wgpu::TextureFormat::BGRA8Unorm; + canvas_.configure(config); + } + const wgpu::Device& device() const { return gpu_->device; } + wgpu::Texture current_texture() { return canvas_.current_texture(); } + void resize(uint32_t width,uint32_t height) { canvas_.resize(width,height); } + std::shared_ptr present() { + canvas_.end_frame(); + auto ticket=provider_->capture_latest_submission(); + return ticket ? std::make_shared(std::move(ticket)) : nullptr; + } + void process_events() { + gpu_->instance.ProcessEvents(); + // Snapshots retain exact outputs independently of the provider queue. + while(provider_->take_ready()) {} + } + bool failed() const { return gpu_->failed->load(); } +}; +} // namespace webscene::graphics +#endif diff --git a/samples/NativeWeb/README.md b/samples/NativeWeb/README.md index 4ffa8383a..c05a46d51 100644 --- a/samples/NativeWeb/README.md +++ b/samples/NativeWeb/README.md @@ -148,3 +148,12 @@ diagnostic readback. This is not the production presentation path and does not prove Foco compositor integration. The native platform host adapters reuse the existing IOSurface/DXGI providers; their end-to-end connection to the Native Web Foco carrier remains outstanding. Only macOS Metal has been run for this new test. + +`native_webgpu_surface` now combines native device initialization with the +platform Canvas provider and retained scene-image snapshots. Its Metal test +(`native_web_gpu_iosurface`) renders eight resized IOSurface frames, retires +consumers, and separately verifies the combined surface API's snapshot resolution. +The path does not require V8 or CPU image copying. These tests do not yet draw the +image through Foco. Foco's current `webscene_scene_v1` command packet and picture +compiler have no GPU image resource channel; adding lifetime-safe retained image +transport and Graphite sampling is the next integration requirement. diff --git a/src/WebScene.NativeWeb/CMakeLists.txt b/src/WebScene.NativeWeb/CMakeLists.txt index 90c487a16..9d0ac15cb 100644 --- a/src/WebScene.NativeWeb/CMakeLists.txt +++ b/src/WebScene.NativeWeb/CMakeLists.txt @@ -88,6 +88,10 @@ if(WEBSCENE_NATIVE_WEB_GPU) add_executable(native_web_gpu "${WEBSCENE_ROOT}/tests/NativeWeb/gpu.cpp") target_link_libraries(native_web_gpu PRIVATE webscene_native_web_gpu) if(APPLE) + add_executable(native_web_gpu_iosurface "${WEBSCENE_ROOT}/tests/NativeWeb/gpu_iosurface.cpp") + target_link_libraries(native_web_gpu_iosurface PRIVATE webscene_native_web_gpu "-framework IOSurface" "-framework CoreFoundation" "-framework Metal") + add_test(NAME native_web_gpu_iosurface COMMAND native_web_gpu_iosurface) + set_tests_properties(native_web_gpu_iosurface PROPERTIES TIMEOUT 90) set(native_web_gpu_backend metal) elseif(WIN32) set(native_web_gpu_backend d3d12) diff --git a/tests/NativeWeb/gpu_iosurface.cpp b/tests/NativeWeb/gpu_iosurface.cpp new file mode 100644 index 000000000..0113606ec --- /dev/null +++ b/tests/NativeWeb/gpu_iosurface.cpp @@ -0,0 +1,76 @@ +#include "native_webgpu_surface.h" +#include "native_webgpu_device.h" +#include "native_webgpu_canvas_context.h" +#include "webgpu_iosurface_canvas_host.h" +#include +#include +#include +using namespace webscene::graphics; +static void check(bool value, const char* message) { if(!value) throw std::runtime_error(message); } +int main() { + auto gpu = std::make_shared(native_webgpu_device::create(wgpu::BackendType::Metal, + {wgpu::FeatureName::SharedTextureMemoryIOSurface, wgpu::FeatureName::SharedFenceMTLSharedEvent})); + auto provider = std::make_shared(16 * 1024 * 1024); + uint64_t serial = 0; + native_webgpu_canvas_context canvas(64, 64, make_iosurface_webgpu_canvas_host(provider, [&] { + image_metadata metadata; + metadata.canvas=1; metadata.allocation_generation=1; metadata.content_serial=++serial; + metadata.producer_timeline=1; metadata.producer_value=serial; + return metadata; + }, gpu)); + webgpu_canvas_configuration config; + config.device=gpu->device; config.format=wgpu::TextureFormat::BGRA8Unorm; + canvas.configure(config); + for(unsigned frame=0;frame<8;++frame) { + canvas.resize(64 + frame * 4, 64); + auto texture=canvas.current_texture(); + check(bool(texture), "IOSurface acquisition failed"); + wgpu::RenderPassColorAttachment color{}; + color.view=texture.CreateView();color.loadOp=wgpu::LoadOp::Clear;color.storeOp=wgpu::StoreOp::Store; + color.clearValue={0.2,0.4,0.6,1}; + wgpu::RenderPassDescriptor pass_descriptor{}; + pass_descriptor.colorAttachmentCount=1;pass_descriptor.colorAttachments=&color; + auto encoder=gpu->device.CreateCommandEncoder(); + auto pass=encoder.BeginRenderPass(&pass_descriptor);pass.End(); + auto commands=encoder.Finish();gpu->device.GetQueue().Submit(1,&commands); + canvas.end_frame(); + auto snapshot=provider->capture_latest_submission(); + check(bool(snapshot), "missing submitted image snapshot"); + auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(10); + while(snapshot->state()==dawn_iosurface_submission::status::pending && std::chrono::steady_clock::now()instance.ProcessEvents();std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + check(snapshot->state()==dawn_iosurface_submission::status::ready,"GPU handoff did not complete"); + auto retained=snapshot->take_ready();check(bool(retained),"missing retained IOSurface"); + check(retained->describe().width==64+frame*4,"wrong image dimensions"); + auto consumer=retained->begin_consumer();check(bool(consumer),"consumer acquisition failed"); + check(consumer->provider()->kind()==image_provider_kind::iosurface,"wrong image provider"); + // No consumer GPU work in this contract test; actual Foco presentation + // must signal completion only after its GPU sampling has completed. + consumer->complete(); + auto ready=provider->take_ready(); + } + canvas.unconfigure(); + check(provider->idle(),"provider did not retire submissions"); + check(!gpu->failed->load(),"WebGPU validation or device loss"); + native_webgpu_surface surface(42, 80, 60); + auto surface_texture=surface.current_texture(); + check(bool(surface_texture), "native surface did not initialize"); + wgpu::RenderPassColorAttachment attachment{}; + attachment.view=surface_texture.CreateView();attachment.loadOp=wgpu::LoadOp::Clear;attachment.storeOp=wgpu::StoreOp::Store; + attachment.clearValue={1,0,0,1}; + wgpu::RenderPassDescriptor desc{};desc.colorAttachmentCount=1;desc.colorAttachments=&attachment; + auto encoder=surface.device().CreateCommandEncoder();auto pass=encoder.BeginRenderPass(&desc);pass.End(); + auto commands=encoder.Finish();surface.device().GetQueue().Submit(1,&commands); + auto snapshot=surface.present();check(bool(snapshot), "native surface snapshot missing"); + auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(10); + std::shared_ptr image; + do { + surface.process_events();image=snapshot->resolve(); + if(!image)std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while(!image && std::chrono::steady_clock::now()describe().canvas==42, "native surface identity"); + check(!surface.failed(), "native surface validation failure"); + std::cout << "Native IOSurface: 8 frames, resize, snapshots and retirement passed\n"; +} From 637c43f19d4d546d3aa4579697197b8879543de1 Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:41:02 +0100 Subject: [PATCH 005/472] Test Foco WebScene external image placement and missing-resource rejection --- src/WebScene.NativeWeb/CMakeLists.txt | 4 +++ tests/NativeWeb/foco_image.cpp | 37 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 tests/NativeWeb/foco_image.cpp diff --git a/src/WebScene.NativeWeb/CMakeLists.txt b/src/WebScene.NativeWeb/CMakeLists.txt index 9d0ac15cb..0fe90b950 100644 --- a/src/WebScene.NativeWeb/CMakeLists.txt +++ b/src/WebScene.NativeWeb/CMakeLists.txt @@ -59,6 +59,10 @@ if(FOCO_SOURCE_DIR) set_target_properties(FocoNativeWeb PROPERTIES MACOSX_BUNDLE_GUI_IDENTIFIER "dev.focoui.nativeweb" MACOSX_BUNDLE_BUNDLE_NAME "Foco Native Web") add_test(NAME native_web_foco COMMAND $ --smoke) if(BUILD_TESTING) + add_executable(native_web_foco_image "${WEBSCENE_ROOT}/tests/NativeWeb/foco_image.cpp") + target_include_directories(native_web_foco_image PRIVATE "${FOCO_SOURCE_DIR}/src" "${FOCO_SKIA_ROOT}") + target_link_libraries(native_web_foco_image PRIVATE FocoUI::PlatformCocoa) + add_test(NAME native_web_foco_image COMMAND native_web_foco_image) add_executable(native_web_foco_focus "${WEBSCENE_ROOT}/tests/NativeWeb/foco_focus.cpp") target_link_libraries(native_web_foco_focus PRIVATE FocoUI::PlatformCocoa) add_test(NAME native_web_foco_focus COMMAND native_web_foco_focus) diff --git a/tests/NativeWeb/foco_image.cpp b/tests/NativeWeb/foco_image.cpp new file mode 100644 index 000000000..e5d5fe962 --- /dev/null +++ b/tests/NativeWeb/foco_image.cpp @@ -0,0 +1,37 @@ +#include "rendering/webscene_graphite.hpp" +#include +#include "include/core/SkSurface.h" +#include "include/core/SkCanvas.h" +#include "include/core/SkBitmap.h" +#include +#include +#include +int main() { + namespace p=foco::webscene_packet; + p::header header{}; + header.magic_value=p::magic;header.version_value=p::version; + header.viewport_width=16;header.viewport_height=16;header.revision=1; + header.layer_count=1;header.layer_offset=sizeof(header); + header.byte_count=sizeof(header)+sizeof(p::layer); + p::layer layer{}; + layer.node_id=17;layer.generation=9;layer.flags=p::layer_replace|p::layer_external_image; + layer.x=4;layer.y=4;layer.width=8;layer.height=8;layer.bitmap_width=4;layer.bitmap_height=4; + std::vector bytes(header.byte_count); + std::memcpy(bytes.data(),&header,sizeof(header));std::memcpy(bytes.data()+sizeof(header),&layer,sizeof(layer)); + auto source=SkSurfaces::Raster(SkImageInfo::MakeN32Premul(4,4)); + source->getCanvas()->clear(SK_ColorRED); + if(foco::rendering::compile_webscene_picture(bytes)) + throw std::runtime_error("unresolved image must reject picture"); + int calls=0; + auto picture=foco::rendering::compile_webscene_picture(bytes,[&](auto node,auto generation){ + if(node!=17||generation!=9)throw std::runtime_error("image identity mismatch"); + ++calls;return source->makeImageSnapshot(); + }); + if(!picture||calls!=1)throw std::runtime_error("image resolver not used"); + auto target=SkSurfaces::Raster(SkImageInfo::MakeN32Premul(16,16)); + target->getCanvas()->clear(SK_ColorWHITE);target->getCanvas()->drawPicture(picture->picture); + SkBitmap pixels;pixels.allocN32Pixels(16,16); + if(!target->readPixels(pixels.pixmap(),0,0))throw std::runtime_error("readPixels failed"); + if(pixels.getColor(5,5)!=SK_ColorRED||pixels.getColor(2,2)!=SK_ColorWHITE) + throw std::runtime_error("external image placement/scaling failed"); +} From 5f80878ddc8b05801b66a93b2d57e375760dcb61 Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:45:33 +0100 Subject: [PATCH 006/472] Verify native image owner transport and replacement cleanup --- tests/NativeWeb/foco_image.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/NativeWeb/foco_image.cpp b/tests/NativeWeb/foco_image.cpp index e5d5fe962..0d12e1294 100644 --- a/tests/NativeWeb/foco_image.cpp +++ b/tests/NativeWeb/foco_image.cpp @@ -1,4 +1,6 @@ #include "rendering/webscene_graphite.hpp" +#include +#include #include #include "include/core/SkSurface.h" #include "include/core/SkCanvas.h" @@ -6,6 +8,16 @@ #include #include #include +struct image_attachment final : foco::composition_resource_attachment {}; +struct image_control final : foco::control { + std::vector packet; + std::shared_ptr owner; + uint64_t generation=1; + std::optional composition_command_stream() const noexcept override { + return foco::composition_command_stream_view{packet,generation, + static_cast(foco::command_stream_format::webscene_scene_v1),16,16,owner}; + } +}; int main() { namespace p=foco::webscene_packet; p::header header{}; @@ -18,6 +30,22 @@ int main() { layer.x=4;layer.y=4;layer.width=8;layer.height=8;layer.bitmap_width=4;layer.bitmap_height=4; std::vector bytes(header.byte_count); std::memcpy(bytes.data(),&header,sizeof(header));std::memcpy(bytes.data()+sizeof(header),&layer,sizeof(layer)); + auto control=foco::make_ref(); + control->packet=bytes;control->owner=std::make_shared(); + std::weak_ptr weak=control->owner; + control->measure({16,16});control->arrange({0,0,16,16}); + foco::scene_publisher publisher;foco::headless_renderer renderer; + foco::compositor compositor(*publisher.mailbox(),renderer); + publisher.commit(*control,foco::theme_variant::dark); + control->owner.reset(); + if(weak.expired())throw std::runtime_error("publication dropped image owner"); + compositor.tick(); + bool retained=false; + for(const auto& [id, resource]:compositor.scene().resources()) retained|=bool(resource.attachment); + if(!retained)throw std::runtime_error("retained scene lost image attachment"); + ++control->generation;control->invalidate_render(); + publisher.commit(*control,foco::theme_variant::dark);compositor.tick(); + if(!weak.expired())throw std::runtime_error("replaced image attachment leaked"); auto source=SkSurfaces::Raster(SkImageInfo::MakeN32Premul(4,4)); source->getCanvas()->clear(SK_ColorRED); if(foco::rendering::compile_webscene_picture(bytes)) From 072ad4edaaf8b1934801be9434effcf67d58afcc Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:54:42 +0100 Subject: [PATCH 007/472] Present Native WebGPU through existing Foco Kestrel integration --- samples/NativeKestrel/LICENSE | 21 ++++++ samples/NativeKestrel/README.md | 14 ++++ samples/NativeKestrel/native/math.hpp | 68 +++++++++++++++++++ samples/NativeWeb/README.md | 37 ++++++---- samples/NativeWeb/main.mm | 33 +++++++++ src/WebScene.NativeWeb/CMakeLists.txt | 11 +-- .../foco/native_gpu_image.cpp | 43 ++++++++++++ .../foco/native_gpu_image.hpp | 8 +++ .../foco/native_web_view.hpp | 40 +++++++++-- tests/NativeWeb/foco_image.cpp | 65 ------------------ tests/NativeWeb/kestrel_math.cpp | 15 ++++ 11 files changed, 264 insertions(+), 91 deletions(-) create mode 100644 samples/NativeKestrel/LICENSE create mode 100644 samples/NativeKestrel/README.md create mode 100644 samples/NativeKestrel/native/math.hpp create mode 100644 src/WebScene.NativeWeb/foco/native_gpu_image.cpp create mode 100644 src/WebScene.NativeWeb/foco/native_gpu_image.hpp delete mode 100644 tests/NativeWeb/foco_image.cpp create mode 100644 tests/NativeWeb/kestrel_math.cpp diff --git a/samples/NativeKestrel/LICENSE b/samples/NativeKestrel/LICENSE new file mode 100644 index 000000000..54d8dc79e --- /dev/null +++ b/samples/NativeKestrel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Kestrel CAD contributors + +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/samples/NativeKestrel/README.md b/samples/NativeKestrel/README.md new file mode 100644 index 000000000..d5b5fed30 --- /dev/null +++ b/samples/NativeKestrel/README.md @@ -0,0 +1,14 @@ +# Native Kestrel port (in progress) + +Source baseline: https://github.com/wieslawsoltes/KestrelCAD at +`7a1e84c67fd24410c22f0d1a45b2e54120b32d0e`. Upstream MIT attribution is in LICENSE. + +The target is a compiled HTML/CSS interface with predefined dynamic templates, +C++ application logic and WebScene native WebGPU, hosted by Foco. No JavaScript +runtime or runtime HTML parsing is permitted in the resulting application. + +The port is not yet runnable. `native/math.hpp` begins the port of src/math.js: +vector operations, transforms, inverse, angles, intersections and polygon area. +The remaining math, drawing model/history/persistence, geometry and renderer, +commands, UI templates and the other application modules remain to be ported. +This directory is not a claim of Kestrel feature parity. diff --git a/samples/NativeKestrel/native/math.hpp b/samples/NativeKestrel/native/math.hpp new file mode 100644 index 000000000..01570f3fd --- /dev/null +++ b/samples/NativeKestrel/native/math.hpp @@ -0,0 +1,68 @@ +#pragma once +// Ported from KestrelCAD src/math.js at 7a1e84c67fd24410c22f0d1a45b2e54120b32d0e. +// Copyright (c) 2026 Kestrel CAD contributors. MIT; see ../LICENSE. +#include +#include +#include +#include +#include +#include +namespace kestrel { +inline constexpr double epsilon=1e-8, tau=2*std::numbers::pi; +struct vec3 { + double x{},y{},z{}; + vec3 operator+(vec3 b) const {return {x+b.x,y+b.y,z+b.z};} + vec3 operator-(vec3 b) const {return {x-b.x,y-b.y,z-b.z};} + vec3 operator*(double s) const {return {x*s,y*s,z*s};} + double dot(vec3 b) const {return x*b.x+y*b.y+z*b.z;} + vec3 cross(vec3 b) const {return {y*b.z-z*b.y,z*b.x-x*b.z,x*b.y-y*b.x};} + double length() const {return std::hypot(x,y,z);} + vec3 normalized() const {auto l=length();return l>epsilon?*this*(1/l):vec3{};} +}; +inline vec3 lerp(vec3 a,vec3 b,double t){return a+(b-a)*t;} +using matrix=std::array; +inline matrix identity(){return {1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};} +inline matrix multiply(const matrix& a,const matrix& b){ + matrix r{};for(int c=0;c<4;++c)for(int row=0;row<4;++row)for(int k=0;k<4;++k) + r[c*4+row]+=a[k*4+row]*b[c*4+k];return r; +} +inline vec3 transform(const matrix& m,vec3 p,double w=1){ + vec3 q{m[0]*p.x+m[4]*p.y+m[8]*p.z+m[12]*w, + m[1]*p.x+m[5]*p.y+m[9]*p.z+m[13]*w, + m[2]*p.x+m[6]*p.y+m[10]*p.z+m[14]*w}; + auto divisor=m[3]*p.x+m[7]*p.y+m[11]*p.z+m[15]*w; + return w&&std::abs(divisor)>epsilon?q*(1/divisor):q; +} +inline matrix translation(vec3 p){auto m=identity();m[12]=p.x;m[13]=p.y;m[14]=p.z;return m;} +inline matrix scale(vec3 p){auto m=identity();m[0]=p.x;m[5]=p.y;m[10]=p.z;return m;} +inline matrix rotation(double angle,vec3 axis={0,0,1}){ + auto [x,y,z]=axis.normalized();auto c=std::cos(angle),s=std::sin(angle),t=1-c; + return {t*x*x+c,t*x*y+s*z,t*x*z-s*y,0,t*x*y-s*z,t*y*y+c,t*y*z+s*x,0, + t*x*z+s*y,t*y*z-s*x,t*z*z+c,0,0,0,0,1}; +} +inline matrix around(vec3 p,const matrix& m){return multiply(translation(p),multiply(m,translation(p*-1)));} +inline std::optional inverse(const matrix& a){ + std::array,4> aug{}; + for(int r=0;r<4;++r)for(int c=0;c<4;++c){aug[r][c]=a[c*4+r];aug[r][c+4]=r==c;} + for(int i=0;i<4;++i){ + int k=i;for(int r=i+1;r<4;++r)if(std::abs(aug[r][i])>std::abs(aug[k][i]))k=r; + if(std::abs(aug[k][i])<1e-16)return {}; + std::swap(aug[i],aug[k]);auto s=aug[i][i];for(auto& v:aug[i])v/=s; + for(int r=0;r<4;++r)if(r!=i){auto f=aug[r][i];for(int c=0;c<8;++c)aug[r][c]-=f*aug[i][c];} + } + matrix result{};for(int r=0;r<4;++r)for(int c=0;c<4;++c)result[c*4+r]=aug[r][c+4];return result; +} +inline double angle(double a){return std::fmod(std::fmod(a,tau)+tau,tau);} +inline double sweep(double a,double b){auto s=angle(b-a);return s line_intersection(vec3 a,vec3 b,vec3 c,vec3 d){ + auto r=b-a,s=d-c;auto den=r.x*s.y-r.y*s.x;if(std::abs(den) points){ + double area=0;if(points.empty())return 0; + for(size_t i=0,j=points.size()-1;i +#endif #import #import #include @@ -14,6 +19,31 @@ foco::ref window_; foco::ref view_; app_state state_; +#if defined(NATIVE_WEB_GPU_SAMPLE) + std::unique_ptr gpu_; + void initialize_gpu() { + auto node=view_->document.find("chart"); + gpu_=std::make_unique(node,300,120); + auto texture=gpu_->current_texture(); + if(!texture)throw std::runtime_error("Native GPU Canvas acquisition failed"); + wgpu::RenderPassColorAttachment color{}; + color.view=texture.CreateView();color.loadOp=wgpu::LoadOp::Clear;color.storeOp=wgpu::StoreOp::Store; + color.clearValue={0.1,0.55,0.85,1}; + wgpu::RenderPassDescriptor desc{};desc.colorAttachmentCount=1;desc.colorAttachments=&color; + auto encoder=gpu_->device().CreateCommandEncoder();auto pass=encoder.BeginRenderPass(&desc);pass.End(); + auto commands=encoder.Finish();gpu_->device().GetQueue().Submit(1,&commands); + auto snapshot=gpu_->present(); + if(!snapshot)throw std::runtime_error("Native GPU snapshot missing"); + std::shared_ptr image; + auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(10); + do { + gpu_->process_events();image=snapshot->resolve(); + if(!image)std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while(!image && std::chrono::steady_clock::now()failed())throw std::runtime_error("Native GPU first frame failed"); + view_->set_gpu_image(node,300,120,1,webscene::foco_host::make_gpu_image(node,1,std::move(image))); + } +#endif public: foco::result started(foco::application_lifetime &base) override { @@ -28,6 +58,9 @@ view_ = foco::make_ref(); compiled_ui::build(view_->document); state_.attach(view_->document); +#if defined(NATIVE_WEB_GPU_SAMPLE) + initialize_gpu(); +#endif auto resource = [NSBundle mainBundle].resourcePath; std::ifstream about(std::string([resource UTF8String]) + "/about.txt"); if (!about) diff --git a/src/WebScene.NativeWeb/CMakeLists.txt b/src/WebScene.NativeWeb/CMakeLists.txt index 0fe90b950..a6290d2c6 100644 --- a/src/WebScene.NativeWeb/CMakeLists.txt +++ b/src/WebScene.NativeWeb/CMakeLists.txt @@ -59,10 +59,6 @@ if(FOCO_SOURCE_DIR) set_target_properties(FocoNativeWeb PROPERTIES MACOSX_BUNDLE_GUI_IDENTIFIER "dev.focoui.nativeweb" MACOSX_BUNDLE_BUNDLE_NAME "Foco Native Web") add_test(NAME native_web_foco COMMAND $ --smoke) if(BUILD_TESTING) - add_executable(native_web_foco_image "${WEBSCENE_ROOT}/tests/NativeWeb/foco_image.cpp") - target_include_directories(native_web_foco_image PRIVATE "${FOCO_SOURCE_DIR}/src" "${FOCO_SKIA_ROOT}") - target_link_libraries(native_web_foco_image PRIVATE FocoUI::PlatformCocoa) - add_test(NAME native_web_foco_image COMMAND native_web_foco_image) add_executable(native_web_foco_focus "${WEBSCENE_ROOT}/tests/NativeWeb/foco_focus.cpp") target_link_libraries(native_web_foco_focus PRIVATE FocoUI::PlatformCocoa) add_test(NAME native_web_foco_focus COMMAND native_web_foco_focus) @@ -88,6 +84,13 @@ if(WEBSCENE_NATIVE_WEB_GPU) add_library(webscene_native_web_gpu INTERFACE) target_include_directories(webscene_native_web_gpu INTERFACE "${NATIVE}/graphics") target_link_libraries(webscene_native_web_gpu INTERFACE dawn::webgpu_dawn) + if(FOCO_SOURCE_DIR AND APPLE) + add_library(webscene_native_web_foco_gpu STATIC foco/native_gpu_image.cpp) + target_include_directories(webscene_native_web_foco_gpu PUBLIC foco "${FOCO_SOURCE_DIR}/src" "${FOCO_SKIA_ROOT}") + target_link_libraries(webscene_native_web_foco_gpu PUBLIC webscene_native_web_gpu FocoUI::PlatformCocoa "-framework IOSurface") + target_link_libraries(FocoNativeWeb PRIVATE webscene_native_web_foco_gpu) + target_compile_definitions(FocoNativeWeb PRIVATE NATIVE_WEB_GPU_SAMPLE=1) + endif() if(BUILD_TESTING) add_executable(native_web_gpu "${WEBSCENE_ROOT}/tests/NativeWeb/gpu.cpp") target_link_libraries(native_web_gpu PRIVATE webscene_native_web_gpu) diff --git a/src/WebScene.NativeWeb/foco/native_gpu_image.cpp b/src/WebScene.NativeWeb/foco/native_gpu_image.cpp new file mode 100644 index 000000000..4c75dcff6 --- /dev/null +++ b/src/WebScene.NativeWeb/foco/native_gpu_image.cpp @@ -0,0 +1,43 @@ +#include "native_gpu_image.hpp" +#include "iosurface_canvas_images.h" +namespace webscene::foco_host { +std::shared_ptr make_gpu_image( + uint32_t node,uint64_t generation,std::shared_ptr image) { + if(!node||!generation||!image||image->requires_producer_wait) + throw std::invalid_argument("Native frame requires a completed GPU image"); + const auto m=image->value.describe(); + if(m.canvas!=node)throw std::invalid_argument("Canvas identity mismatch"); + auto frame=std::make_shared(); + foco::webscene_gpu_image_info info; + info.canvas=m.canvas;info.allocation=m.allocation;info.allocation_generation=m.allocation_generation; + info.content_serial=m.content_serial;info.producer_timeline=m.producer_timeline;info.producer_value=m.producer_value; + info.width=m.width;info.height=m.height;info.format=uint32_t(m.format);info.alpha=uint32_t(m.alpha); + info.color_space=uint32_t(m.color_space);info.orientation=uint32_t(m.orientation); + frame->images.push_back({const_cast(image.get()),info}); + frame->release=[image=std::move(image)] {}; + frame->begin_consumer=[](const void* lease,void** output)->uint32_t { + if(!lease||!output)return 1; + *output=nullptr; + try { + auto value=static_cast(lease)->value.begin_consumer(); + if(!value)return 1; + try { *output=new webscene_gpu_image_consumer_v3(std::move(*value)); } + catch(...) { value->complete(); throw; } + return 0; + } catch(...) { return 1; } + }; + frame->complete_consumer=[](void* value) { + auto* consumer=static_cast(value); + if(consumer){consumer->value.complete();delete consumer;} + }; + frame->get_iosurface=[](const void* value,foco::webscene_gpu_iosurface_view* output)->uint8_t { + if(!value||!output)return 0; + try { + const auto& consumer=static_cast(value)->value; + const auto& surface=graphics::iosurface_canvas_images::resolve(consumer); + output->surface=surface.borrowed_handle();output->allocation_bytes=surface.allocation_bytes();return 1; + } catch(...) { return 0; } + }; + return frame; +} +} diff --git a/src/WebScene.NativeWeb/foco/native_gpu_image.hpp b/src/WebScene.NativeWeb/foco/native_gpu_image.hpp new file mode 100644 index 000000000..725e24a62 --- /dev/null +++ b/src/WebScene.NativeWeb/foco/native_gpu_image.hpp @@ -0,0 +1,8 @@ +#pragma once +#include +#include "image_lease_abi.h" +namespace webscene::foco_host { +std::shared_ptr make_gpu_image( + uint32_t node, uint64_t generation, + std::shared_ptr image); +} diff --git a/src/WebScene.NativeWeb/foco/native_web_view.hpp b/src/WebScene.NativeWeb/foco/native_web_view.hpp index 68f8bdb9f..223e2cc85 100644 --- a/src/WebScene.NativeWeb/foco/native_web_view.hpp +++ b/src/WebScene.NativeWeb/foco/native_web_view.hpp @@ -14,12 +14,20 @@ class view final : public foco::control { set_clip_to_bounds(true); set_focusable(true); } + void set_gpu_image(native_web::node_id node, uint32_t width, uint32_t height, + uint64_t generation, + std::shared_ptr owner) { + gpu_node_ = node; gpu_width_ = width; gpu_height_ = height; + gpu_generation_ = generation; gpu_owner_ = std::move(owner); + gpu_dirty_ = true; + refresh(); + } void refresh() { auto b = bounds(); if (b.width <= 0 || b.height <= 0) return; const auto &scene = document.render(b.width, b.height); - if (scene.revision == revision_) + if (scene.revision == document_revision_ && !gpu_dirty_) return; namespace packet = foco::webscene_packet; static_assert(sizeof(webscene_scene_command) == @@ -33,11 +41,25 @@ class view final : public foco::control { l.command_count, l.string_offset, l.string_count, l.flags, l.x, l.y, l.width, l.height, l.bitmap_width, l.bitmap_height, l.generation}); + auto commands = scene.commands; + if (gpu_owner_ && gpu_node_) { + const auto area = document.bounds(gpu_node_); + std::erase_if(layers, [&](const auto& layer){ return layer.node_id == gpu_node_; }); + for (const auto& layer : layers) { + webscene_scene_command placement{};placement.kind=257;placement.node_id=layer.node_id; + placement.x=layer.x;placement.y=layer.y;placement.width=layer.width;placement.height=layer.height; + commands.push_back(placement); + } + webscene_scene_command image{}; + image.kind=256;image.node_id=gpu_node_;image.rgba=0; + image.x=area.x;image.y=area.y;image.width=area.width;image.height=area.height; + commands.push_back(image); + } packet::header h{}; h.magic_value = packet::magic; h.version_value = packet::version; h.flags = packet::checkpoint | packet::dom_replacement; - h.revision = scene.revision; + h.revision = ++revision_; h.viewport_width = scene.width; h.viewport_height = scene.height; packet_.assign(sizeof(h), std::byte{}); @@ -51,8 +73,8 @@ class view final : public foco::control { data.size() * sizeof(T)); return static_cast(offset); }; - h.dom_command_count = scene.commands.size(); - h.dom_command_offset = append(scene.commands); + h.dom_command_count = commands.size(); + h.dom_command_offset = append(commands); h.layer_count = layers.size(); h.layer_offset = append(layers); h.canvas_command_count = scene.canvas.size(); @@ -63,7 +85,8 @@ class view final : public foco::control { h.string_byte_offset = append(scene.bytes); h.byte_count = packet_.size(); std::memcpy(packet_.data(), &h, sizeof(h)); - revision_ = scene.revision; + document_revision_ = scene.revision; + gpu_dirty_ = false; invalidate_render(); } std::optional @@ -74,7 +97,7 @@ class view final : public foco::control { packet_, revision_, static_cast(foco::command_stream_format::webscene_scene_v1), static_cast(std::max(1.f, bounds().width)), - static_cast(std::max(1.f, bounds().height))}; + static_cast(std::max(1.f, bounds().height)), gpu_owner_}; } foco::size measure_override(foco::size available) override { return {std::isfinite(available.width) ? available.width : 1000.f, @@ -116,6 +139,9 @@ class view final : public foco::control { private: std::vector packet_; - uint64_t revision_{}; + uint64_t revision_{}, document_revision_{}, gpu_generation_{}; + uint32_t gpu_node_{}, gpu_width_{}, gpu_height_{}; + bool gpu_dirty_{}; + std::shared_ptr gpu_owner_; }; } // namespace webscene::foco_host diff --git a/tests/NativeWeb/foco_image.cpp b/tests/NativeWeb/foco_image.cpp deleted file mode 100644 index 0d12e1294..000000000 --- a/tests/NativeWeb/foco_image.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "rendering/webscene_graphite.hpp" -#include -#include -#include -#include "include/core/SkSurface.h" -#include "include/core/SkCanvas.h" -#include "include/core/SkBitmap.h" -#include -#include -#include -struct image_attachment final : foco::composition_resource_attachment {}; -struct image_control final : foco::control { - std::vector packet; - std::shared_ptr owner; - uint64_t generation=1; - std::optional composition_command_stream() const noexcept override { - return foco::composition_command_stream_view{packet,generation, - static_cast(foco::command_stream_format::webscene_scene_v1),16,16,owner}; - } -}; -int main() { - namespace p=foco::webscene_packet; - p::header header{}; - header.magic_value=p::magic;header.version_value=p::version; - header.viewport_width=16;header.viewport_height=16;header.revision=1; - header.layer_count=1;header.layer_offset=sizeof(header); - header.byte_count=sizeof(header)+sizeof(p::layer); - p::layer layer{}; - layer.node_id=17;layer.generation=9;layer.flags=p::layer_replace|p::layer_external_image; - layer.x=4;layer.y=4;layer.width=8;layer.height=8;layer.bitmap_width=4;layer.bitmap_height=4; - std::vector bytes(header.byte_count); - std::memcpy(bytes.data(),&header,sizeof(header));std::memcpy(bytes.data()+sizeof(header),&layer,sizeof(layer)); - auto control=foco::make_ref(); - control->packet=bytes;control->owner=std::make_shared(); - std::weak_ptr weak=control->owner; - control->measure({16,16});control->arrange({0,0,16,16}); - foco::scene_publisher publisher;foco::headless_renderer renderer; - foco::compositor compositor(*publisher.mailbox(),renderer); - publisher.commit(*control,foco::theme_variant::dark); - control->owner.reset(); - if(weak.expired())throw std::runtime_error("publication dropped image owner"); - compositor.tick(); - bool retained=false; - for(const auto& [id, resource]:compositor.scene().resources()) retained|=bool(resource.attachment); - if(!retained)throw std::runtime_error("retained scene lost image attachment"); - ++control->generation;control->invalidate_render(); - publisher.commit(*control,foco::theme_variant::dark);compositor.tick(); - if(!weak.expired())throw std::runtime_error("replaced image attachment leaked"); - auto source=SkSurfaces::Raster(SkImageInfo::MakeN32Premul(4,4)); - source->getCanvas()->clear(SK_ColorRED); - if(foco::rendering::compile_webscene_picture(bytes)) - throw std::runtime_error("unresolved image must reject picture"); - int calls=0; - auto picture=foco::rendering::compile_webscene_picture(bytes,[&](auto node,auto generation){ - if(node!=17||generation!=9)throw std::runtime_error("image identity mismatch"); - ++calls;return source->makeImageSnapshot(); - }); - if(!picture||calls!=1)throw std::runtime_error("image resolver not used"); - auto target=SkSurfaces::Raster(SkImageInfo::MakeN32Premul(16,16)); - target->getCanvas()->clear(SK_ColorWHITE);target->getCanvas()->drawPicture(picture->picture); - SkBitmap pixels;pixels.allocN32Pixels(16,16); - if(!target->readPixels(pixels.pixmap(),0,0))throw std::runtime_error("readPixels failed"); - if(pixels.getColor(5,5)!=SK_ColorRED||pixels.getColor(2,2)!=SK_ColorWHITE) - throw std::runtime_error("external image placement/scaling failed"); -} diff --git a/tests/NativeWeb/kestrel_math.cpp b/tests/NativeWeb/kestrel_math.cpp new file mode 100644 index 000000000..7df75eda5 --- /dev/null +++ b/tests/NativeWeb/kestrel_math.cpp @@ -0,0 +1,15 @@ +#include "../../samples/NativeKestrel/native/math.hpp" +#include +int main(){ + using namespace kestrel; + auto m=multiply(translation({10,-3,5}),multiply(rotation(0.8,{1,2,3}),scale({2,3,4}))); + auto inv=inverse(m);if(!inv)throw std::runtime_error("invertible transform rejected"); + for(auto p:{vec3{0,0,0},vec3{100,-40,2},vec3{1e5,2e5,-3e5}}) + if((transform(*inv,transform(m,p))-p).length()>1e-8)throw std::runtime_error("transform round trip"); + if(inverse(scale({1,0,1})))throw std::runtime_error("singular transform accepted"); + auto cross=line_intersection({0,0,0},{10,10,0},{0,10,0},{10,0,0}); + if(!cross||(cross->point-vec3{5,5,0}).length()>epsilon)throw std::runtime_error("line intersection"); + if(line_intersection({0,0,0},{10,0,0},{0,2,0},{10,2,0}))throw std::runtime_error("parallel intersection"); + std::array polygon{{{0,0,0},{10,0,0},{10,4,0},{0,4,0}}}; + if(polygon_area(polygon)!=40||std::abs(sweep(0,0)-tau)>epsilon)throw std::runtime_error("area/sweep"); +} From 38fbfc4b64c8d95fa608d6726a64730949ffd231 Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 17:57:47 +0100 Subject: [PATCH 008/472] Port Kestrel geometry math and camera to native C++ --- samples/NativeKestrel/README.md | 8 +- samples/NativeKestrel/native/camera.hpp | 67 +++++++ samples/NativeKestrel/native/math.hpp | 57 ++++++ src/WebScene.NativeWeb/CMakeLists.txt | 4 + tests/NativeWeb/kestrel_camera.cpp | 13 ++ tests/NativeWeb/kestrel_camera_reference.json | 173 ++++++++++++++++++ tests/NativeWeb/kestrel_camera_test.py | 9 + tests/NativeWeb/kestrel_math.cpp | 9 + 8 files changed, 337 insertions(+), 3 deletions(-) create mode 100644 samples/NativeKestrel/native/camera.hpp create mode 100644 tests/NativeWeb/kestrel_camera.cpp create mode 100644 tests/NativeWeb/kestrel_camera_reference.json create mode 100644 tests/NativeWeb/kestrel_camera_test.py diff --git a/samples/NativeKestrel/README.md b/samples/NativeKestrel/README.md index d5b5fed30..e40dab281 100644 --- a/samples/NativeKestrel/README.md +++ b/samples/NativeKestrel/README.md @@ -7,8 +7,10 @@ The target is a compiled HTML/CSS interface with predefined dynamic templates, C++ application logic and WebScene native WebGPU, hosted by Foco. No JavaScript runtime or runtime HTML parsing is permitted in the resulting application. -The port is not yet runnable. `native/math.hpp` begins the port of src/math.js: -vector operations, transforms, inverse, angles, intersections and polygon area. -The remaining math, drawing model/history/persistence, geometry and renderer, +The port is not yet runnable. `native/math.hpp` and `native/camera.hpp` port the +geometry math, triangulation and camera operations from src/math.js. Camera tests +compare 154 values against the pinned upstream implementation; additional native +tests cover transforms, concave/vertical triangulation and intersection behavior. +The drawing model/history/persistence, geometry and renderer, commands, UI templates and the other application modules remain to be ported. This directory is not a claim of Kestrel feature parity. diff --git a/samples/NativeKestrel/native/camera.hpp b/samples/NativeKestrel/native/camera.hpp new file mode 100644 index 000000000..6df58aa1d --- /dev/null +++ b/samples/NativeKestrel/native/camera.hpp @@ -0,0 +1,67 @@ +#pragma once +// Ported from upstream src/math.js; see math.hpp and ../LICENSE. +#include "math.hpp" +#include +#include +#include +namespace kestrel { +struct camera_state {vec3 target{};double zoom=1,yaw=-std::numbers::pi/2,pitch=std::numbers::pi/2;bool perspective=false;}; +class camera : public camera_state { +public: + double width=1000,height=700,distance{}; + uint64_t revision{}; + vec3 right,up,direction,eye; + kestrel::matrix view{},projection{},combined{}; + std::optional inverse_matrix; + camera(){update();} + void update(){ + auto c=std::cos(pitch);direction={std::cos(yaw)*c,std::sin(yaw)*c,std::sin(pitch)}; + right={-std::sin(yaw),std::cos(yaw),0};up=direction.cross(right); + auto h=height/zoom;distance=h*1.35;eye=target+direction*distance; + auto r=right,u=up,n=direction,e=eye; + view={r.x,u.x,n.x,0,r.y,u.y,n.y,0,r.z,u.z,n.z,0,-r.dot(e),-u.dot(e),-n.dot(e),1}; + auto w=width/zoom,near=std::max(.00001,distance/100000),far=distance*100; + projection=perspective?kestrel::perspective(40*std::numbers::pi/180,width/height,near,far):ortho(-w/2,w/2,-h/2,h/2,near,far); + combined=multiply(projection,view);inverse_matrix=inverse(combined);++revision; + } + void resize(double w,double h){if(w==width&&h==height)return;width=w;height=h;update();} + vec3 project(vec3 p)const{ + auto& m=combined;auto w=m[3]*p.x+m[7]*p.y+m[11]*p.z+m[15];if(w<=0)return {-1e9,-1e9,2}; + auto v=transform(m,p);return {(v.x+1)*width/2,(1-v.y)*height/2,v.z}; + } + struct ray_value{vec3 origin,direction;}; + ray_value ray(double x,double y)const{ + if(!inverse_matrix)throw std::runtime_error("Camera projection is singular"); + auto a=transform(*inverse_matrix,{x/width*2-1,1-y/height*2,0}); + auto b=transform(*inverse_matrix,{x/width*2-1,1-y/height*2,1});return {a,(b-a).normalized()}; + } + std::optional unproject(double x,double y,double z=0)const{ + auto r=ray(x,y);if(std::abs(r.direction.z)<1e-7)return {};return r.origin+r.direction*((z-r.origin.z)/r.direction.z); + } + vec3 point_on_view(double x,double y)const{auto r=ray(x,y);return r.origin+r.direction*((target-r.origin).dot(direction)/r.direction.dot(direction));} + void pan(double dx,double dy){target=target-(point_on_view(width/2+dx,height/2+dy)-point_on_view(width/2,height/2));update();} + void zoom_at(double factor,double x,double y){ + auto before=unproject(x,y,target.z).value_or(point_on_view(x,y));zoom=std::clamp(zoom*factor,1e-7,1e7);update(); + auto after=unproject(x,y,target.z).value_or(point_on_view(x,y));target=target+before-after;update(); + } + void zoom_at(double factor){zoom_at(factor,width/2,height/2);} + void set_view(std::string_view name){ + double y=-48,p=32; + if(name=="top"){y=-90;p=90;}else if(name=="bottom"){y=-90;p=-90;} + else if(name=="front"){y=-90;p=0;}else if(name=="back"){y=90;p=0;} + else if(name=="right"){y=0;p=0;}else if(name=="left"){y=180;p=0;} + yaw=y*std::numbers::pi/180;pitch=p*std::numbers::pi/180;update(); + } + void fit(std::span points,double padding=1.22){ + if(points.empty()){target={};zoom=std::min(width/2000,height/1400);update();return;} + vec3 min=points.front(),max=min; + for(auto p:points){min={std::min(min.x,p.x),std::min(min.y,p.y),std::min(min.z,p.z)};max={std::max(max.x,p.x),std::max(max.y,p.y),std::max(max.z,p.z)};} + target=(min+max)*.5;double x=0,y=0; + for(auto p:points){auto d=p-target;x=std::max(x,std::abs(d.dot(right)));y=std::max(y,std::abs(d.dot(up)));} + zoom=std::min(width/std::max(x*2*padding,1.),height/std::max(y*2*padding,1.));update(); + } + camera_state serialize()const{return *this;} + void restore(camera_state state){target=state.target;if(std::isfinite(state.zoom))zoom=state.zoom; + if(std::isfinite(state.yaw))yaw=state.yaw;if(std::isfinite(state.pitch))pitch=state.pitch;perspective=state.perspective;update();} +}; +} diff --git a/samples/NativeKestrel/native/math.hpp b/samples/NativeKestrel/native/math.hpp index 01570f3fd..9fc01ab96 100644 --- a/samples/NativeKestrel/native/math.hpp +++ b/samples/NativeKestrel/native/math.hpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include namespace kestrel { inline constexpr double epsilon=1e-8, tau=2*std::numbers::pi; struct vec3 { @@ -65,4 +67,59 @@ inline double polygon_area(std::span points){ for(size_t i=0,j=points.size()-1;i polygon){ + bool yes=false;if(polygon.empty())return false; + for(size_t i=0,j=polygon.size()-1;ip.y)!=(b.y>p.y)&&p.x<(b.x-a.x)*(p.y-a.y)/(b.y-a.y)+a.x)yes=!yes; + }return yes; +} +inline vec3 face_normal(std::span points){ + vec3 n;for(size_t i=0;i> triangulate(std::span points){ + if(points.size()<3)return {};if(points.size()==3)return {{{0,1,2}}}; + auto n=face_normal(points);auto drop=std::abs(n.x)>std::abs(n.y)?(std::abs(n.x)>std::abs(n.z)?0:2):(std::abs(n.y)>std::abs(n.z)?1:2); + std::vector p;for(auto v:points)p.push_back(drop==0?vec3{v.y,v.z,0}:drop==1?vec3{v.x,v.z,0}:vec3{v.x,v.y,0}); + double sign=polygon_area(p)>=0?1:-1;std::vector indices(p.size());std::iota(indices.begin(),indices.end(),0); + std::vector> out; + auto cross=[](vec3 a,vec3 b,vec3 c){return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);}; + size_t guard=points.size()*points.size(); + while(indices.size()>3&&guard--){ + bool found=false; + for(size_t k=0;k=-epsilon&&cross(p[b],p[c],p[j])*sign>=-epsilon&&cross(p[c],p[a],p[j])*sign>=-epsilon){blocked=true;break;}} + if(!blocked){out.push_back({a,b,c});indices.erase(indices.begin()+k);found=true;break;} + } + if(!found){ + size_t k=0;for(;k) add_test(NAME native_web_compiler COMMAND ${Python3_EXECUTABLE} "${WEBSCENE_ROOT}/tests/NativeWeb/compiler_tests.py" $) endif() diff --git a/tests/NativeWeb/kestrel_camera.cpp b/tests/NativeWeb/kestrel_camera.cpp new file mode 100644 index 000000000..0ee3e3b1f --- /dev/null +++ b/tests/NativeWeb/kestrel_camera.cpp @@ -0,0 +1,13 @@ +#include "../../samples/NativeKestrel/native/camera.hpp" +#include +#include +int main(){ + kestrel::camera c; + std::cout< points{{{-100,-200,-30},{500,250,80},{0,10,50}}};c.fit(points);dump(); + c.set_view("front");dump(); +} diff --git a/tests/NativeWeb/kestrel_camera_reference.json b/tests/NativeWeb/kestrel_camera_reference.json new file mode 100644 index 000000000..9734aa4f0 --- /dev/null +++ b/tests/NativeWeb/kestrel_camera_reference.json @@ -0,0 +1,173 @@ +{ + "source": "KestrelCAD 7a1e84c67fd24410c22f0d1a45b2e54120b32d0e src/math.js", + "values": [ + [ + 0.002, + -1.7494954273533618e-19, + -3.967618869412303e-38, + 0, + 1.2246467991473531e-19, + 0.002857142857142857, + 6.479613341862673e-22, + 0, + 0, + 1.7494954273533618e-19, + -0.000010582011640211743, + 0, + 0, + 0, + 0.009999900999990098, + 1, + 500, + 350, + 0.009999900999990098, + 620, + 390, + 0.009735350708984805 + ], + [ + 0.0010321455909408253, + -0.0007879671079946764, + -0.000004670411469531884, + 0, + 0.0009293480643873032, + 0.0008751261314126538, + 0.000005187017427463912, + 0, + 0, + 0.001884551324792058, + -0.00000436147586193528, + 0, + 1.5789838572446671e-16, + -2.5263741715914673e-16, + 0.009999900999990098, + 1, + 720.0000000000001, + 450.0000000000001, + 0.009999900999990098, + 782.4121548029331, + 487.10129179322973, + 0.009122934029999334 + ], + [ + 0.001548218386411238, + -0.0011819506619920148, + -0.000007005617204297827, + 0, + 0.0013940220965809546, + 0.001312689197118981, + 0.00000778052614119587, + 0, + 0, + 0.002826826987188087, + -0.000006542213792902923, + 0, + 0.3750000000000002, + -0.21111111111111144, + 0.008353466134687097, + 1, + 990.0000000000001, + 545.0000000000001, + 0.008353466134687097, + 1083.6182322043996, + 600.6519376898447, + 0.00703801567970095 + ], + [ + 1.2761085171148043, + -0.974214826419751, + -0.567454993548124, + -0.5674549368026246, + 1.149013269773089, + 1.0819751783539253, + 0.6302226174368654, + 0.6302225544146036, + 0, + 2.329992994801263, + -0.5299193172251366, + -0.5299192642332049, + 309.0912096886452, + -174.00690323212635, + 676.6307569096548, + 676.6387892465791, + 1048.8987780668378, + 565.7236441346282, + 0.9999881290622826, + 1245.7262489893767, + 667.8154753806236, + 0.9999858916487195 + ], + [ + 1.2761085171148043, + -0.974214826419751, + -0.567454993548124, + -0.5674549368026246, + 1.149013269773089, + 1.0819751783539253, + 0.6302226174368654, + 0.6302225544146036, + 0, + 2.329992994801263, + -0.5299193172251366, + -0.5299192642332049, + 322.8180601063632, + -264.23375366082183, + 1002.6689719180081, + 1002.6804430796822, + 951.8076560491073, + 568.5873225792243, + 0.9999885595039244, + 1065.4783947710105, + 633.8752321179934, + 0.9999871873165056 + ], + [ + 1.2761085171148043, + -0.974214826419751, + -0.567454993548124, + -0.5674549368026246, + 1.149013269773089, + 1.0819751783539253, + 0.6302226174368654, + 0.6302225544146036, + 0, + 2.329992994801263, + -0.5299193172251366, + -0.5299192642332049, + -283.9470351672881, + 109.54376095507047, + 879.9144696105458, + 879.9220710057577, + 487.6591233962699, + 393.97834302140245, + 0.9999913612858883, + 555.4247336712464, + 445.5726791175542, + 0.9999901573056802 + ], + [ + 1.717173387159139, + 0, + -6.123234608060227e-17, + -6.123233995736766e-17, + 1.0514654460827291e-16, + 0, + 1.00000010000001, + 1, + 0, + 2.7474774194546225, + 0, + 0, + -343.4346774318278, + -68.68693548636557, + 743.9310509062141, + 743.9386658997679, + 387.61645941356204, + 491.5479425733047, + 0.9999897639497678, + 579.4917541943208, + 450, + 0.9999891766230166 + ] + ] +} diff --git a/tests/NativeWeb/kestrel_camera_test.py b/tests/NativeWeb/kestrel_camera_test.py new file mode 100644 index 000000000..9cc7ed38c --- /dev/null +++ b/tests/NativeWeb/kestrel_camera_test.py @@ -0,0 +1,9 @@ +import json, math, pathlib, subprocess, sys +expected=json.loads(pathlib.Path(__file__).with_name('kestrel_camera_reference.json').read_text())['values'] +actual=[[float(x) for x in line.split()] for line in subprocess.check_output([sys.argv[1]],text=True).splitlines()] +assert len(actual)==len(expected) +for row,(a,b) in enumerate(zip(actual,expected)): + assert len(a)==len(b) + for column,(x,y) in enumerate(zip(a,b)): + assert math.isclose(x,y,rel_tol=1e-9,abs_tol=1e-8),(row,column,x,y) +print('Kestrel camera: 154 upstream reference values passed') diff --git a/tests/NativeWeb/kestrel_math.cpp b/tests/NativeWeb/kestrel_math.cpp index 7df75eda5..4afa13e06 100644 --- a/tests/NativeWeb/kestrel_math.cpp +++ b/tests/NativeWeb/kestrel_math.cpp @@ -12,4 +12,13 @@ int main(){ if(line_intersection({0,0,0},{10,0,0},{0,2,0},{10,2,0}))throw std::runtime_error("parallel intersection"); std::array polygon{{{0,0,0},{10,0,0},{10,4,0},{0,4,0}}}; if(polygon_area(polygon)!=40||std::abs(sweep(0,0)-tau)>epsilon)throw std::runtime_error("area/sweep"); + std::array concave{{{0,0,0},{4,0,0},{4,4,0},{2,2,0},{0,4,0}}}; + auto triangles=triangulate(concave);double area=0; + for(auto t:triangles){std::array face{concave[t[0]],concave[t[1]],concave[t[2]]};area+=polygon_area(face);} + if(triangles.size()!=3||std::abs(area-polygon_area(concave))>epsilon)throw std::runtime_error("concave triangulation"); + for(auto& p:concave){p.z=p.y;p.y=0;} + triangles=triangulate(concave);if(triangles.size()!=3)throw std::runtime_error("vertical triangulation"); + auto closest=segment_distance({20,3,0},{0,0,0},{10,0,0}); + if(closest.t!=1||closest.point.x!=10)throw std::runtime_error("segment endpoint clamp"); + if(!inside({5,2,0},polygon)||inside({20,2,0},polygon))throw std::runtime_error("polygon containment"); } From a65fee5a36918314464b818407358bdc29e21667 Mon Sep 17 00:00:00 2001 From: Dan Walmsley <4672627+danwalmsley@users.noreply.github.com> Date: Thu, 10 Sep 2026 18:01:53 +0100 Subject: [PATCH 009/472] Port Kestrel drawing transactions and project data to C++ --- samples/NativeKestrel/README.md | 13 + samples/NativeKestrel/native/drawing.hpp | 135 + .../third_party/nlohmann/LICENSE.MIT | 21 + .../third_party/nlohmann/json.hpp | 25526 ++++++++++++++++ src/WebScene.NativeWeb/CMakeLists.txt | 2 + tests/NativeWeb/kestrel_drawing.cpp | 30 + 6 files changed, 25727 insertions(+) create mode 100644 samples/NativeKestrel/native/drawing.hpp create mode 100644 samples/NativeKestrel/third_party/nlohmann/LICENSE.MIT create mode 100644 samples/NativeKestrel/third_party/nlohmann/json.hpp create mode 100644 tests/NativeWeb/kestrel_drawing.cpp diff --git a/samples/NativeKestrel/README.md b/samples/NativeKestrel/README.md index e40dab281..9dd61d9f2 100644 --- a/samples/NativeKestrel/README.md +++ b/samples/NativeKestrel/README.md @@ -14,3 +14,16 @@ tests cover transforms, concave/vertical triangulation and intersection behavior The drawing model/history/persistence, geometry and renderer, commands, UI templates and the other application modules remain to be ported. This directory is not a claim of Kestrel feature parity. + +`native/drawing.hpp` ports the core drawing/project representation, layer rules, +entity mutation, native history snapshots and base project validation. Tests cover +rollback, undo/redo, selection pruning, project round-trip and history bounds. +Production metadata, constraint enforcement/removal, fields and source-archive +validation still require their native modules; retaining their data does not mean +those features are implemented. Geometry caching, entity transforms and spatial +indexing are also outstanding. Layer-name case folding currently covers ASCII. + +Project data uses vendored nlohmann JSON 3.12.0 (MIT). Header SHA-256: +`aaf127c04cb31c406e5b04a63f1ae89369fccde6d8fa7cdda1ed4f32dfc5de63`. +This is project serialization only; HTML remains compiled into predefined views +and templates. diff --git a/samples/NativeKestrel/native/drawing.hpp b/samples/NativeKestrel/native/drawing.hpp new file mode 100644 index 000000000..3fe36b472 --- /dev/null +++ b/samples/NativeKestrel/native/drawing.hpp @@ -0,0 +1,135 @@ +#pragma once +// Native port of KestrelCAD src/model.js. See ../LICENSE and README.md. +#include "../third_party/nlohmann/json.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +namespace kestrel { +using json=nlohmann::ordered_json; +inline std::string uid(std::string prefix="e") {static std::atomic sequence{};return prefix+"_native_"+std::to_string(std::chrono::system_clock::now().time_since_epoch().count())+"_"+std::to_string(++sequence);} +inline json default_layers(){ + json layers=json::array(); + const char* ids[]={"0","architecture","openings","furniture","dimensions","annotation","hatch","construction"}; + const char* names[]={"0","A-WALL","A-OPENING","A-FURNITURE","A-DIMENSION","A-ANNOTATION","A-HATCH","A-CENTER"}; + const char* colors[]={"#dce4ed","#dee6ed","#59c8d9","#a4b5c7","#65c4b6","#c2cbd5","#687d91","#c69a66"}; + const double weights[]={.25,.35,.20,.18,.15,.18,.13,.13}; + for(int i=0;i<8;++i)layers.push_back({{"id",ids[i]},{"name",names[i]},{"color",colors[i]},{"visible",true},{"locked",false},{"linetype",i==7?"Center":"Continuous"},{"lineweight",weights[i]}}); + return layers; +} +inline bool finite_number(const json& v){return v.is_number()&&std::isfinite(v.get());} +inline void validate_project(json& data){ + auto require=[](bool value,const std::string& message){if(!value)throw std::invalid_argument(message);}; + require(data.is_object()&&data.value("format",std::string{})=="kestrel-cad"&&(data.value("version",0)==1||data.value("version",0)==2),"Unsupported Kestrel project"); + require(data.contains("entities")&&data["entities"].is_array()&&data["entities"].size()<=200000,"Invalid entity table"); + require(data.contains("layers")&&data["layers"].is_array()&&!data["layers"].empty()&&data["layers"].size()<=2048,"Invalid layer table"); + if(data.contains("name"))require(data["name"].is_string()&&data["name"].get_ref().size()<=512,"Invalid drawing name"); + static const std::regex identifier("[-a-zA-Z0-9_.:]{1,128}"),color("#[0-9a-fA-F]{6}"); + auto matches=[](const json& v,const std::regex& re){return v.is_string()&&std::regex_match(v.get_ref(),re);}; + std::unordered_set layers,ids; + for(auto& l:data["layers"]){ + require(l.is_object()&&l.contains("id")&&matches(l["id"],identifier)&&layers.insert(l["id"].get()).second,"Invalid or duplicate layer identifier"); + require(l.contains("name")&&l["name"].is_string()&&l["name"].get_ref().size()<=255,"Invalid layer name"); + if(!l.contains("color")||!matches(l["color"],color))l["color"]="#dce4ed"; + l["visible"]=!l.contains("visible")||l["visible"]!=false;l["locked"]=l.value("locked",false); + l["lineweight"]=l.contains("lineweight")&&finite_number(l["lineweight"])?std::clamp(l["lineweight"].get(),.01,5.):.25; + } + auto point=[&](json& p){require(p.is_array()&&p.size()>=2&&p.size()<=3,"Invalid coordinate shape");for(auto& v:p)require(finite_number(v)&&std::abs(v.get())<=1e12,"Invalid coordinate");if(p.size()==2)p.push_back(0);}; + const std::unordered_set types={"LINE","POLYLINE","CIRCLE","ARC","ELLIPSE","SPLINE","HATCH","POINT","TEXT","MTEXT","DIMENSION","MESH","INSERT","TABLE","LEADER"}; + size_t vertices=0; + for(auto& e:data["entities"]){ + require(e.is_object()&&types.contains(e.value("type",std::string{})),"Unsupported entity type"); + auto type=e["type"].get();if(!e.contains("id"))e["id"]=uid(); + require(matches(e["id"],identifier)&&ids.insert(e["id"].get()).second,"Invalid or duplicate entity identifier"); + if(!layers.contains(e.value("layer",std::string{})))e["layer"]=data["layers"][0]["id"]; + for(auto key:{"points","vertices","controlPoints"})if(e.contains(key)){require(e[key].is_array(),"Invalid coordinate array");vertices+=e[key].size();for(auto& p:e[key])point(p);} + for(auto key:{"position","center","axisX","axisY","normal","direction"})if(e.contains(key))point(e[key]); + for(auto key:{"radius","rx","ry","height","textHeight","spacing"})if(e.contains(key)&&!e[key].is_null())require(finite_number(e[key])&&e[key].get()>0,"Invalid positive dimension"); + for(auto key:{"rotation","startAngle","endAngle","offset","angle"})if(e.contains(key)&&!e[key].is_null())require(finite_number(e[key]),"Invalid angle or offset"); + if(type=="MESH"){ + require(e.contains("faces")&&e["faces"].is_array()&&e.contains("vertices")&&e["faces"].size()<=2000000,"Invalid mesh"); + for(auto& f:e["faces"]){require(f.is_array()&&f.size()>=3&&f.size()<=10000,"Invalid mesh face");for(auto& i:f)require(i.is_number_integer()&&i.get()>=0&&i.get()=(type=="HATCH"?3:2),"Too few entity points"); + if(type=="CIRCLE"||type=="ARC"||type=="ELLIPSE")require(e.contains("center"),"Missing curve center"); + if(type=="SPLINE"){ + auto count=e.contains("controlPoints")?e["controlPoints"].size():e.contains("points")?e["points"].size():0; + require(count>=2,"Too few spline points"); + if(e.contains("degree"))require(e["degree"].is_number_integer()&&e["degree"].get()>=1&&e["degree"].get()<=std::min(10,count-1),"Invalid spline degree"); + if(e.contains("knots")){require(e["knots"].is_array(),"Invalid knot sequence");double previous=-INFINITY;for(auto& v:e["knots"]){require(finite_number(v)&&v.get()>=previous,"Invalid knot order");previous=v.get();}} + if(e.contains("weights")){require(e["weights"].is_array()&&e["weights"].size()==count,"Invalid spline weights");for(auto& v:e["weights"])require(finite_number(v)&&v.get()>0,"Invalid spline weight");} + } + if(type=="POINT"||type=="TEXT"||type=="MTEXT")require(e.contains("position"),"Missing insertion point"); + if(type=="TEXT"||type=="MTEXT")require(e.contains("text")&&e["text"].is_string()&&e["text"].get_ref().size()<=100000,"Invalid text entity"); + if(e.contains("color")&&e["color"]!="bylayer"&&e["color"]!="byblock"&&!matches(e["color"],color))e["color"]="bylayer"; + } + require(vertices<=3000000,"Project vertex limit exceeded"); + if(data.contains("camera")&&!data["camera"].is_null()){ + auto& c=data["camera"];require(c.contains("target"),"Missing camera target");point(c["target"]); + for(auto key:{"zoom","yaw","pitch"})require(c.contains(key)&&finite_number(c[key]),"Invalid camera");require(c["zoom"].get()>0,"Invalid camera zoom"); + } + const std::unordered_set units={"mm","cm","m","in","ft","unitless"};if(!units.contains(data.value("units",std::string{})))data["units"]="mm"; +} +class drawing { + struct history {std::string label;json state;size_t bytes;}; + std::vector undo_,redo_; + void reindex(){ + if(data["layers"].empty())throw std::invalid_argument("Drawing requires a layer"); + bool current=false;for(auto& l:data["layers"])current|=l["id"]==data["currentLayer"]; + if(!current)data["currentLayer"]=data["layers"][0]["id"]; + std::erase_if(selection,[&](auto& id){return !find(id);}); + } + void changed(const std::string& label){++revision;dirty=true;if(on_change)on_change(label);} +public: + json data={{"format","kestrel-cad"},{"version",2},{"production",nullptr},{"name","Untitled"},{"units","mm"},{"currentLayer","architecture"},{"layers",default_layers()},{"entities",json::array()},{"camera",nullptr}}; + json source_document=nullptr; + std::unordered_set selection; + uint64_t revision{};bool dirty{}; + std::function on_change; + // Extension validators/constraints are supplied by the corresponding native + // modules as they are ported. They participate in transaction rollback. + std::function enforce; + json* find(const std::string& id){for(auto& e:data["entities"])if(e["id"]==id)return &e;return nullptr;} + const json& layer(const json& e)const{for(auto& l:data["layers"])if(l["id"]==e.value("layer",std::string{}))return l;return data["layers"][0];} + bool visible(const json& e)const{return layer(e).value("visible",true)&&!e.value("hidden",false);} + bool editable(const json& e)const{return visible(e)&&!layer(e).value("locked",false);} + std::vector selected(bool editable_only=false){ + std::vector result; + for(auto& id:selection)if(auto* e=find(id);e&&(!editable_only||editable(*e)))result.push_back(id); + return result; + } + std::string add_layer(std::string name,std::string color="#70b8d3"){ + auto first=name.find_first_not_of(" \t\r\n"),last=name.find_last_not_of(" \t\r\n"); + if(first==std::string::npos)throw std::invalid_argument("A layer name is required"); + name=name.substr(first,last-first+1); + auto fold=[](std::string text){for(auto& c:text)c=static_cast(std::tolower(static_cast(c)));return text;}; + for(auto& l:data["layers"])if(fold(l["name"].get())==fold(name))throw std::invalid_argument("Layer names must be unique"); + auto id=uid("layer");data["layers"].push_back({{"id",id},{"name",name},{"color",color},{"visible",true},{"locked",false},{"linetype","Continuous"},{"lineweight",.25}}); + reindex();return id; + } + std::string add(std::string type,json properties=json::object()){ + json e={{"id",uid()},{"type",std::move(type)},{"layer",data["currentLayer"]},{"color","bylayer"},{"linetype","ByLayer"}}; + e.update(properties);auto id=e["id"].get();data["entities"].push_back(std::move(e));return id; + } + void remove(const std::unordered_set& ids){std::erase_if(data["entities"].get_ref(),[&](auto& e){return ids.contains(e["id"].template get());});reindex();} + void replace(const std::string& id,json e){if(auto* old=find(id)){e["id"]=id;*old=std::move(e);}} + json serialize(bool include_source=true)const{auto result=data;if(include_source&&!source_document.is_null())result["sourceDocument"]=source_document;return result;} + void apply(json value,bool retain_source=false){auto source=value.value("sourceDocument",json{});value.erase("sourceDocument");validate_project(value);data=std::move(value);if(!source.is_null()||!retain_source)source_document=std::move(source);reindex();} + template bool transaction(std::string label,F operation){ + auto before=data;auto old_selection=selection; + try{operation();reindex();if(enforce)enforce(*this);validate_project(data);} + catch(...){data=std::move(before);selection=std::move(old_selection);throw;} + if(before==data)return false; + auto bytes=before.dump().size();undo_.push_back({label,std::move(before),bytes});redo_.clear(); + size_t total=0;for(auto& h:undo_)total+=h.bytes; + while(undo_.size()>80||(total>32000000&&undo_.size()>1)){total-=undo_.front().bytes;undo_.erase(undo_.begin());} + changed(label);return true; + } + std::optional undo(){if(undo_.empty())return {};auto item=std::move(undo_.back());undo_.pop_back();redo_.push_back({item.label,data,data.dump().size()});data=std::move(item.state);reindex();changed("Undo "+item.label);return item.label;} + std::optional redo(){if(redo_.empty())return {};auto item=std::move(redo_.back());redo_.pop_back();undo_.push_back({item.label,data,data.dump().size()});data=std::move(item.state);reindex();changed("Redo "+item.label);return item.label;} +}; +} diff --git a/samples/NativeKestrel/third_party/nlohmann/LICENSE.MIT b/samples/NativeKestrel/third_party/nlohmann/LICENSE.MIT new file mode 100644 index 000000000..a1dacc8db --- /dev/null +++ b/samples/NativeKestrel/third_party/nlohmann/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2025 Niels Lohmann + +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/samples/NativeKestrel/third_party/nlohmann/json.hpp b/samples/NativeKestrel/third_party/nlohmann/json.hpp new file mode 100644 index 000000000..82d69f7c5 --- /dev/null +++ b/samples/NativeKestrel/third_party/nlohmann/json.hpp @@ -0,0 +1,25526 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 12 || NLOHMANN_JSON_VERSION_PATCH != 0 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 12 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 0 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_DIAGNOSTIC_POSITIONS + #define JSON_DIAGNOSTIC_POSITIONS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_DIAGNOSTIC_POSITIONS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS _dp +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) json_abi ## a ## b ## c +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON, \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#ifdef JSON_HAS_CPP_17 + #include // optional +#endif +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#if JSON_DIAGNOSTICS + #include // accumulate +#endif +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2016 - 2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_23) && !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus > 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG > 202002L) + #define JSON_HAS_CPP_23 + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG > 201703L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201402L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus > 201103L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifndef JSON_HAS_STATIC_RTTI + #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 + #define JSON_HAS_STATIC_RTTI 1 + #else + #define JSON_HAS_STATIC_RTTI 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + /* NOLINTNEXTLINE(modernize-type-traits) we use C++11 */ \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + /* NOLINTNEXTLINE(modernize-avoid-c-arrays) we don't want to depend on */ \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType, \ + class CustomBaseClass> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = !nlohmann_json_j.is_null() ? nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1) : nlohmann_json_default_obj.v1; + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.11.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.11.3 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_type_non_intrusive/ +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + friend void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + friend void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + template::value, int> = 0> \ + void from_json(const BasicJsonType& nlohmann_json_j, Type& nlohmann_json_t) { nlohmann::from_json(nlohmann_json_j, static_cast(nlohmann_json_t)); const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE +@since version 3.12.0 +@sa https://json.nlohmann.me/api/macros/nlohmann_define_derived_type/ +*/ +#define NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, BaseType, ...) \ + template::value, int> = 0> \ + void to_json(BasicJsonType& nlohmann_json_j, const Type& nlohmann_json_t) { nlohmann::to_json(nlohmann_json_j, static_cast(nlohmann_json_t)); NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } + +// inspired from https://stackoverflow.com/a/26745591 +// allows calling any std function as if (e.g., with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // char_traits +#include // tuple +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.12.0 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector, // cppcheck-suppress syntaxError + class CustomBaseClass = void> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +///////////////// +// char_traits // +///////////////// + +// Primary template of char_traits calls std char_traits +template +struct char_traits : std::char_traits +{}; + +// Explicitly define char traits for unsigned char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = unsigned char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +// Explicitly define char traits for signed char since it is not standard +template<> +struct char_traits : std::char_traits +{ + using char_type = signed char; + using int_type = uint64_t; + + // Redefine to_int_type function + static int_type to_int_type(char_type c) noexcept + { + return static_cast(c); + } + + static char_type to_char_type(int_type i) noexcept + { + return static_cast(i); + } + + static constexpr int_type eof() noexcept + { + return static_cast(std::char_traits::eof()); + } +}; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& +is_complete_type < +detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template