nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
Documentation
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Real C11 (`-std=c11 -Werror`) and C++20 (`-std=c++20 -Werror -fsanitize=address,undefined`)
//! bidirectional compile-and-run tests for Direct-First Hybrid FFI (`direct_services.rs`):
//! - C11 ABI header compiles clean under `-std=c11 -Wall -Wextra -Werror` AND with Qt keyword
//!   macros (`-Demit= -Dslots= -Dsignals= -Dforeach=`)
//! - C++20 -> Rust (`DirectMathDirectClient` stateless, `DirectCounterDirectClient` stateful)
//! - Rust -> C++20 (`SystemThemeHostRegistration`, `ClipboardHostRegistration`,
//!   `FileDialogHostRegistration` including background-thread async completion, `cancel`,
//!   non-canonical `SurfaceToken` canonicalization, and `pushOnThemeChanged` / `pushOnChanged`).

mod common;

use std::path::{Path, PathBuf};
use std::process::Command;

use common::rustc::Rustc;
use nativeview_codegen::{HybridTarget, generate_hybrid_target, parse_hybrid_rust_spec};

const DIRECT_SERVICES_SPEC: &str = include_str!("fixtures/direct_services.rs");

fn temp_test_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "nv_direct_cpp_runtime_{tag}_{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("create temp test dir");
    dir
}

fn workspace_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..")
}

const RUST_PROVIDER_SRC: &str = r#"
use std::ffi::c_void;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicI32, Ordering};

use direct_services::{
    ClipboardBackend, ColorScheme, DialogError, DirectClipboardClient, DirectCounterHybrid,
    DirectFileDialogClient, DirectMathHybrid, DirectSystemThemeClient, FileDialogAsyncBackend,
    FileFilter, FilePickerOptions, MotionPreference, NvModClipboardHostOps,
    NvModFileDialogHostOps, NvModSystemThemeHostOps, PickedFile, SystemThemeBackend,
    ThemeSnapshot, decode_clipboard_on_changed, decode_clipboard_on_text_changed,
    decode_system_theme_on_theme_changed,
};
use nativeview_abi::{
    HostServiceId, NvDirectEventSink, NvModStatus, SurfaceId, SurfaceToken,
    NV_DIRECT_EVENT_FLAG_RETAINED,
};

struct MathImpl;
impl DirectMathHybrid for MathImpl {
    fn add(a: i64, b: i64) -> i64 { a + b }
    fn format_label(prefix: &str, value: i32) -> String { format!("{prefix}:{value}") }
    fn xor_bytes(data: &[u8], key: u8) -> Vec<u8> { data.iter().map(|b| b ^ key).collect() }
    fn checked_div(a: i64, b: i64) -> Result<i64, NvModStatus> {
        if b == 0 { Err(NvModStatus::InvalidArg) } else { Ok(a / b) }
    }
    fn parse_non_empty(raw: Option<String>) -> Result<Option<String>, String> {
        match raw {
            None => Ok(None),
            Some(s) if s == "bad" => Err("bad input".to_owned()),
            Some(s) => Ok(Some(s)),
        }
    }
    fn echo_theme(snapshot: ThemeSnapshot) -> ThemeSnapshot { snapshot }
    fn compute_async(
        _request_id: u64,
        seed: u64,
        done: impl FnOnce(Result<String, NvModStatus>) + Send + 'static,
    ) {
        if seed == 0 {
            done(Err(NvModStatus::InvalidArg));
            return;
        }
        if seed == 999_001 {
            let _keep = done;
            panic!("cpp panic before done");
        }
        if seed == 999_002 {
            done(Ok("cpp-before-panic".to_owned()));
            panic!("cpp panic after done");
        }
        std::thread::spawn(move || {
            done(Ok(format!("seed={seed}")));
        });
    }
}
direct_services::export_direct_math_direct!(MathImpl);

struct CounterImpl {
    count: AtomicI32,
    tag: Mutex<Option<String>>,
    theme: Mutex<Option<ThemeSnapshot>>,
}
impl Default for CounterImpl {
    fn default() -> Self {
        Self {
            count: AtomicI32::new(0),
            tag: Mutex::new(None),
            theme: Mutex::new(None),
        }
    }
}
impl DirectCounterHybrid for CounterImpl {
    fn increment(&mut self, delta: i32) -> i32 {
        self.count.fetch_add(delta, Ordering::SeqCst) + delta
    }
    fn get_optional_tag(&mut self) -> Result<Option<String>, NvModStatus> {
        Ok(self.tag.lock().unwrap().clone())
    }
    fn set_tag(&mut self, tag: Option<String>) -> Result<(), NvModStatus> {
        *self.tag.lock().unwrap() = tag;
        Ok(())
    }
    fn set_theme(&mut self, theme: Option<ThemeSnapshot>) -> Option<ThemeSnapshot> {
        let mut g = self.theme.lock().unwrap();
        let prev = *g;
        *g = theme;
        prev
    }
}
direct_services::export_direct_counter_direct!(CounterImpl);

#[derive(Default)]
struct EventCapture {
    theme_events: Vec<(SurfaceToken, ThemeSnapshot, bool)>,
    clip_events: Vec<(SurfaceToken, u64)>,
    clip_text_events: Vec<Option<String>>,
}

unsafe extern "C" fn capture_event_sink(
    ctx: *mut c_void,
    target: SurfaceToken,
    service_id: HostServiceId,
    event_id: u32,
    flags: u32,
    ptr: *const u8,
    len: usize,
) -> i32 {
    let cap = unsafe { &mut *ctx.cast::<Mutex<EventCapture>>() };
    let bytes = if len == 0 { &[][..] } else { unsafe { std::slice::from_raw_parts(ptr, len) } };
    let mut g = cap.lock().unwrap();
    if service_id == direct_services::NV_MOD_SYSTEM_THEME_SERVICE_ID
        && event_id == direct_services::NV_MOD_SYSTEM_THEME_EVENT_ON_THEME_CHANGED
    {
        if let Ok(ev) = decode_system_theme_on_theme_changed(bytes) {
            g.theme_events.push((target, ev.snapshot, (flags & NV_DIRECT_EVENT_FLAG_RETAINED) != 0));
            return 0;
        }
        return NvModStatus::Codec.as_i32();
    }
    if service_id == direct_services::NV_MOD_CLIPBOARD_SERVICE_ID
        && event_id == direct_services::NV_MOD_CLIPBOARD_EVENT_ON_CHANGED
    {
        if let Ok(ev) = decode_clipboard_on_changed(bytes) {
            g.clip_events.push((target, ev.sequence));
            return 0;
        }
        return NvModStatus::Codec.as_i32();
    }
    if service_id == direct_services::NV_MOD_CLIPBOARD_SERVICE_ID
        && event_id == direct_services::NV_MOD_CLIPBOARD_EVENT_ON_TEXT_CHANGED
    {
        if let Ok(ev) = decode_clipboard_on_text_changed(bytes) {
            g.clip_text_events.push(ev.text);
            return 0;
        }
        return NvModStatus::Codec.as_i32();
    }
    NvModStatus::Unsupported.as_i32()
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn nv_test_rust_calls_cpp_hosts(
    theme_ops: *const NvModSystemThemeHostOps,
    clip_ops: *const NvModClipboardHostOps,
    dialog_ops: *const NvModFileDialogHostOps,
    push_events_cb: extern "C" fn(NvDirectEventSink),
) -> i32 {
    let surface = SurfaceToken::new(SurfaceId::new(9, 1), 2);
    let theme = unsafe { DirectSystemThemeClient::from_static_ops(theme_ops, surface) }
        .expect("theme client");
    let snap = theme.current().expect("theme current");
    assert_eq!(snap.scheme, ColorScheme::Dark);
    assert!(snap.high_contrast);
    assert_eq!(snap.motion, MotionPreference::Reduced);
    assert_eq!(snap.accent_rgba, 0x1122_3344);
    theme.set_preferred_scheme(ColorScheme::Light).expect("set scheme");
    assert_eq!(theme.current().expect("updated theme").scheme, ColorScheme::Light);

    // Non-canonical null surface token (surface_id=0, reload_gen=7) must be canonicalized to NULL (0, 0).
    let forged = SurfaceToken { surface_id: SurfaceToken::NULL.surface_id, reload_gen: 7 };
    let theme_forged = unsafe { DirectSystemThemeClient::from_static_ops(theme_ops, forged) }
        .expect("forged client");
    assert_eq!(theme_forged.current().expect("forged current").scheme, ColorScheme::Light);

    let clip = unsafe { DirectClipboardClient::from_static_ops(clip_ops, surface) }
        .expect("clip client");
    assert_eq!(clip.read_text().expect("initially none"), None);
    clip.write_text("").expect("write empty");
    assert_eq!(clip.read_text().expect("read empty"), Some(String::new()));
    clip.write_text("café 🚀").expect("write utf8");
    assert_eq!(clip.read_text().expect("read utf8"), Some("café 🚀".to_owned()));
    clip.write_bytes("application/octet-stream", &[1, 2, 3, 255]).expect("write bytes");
    assert_eq!(
        clip.read_bytes("application/octet-stream").expect("read bytes"),
        Some(vec![1, 2, 3, 255])
    );
    assert_eq!(clip.read_bytes("missing/mime").expect("missing mime"), None);
    clip.clear().expect("clear");
    assert_eq!(clip.read_text().expect("after clear"), None);

    // Optional slot NULL -> Unsupported.
    let mut null_clear_ops = unsafe { *clip_ops };
    null_clear_ops.clear = None;
    let clip_no_clear = unsafe { DirectClipboardClient::from_static_ops(&null_clear_ops, surface) }
        .expect("clip without clear");
    assert_eq!(clip_no_clear.clear(), Err(NvModStatus::Unsupported));

    // Async FileDialog calls completed on a C++ std::thread.
    let dialog = unsafe { DirectFileDialogClient::from_static_ops(dialog_ops, surface) }
        .expect("dialog client");
    let done_files = Arc::new(Mutex::new(None));
    let done_files_c = Arc::clone(&done_files);
    let opts = FilePickerOptions {
        title: Some("Pick Rust files".to_owned()),
        multiple: true,
        filters: vec![FileFilter {
            label: "Rust".to_owned(),
            extensions: vec!["rs".to_owned(), "toml".to_owned()],
        }],
    };
    dialog
        .open_files(opts, Box::new(move |res| {
            *done_files_c.lock().unwrap() = Some(res);
        }))
        .expect("start open_files");
    for _ in 0..200 {
        if done_files.lock().unwrap().is_some() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    let files = done_files.lock().unwrap().take().expect("open_files completed").expect("open_files ok").expect("some files");
    assert_eq!(files, vec![PickedFile {
        path: "/tmp/lib.rs".to_owned(),
        name: "lib.rs".to_owned(),
        size_bytes: 4096,
    }]);

    // Custom negative DialogError::Cancelled (-100) from C++ host.
    let done_err = Arc::new(Mutex::new(None));
    let done_err_c = Arc::clone(&done_err);
    dialog
        .open_files(
            FilePickerOptions { title: Some("CANCEL".to_owned()), multiple: false, filters: vec![] },
            Box::new(move |res| { *done_err_c.lock().unwrap() = Some(res); }),
        )
        .expect("start cancel err");
    for _ in 0..200 {
        if done_err.lock().unwrap().is_some() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    assert_eq!(done_err.lock().unwrap().take(), Some(Err(DialogError::Cancelled)));

    // Async pick_folder returning Ok(None) & Ok(Some(...)).
    let done_folder = Arc::new(Mutex::new(None));
    let done_folder_c = Arc::clone(&done_folder);
    dialog
        .pick_folder(None, Box::new(move |res| { *done_folder_c.lock().unwrap() = Some(res); }))
        .expect("start pick_folder none");
    for _ in 0..200 {
        if done_folder.lock().unwrap().is_some() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
    }
    assert_eq!(done_folder.lock().unwrap().take(), Some(Ok(None)));

    // Push events from C++ host into Rust sink.
    let cap = Box::new(Mutex::new(EventCapture::default()));
    let sink = NvDirectEventSink {
        sink_ctx: (&*cap as *const Mutex<EventCapture>).cast_mut().cast(),
        emit_fn: Some(capture_event_sink),
    };
    push_events_cb(sink);
    let g = cap.lock().unwrap();
    assert_eq!(g.theme_events.len(), 1);
    assert_eq!(g.theme_events[0].1.scheme, ColorScheme::System);
    assert!(g.theme_events[0].2, "retained flag must be set");
    assert_eq!(g.clip_events.len(), 1);
    assert_eq!(g.clip_events[0].1, 42);
    assert_eq!(
        g.clip_text_events,
        vec![None, Some(String::new()), Some("cpp-opt".to_owned())]
    );
    0
}
"#;

const CPP_HARNESS_SRC: &str = r#"
#include <atomic>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <map>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include <vector>

#include "DirectServicesHybridSpec.generated.hpp"

extern "C" int32_t nv_test_rust_calls_cpp_hosts(
    const NvModSystemThemeHostOps* theme_ops,
    const NvModClipboardHostOps* clip_ops,
    const NvModFileDialogHostOps* dialog_ops,
    void (*push_events_cb)(NvDirectEventSink));

using namespace nv::hybrid;

class MockThemeHost final : public HybridSystemThemeHost {
 public:
  ThemeSnapshot current(NvSurfaceToken surface) override {
    if (surface.surface_id == 0u) {
      assert(surface.reload_gen == 0u && "forged non-canonical token must be canonicalized");
    }
    std::lock_guard<std::mutex> lk(mu_);
    return snap_;
  }
  void setPreferredScheme(NvSurfaceToken, ColorScheme scheme) override {
    std::lock_guard<std::mutex> lk(mu_);
    snap_.scheme = scheme;
  }

 private:
  std::mutex mu_;
  ThemeSnapshot snap_{ColorScheme::Dark, true, MotionPreference::Reduced, 0u, 0x11223344u, 1.25f};
};

class MockClipboardHost final : public HybridClipboardHost {
 public:
  std::optional<std::string> readText(NvSurfaceToken) override { return text_; }
  void writeText(NvSurfaceToken, std::string_view text) override { text_ = std::string(text); }
  std::optional<std::vector<uint8_t>> readBytes(NvSurfaceToken, std::string_view mime) override {
    auto it = blobs_.find(std::string(mime));
    if (it == blobs_.end()) return std::nullopt;
    return it->second;
  }
  void writeBytes(NvSurfaceToken, std::string_view mime, std::span<const uint8_t> data) override {
    blobs_[std::string(mime)] = std::vector<uint8_t>(data.begin(), data.end());
  }
  void clear(NvSurfaceToken) override {
    text_.reset();
    blobs_.clear();
  }

 private:
  std::optional<std::string> text_;
  std::map<std::string, std::vector<uint8_t>> blobs_;
};

class MockFileDialogHost final : public HybridFileDialogHost {
 public:
  void openFiles(
      NvSurfaceToken,
      uint64_t,
      const FilePickerOptions& options,
      std::function<void(int32_t, std::optional<std::vector<PickedFile>>)> on_done) override {
    std::thread([options, cb = std::move(on_done)]() mutable {
      if (options.title.has_value() && *options.title == "CANCEL") {
        cb(static_cast<int32_t>(DialogError::Cancelled), std::nullopt);
        return;
      }
      assert(options.multiple);
      assert(options.filters.size() == 1u);
      assert(options.filters[0].label == "Rust");
      std::vector<PickedFile> out;
      out.push_back(PickedFile{"/tmp/lib.rs", "lib.rs", 4096u});
      cb(NV_MOD_OK, std::move(out));
    }).detach();
  }
  void pickFolder(
      NvSurfaceToken,
      uint64_t,
      const std::optional<std::string>& title,
      std::function<void(int32_t, std::optional<std::string>)> on_done) override {
    std::thread([title, cb = std::move(on_done)]() mutable {
      if (!title.has_value()) {
        cb(NV_MOD_OK_NONE, std::nullopt);
      } else if (*title == "BAD_POS") {
        cb(42, std::string("bad-positive-status"));
      } else if (*title == "HOLD") {
        return;
      } else {
        cb(NV_MOD_OK, std::string("/var/tmp/nv-test/") + *title);
      }
    }).detach();
  }
  void cancel(NvSurfaceToken, uint64_t req_id) override {
    last_cancelled_id_.store(req_id, std::memory_order_release);
    cancelled_.fetch_add(1, std::memory_order_relaxed);
  }
  std::atomic<int> cancelled_{0};
  std::atomic<uint64_t> last_cancelled_id_{0};
};

static void push_events_from_cpp(NvDirectEventSink sink) {
  const NvSurfaceToken target{9u, 2u};
  const ThemeSnapshot snap{ColorScheme::System, false, MotionPreference::Full, 0u, 0xAABBCCDDu, 1.0f};
  assert(SystemThemeHostRegistration::pushOnThemeChanged(sink, target, snap) == NV_MOD_OK);
  assert(ClipboardHostRegistration::pushOnChanged(sink, target, 42u) == NV_MOD_OK);
  assert(ClipboardHostRegistration::pushOnTextChanged(sink, target, std::nullopt) == NV_MOD_OK);
  assert(ClipboardHostRegistration::pushOnTextChanged(sink, target, std::string("")) == NV_MOD_OK);
  assert(ClipboardHostRegistration::pushOnTextChanged(sink, target, std::string("cpp-opt")) == NV_MOD_OK);
}

int main() {
  // 1. C++20 -> Rust (`impl = "rust"` stateless & stateful).
  DirectMathDirectClient math;
  assert(math.add(17, 25) == 42);
  assert(math.formatLabel("v", -9) == "v:-9");
  const std::vector<uint8_t> raw = {0x10u, 0x20u, 0xFFu};
  const auto xored = math.xorBytes(raw, 0xAAu);
  assert(xored.size() == 3u && xored[0] == 0xBAu && xored[1] == 0x8Au && xored[2] == 0x55u);
  assert(math.checkedDiv(84, 2) == 42);
  bool caught_div_zero = false;
  try { (void)math.checkedDiv(1, 0); } catch (const nv::host::DirectError& e) {
    caught_div_zero = (e.code() == NV_MOD_INVALID_ARG);
  }
  assert(caught_div_zero);
  assert(!math.parseNonEmpty(std::nullopt).has_value());
  assert(math.parseNonEmpty(std::string("")) == std::optional<std::string>(""));
  assert(math.parseNonEmpty(std::string("ok")) == std::optional<std::string>("ok"));
  bool caught_str_err = false;
  try { (void)math.parseNonEmpty(std::string("bad")); } catch (const nv::host::DirectError& e) {
    caught_str_err = (std::string(e.what()) == "bad input");
  }
  assert(caught_str_err);
  const ThemeSnapshot tin{ColorScheme::Dark, true, MotionPreference::Reduced, 0u, 0xCAFEBABEu, 1.5f};
  const ThemeSnapshot tout = math.echoTheme(tin);
  assert(tout.scheme == tin.scheme && tout.highContrast == tin.highContrast &&
         tout.motion == tin.motion && tout.accentRgba == tin.accentRgba && tout.fontScale == tin.fontScale);

  std::atomic<int> async_done{0};
  std::string async_val;
  math.computeAsync(77u, 9001u, [&](int32_t st, std::string v) {
    assert(st == NV_MOD_OK);
    async_val = std::move(v);
    async_done.store(1, std::memory_order_release);
  });
  for (int i = 0; i < 200 && async_done.load(std::memory_order_acquire) == 0; ++i) {
    std::this_thread::sleep_for(std::chrono::milliseconds(5));
  }
  assert(async_done.load(std::memory_order_acquire) == 1 && async_val == "seed=9001");

  // Panic-in-async before and after `done`: must invoke callback exactly once with zero double-free under ASan.
  std::atomic<int> panic_before_calls{0};
  int32_t panic_before_st = 0;
  math.computeAsync(78u, 999001u, [&](int32_t st, std::string) {
    panic_before_st = st;
    panic_before_calls.fetch_add(1, std::memory_order_acq_rel);
  });
  assert(panic_before_calls.load(std::memory_order_acquire) == 1 && panic_before_st == NV_MOD_INTERNAL_ERROR);

  std::atomic<int> panic_after_calls{0};
  std::string panic_after_val;
  math.computeAsync(79u, 999002u, [&](int32_t st, std::string v) {
    assert(st == NV_MOD_OK);
    panic_after_val = std::move(v);
    panic_after_calls.fetch_add(1, std::memory_order_acq_rel);
  });
  assert(panic_after_calls.load(std::memory_order_acquire) == 1 && panic_after_val == "cpp-before-panic");

  // P0-2: Concurrent race stress between DirectAsyncBox::trampoline (x2) and finish_start + late call.
  for (uint64_t iter = 0; iter < 200u; ++iter) {
    std::atomic<int> race_calls{0};
    auto race_box = nv::host::DirectAsyncBox<
        std::function<void(uint64_t, int32_t, const uint8_t*, size_t)>>::create(
        [&](uint64_t, int32_t, const uint8_t*, size_t) {
          race_calls.fetch_add(1, std::memory_order_acq_rel);
        });
    void* raw_ctx = decltype(race_box)::element_type::retain_raw(race_box);
    static constexpr uint8_t ok_bytes[2] = {'o', 'k'};
    std::thread t1([raw_ctx, iter]() {
      decltype(race_box)::element_type::trampoline(raw_ctx, iter, NV_MOD_OK, ok_bytes, 2u);
    });
    std::thread t2([raw_ctx, iter]() {
      decltype(race_box)::element_type::trampoline(raw_ctx, iter, NV_MOD_OK, ok_bytes, 2u);
    });
    race_box->finish_start(raw_ctx, iter, NV_MOD_INTERNAL_ERROR);
    t1.join();
    t2.join();
    // Late duplicate after resolution must be a safe no-op with zero UAF.
    decltype(race_box)::element_type::trampoline(raw_ctx, iter, NV_MOD_OK, ok_bytes, 2u);
    assert(race_calls.load(std::memory_order_acquire) == 1);
  }

  DirectCounterDirectClient counter;
  assert(counter.increment(5) == 5);
  assert(counter.increment(-2) == 3);
  assert(!counter.getOptionalTag().has_value());
  counter.setTag(std::string("beta"));
  assert(counter.getOptionalTag() == std::optional<std::string>("beta"));
  counter.setTag(std::nullopt);
  assert(!counter.getOptionalTag().has_value());
  assert(!counter.setTheme(tin).has_value());
  const auto prev = counter.setTheme(std::nullopt);
  assert(prev.has_value() && prev->accentRgba == 0xCAFEBABEu);

  // 2. Rust -> C++20 (`impl = "host"` registrations).
  MockThemeHost theme_host;
  MockClipboardHost clip_host;
  MockFileDialogHost dialog_host;
  SystemThemeHostRegistration theme_reg(theme_host);
  ClipboardHostRegistration clip_reg(clip_host);
  FileDialogHostRegistration dialog_reg(dialog_host);
  assert(nv_test_rust_calls_cpp_hosts(
             theme_reg.ops(), clip_reg.ops(), dialog_reg.ops(), &push_events_from_cpp) == 0);

  // 3. C++20 `wire_to_direct_file_dialog`: explicit request_id round-trip, cancel, & bad positive status.
  {
    struct WireCapture {
      std::mutex mu;
      bool done = false;
      uint64_t req_id = 0;
      int32_t status = 0;
      std::vector<uint8_t> payload;
    };
    auto on_wire_done = [](void* ctx, uint64_t req_id, int32_t status, const uint8_t* ptr, size_t len) noexcept {
      auto* cap = static_cast<WireCapture*>(ctx);
      std::lock_guard<std::mutex> lk(cap->mu);
      cap->done = true;
      cap->req_id = req_id;
      cap->status = status;
      cap->payload.assign(len ? ptr : nullptr, len ? ptr + len : nullptr);
    };
    const NvSurfaceToken surface{9u, 2u};

    // 3a. Async Some(...) round-trip preserves exact explicit request_id.
    {
      WireCapture cap;
      const uint64_t explicit_id = 0xCAFE1234567890ABULL;
      const std::string title = "wire-ok";
      std::vector<uint8_t> req(1u + title.size());
      req[0] = 1u;
      std::memcpy(req.data() + 1u, title.data(), title.size());
      const int32_t rc = FileDialogHostRegistration::wire_to_direct_file_dialog(
          dialog_reg.ops(), surface, explicit_id, NV_MOD_FILE_DIALOG_METHOD_PICK_FOLDER,
          req.data(), req.size(), on_wire_done, &cap);
      assert(rc == NV_MOD_OK);
      for (int i = 0; i < 400; ++i) {
        {
          std::lock_guard<std::mutex> lk(cap.mu);
          if (cap.done) break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
      }
      std::lock_guard<std::mutex> lk(cap.mu);
      assert(cap.done && cap.req_id == explicit_id && cap.status == NV_MOD_OK);
      const std::string expected = "/var/tmp/nv-test/wire-ok";
      assert(cap.payload.size() == 1u + expected.size() && cap.payload[0] == 1u);
      assert(std::memcmp(cap.payload.data() + 1u, expected.data(), expected.size()) == 0);
    }

    // 3b. Unknown positive status (+42) from async op maps to NV_MOD_CODEC with exact request_id.
    {
      WireCapture cap;
      const uint64_t explicit_id = 0xCAFE56789ABCDEF0ULL;
      const std::string title = "BAD_POS";
      std::vector<uint8_t> req(1u + title.size());
      req[0] = 1u;
      std::memcpy(req.data() + 1u, title.data(), title.size());
      const int32_t rc = FileDialogHostRegistration::wire_to_direct_file_dialog(
          dialog_reg.ops(), surface, explicit_id, NV_MOD_FILE_DIALOG_METHOD_PICK_FOLDER,
          req.data(), req.size(), on_wire_done, &cap);
      assert(rc == NV_MOD_OK);
      for (int i = 0; i < 400; ++i) {
        {
          std::lock_guard<std::mutex> lk(cap.mu);
          if (cap.done) break;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
      }
      std::lock_guard<std::mutex> lk(cap.mu);
      assert(cap.done && cap.req_id == explicit_id && cap.status == NV_MOD_CODEC);
      assert(cap.payload.empty());
    }

    // 3c. Explicit cancel sentinel (method_id == 0) forwards exact cancel_id to MockFileDialogHost::cancel.
    {
      WireCapture cap;
      const uint64_t cancel_id = 0xCAFE999988887777ULL;
      const std::string title = "HOLD";
      std::vector<uint8_t> req(1u + title.size());
      req[0] = 1u;
      std::memcpy(req.data() + 1u, title.data(), title.size());
      assert(FileDialogHostRegistration::wire_to_direct_file_dialog(
                 dialog_reg.ops(), surface, cancel_id, NV_MOD_FILE_DIALOG_METHOD_PICK_FOLDER,
                 req.data(), req.size(), on_wire_done, &cap) == NV_MOD_OK);
      uint8_t cancel_bytes[8];
      for (size_t i = 0; i < 8; ++i) cancel_bytes[i] = static_cast<uint8_t>((cancel_id >> (i * 8u)) & 0xFFu);
      assert(FileDialogHostRegistration::wire_to_direct_file_dialog(
                 dialog_reg.ops(), surface, cancel_id, 0u, cancel_bytes, 8u, on_wire_done, &cap) == NV_MOD_OK);
      assert(dialog_host.last_cancelled_id_.load(std::memory_order_acquire) == cancel_id);
    }
  }

  std::puts("DIRECT_CPP_E2E_OK");
  return 0;
}
"#;

#[test]
fn c11_and_cpp20_direct_ffi_compile_with_qt_macros_and_run_bidirectional_e2e() {
    if !common::require_tool("c++") || !common::require_tool("cc") {
        return;
    }
    let dir = temp_test_dir("e2e");
    let spec = parse_hybrid_rust_spec(DIRECT_SERVICES_SPEC).expect("parse direct_services");
    for target in [HybridTarget::Rust, HybridTarget::Cpp] {
        generate_hybrid_target(&spec, target)
            .expect("generate target")
            .write_to_dir(&dir)
            .expect("write generated");
    }

    let host_cxx_inc = workspace_root().join("packages/core/host-cxx/include");

    // 1. Pure C11 header check under `-std=c11 -Wall -Wextra -Wsign-conversion -Werror` AND Qt `-Demit=` macros.
    let c11_driver = dir.join("check_c11.c");
    std::fs::write(
        &c11_driver,
        "#include \"DirectServicesHybridAbi.generated.h\"\n\
         uint32_t ok(void) {\n\
           uint32_t r = nv_mod_system_theme_unregister(NULL, NULL);\n\
           return r + NV_MOD_SYSTEM_THEME_SERVICE_ID;\n\
         }\n",
    )
    .unwrap();
    let c11 = Command::new("cc")
        .args([
            "-std=c11",
            "-Wall",
            "-Wextra",
            "-Wsign-conversion",
            "-Werror",
            "-Demit=",
            "-Dslots=",
            "-Dsignals=",
            "-Dforeach=",
            "-fsyntax-only",
        ])
        .arg(format!("-I{}", dir.display()))
        .arg(format!("-I{}", host_cxx_inc.display()))
        .arg(&c11_driver)
        .output()
        .expect("run cc");
    assert!(
        c11.status.success(),
        "C11 header failed under -std=c11 + Qt macros:\n{}",
        String::from_utf8_lossy(&c11.stderr)
    );

    // 2. Build Rust staticlib (DirectMath + DirectCounter + Rust-calls-C++-hosts harness).
    let rustc = Rustc::locate();
    let gen_rs = dir.join("direct_services_hybrid.generated.rs");
    let rlib = rustc.build_lib(&dir, "direct_services", &gen_rs);
    let provider_rs = dir.join("provider.rs");
    std::fs::write(&provider_rs, RUST_PROVIDER_SRC).unwrap();
    let staticlib = dir.join("libdirect_cpp_provider.a");
    rustc.build(
        &dir,
        &["--crate-type=staticlib"],
        &[("direct_services", rlib.as_path())],
        &provider_rs,
        &staticlib,
    );

    // 3. Compile & run C++20 bidirectional E2E with Qt macros + ASan/UBSan.
    let cpp_main = dir.join("main.cpp");
    std::fs::write(&cpp_main, CPP_HARNESS_SRC).unwrap();
    let exe = dir.join("direct_cpp_e2e");
    let mut build = Command::new("c++");
    build
        .args([
            "-std=c++20",
            "-Wall",
            "-Wextra",
            "-Werror",
            "-Demit=",
            "-Dslots=",
            "-Dsignals=",
            "-Dforeach=",
            "-fsanitize=address,undefined",
        ])
        .arg(format!("-I{}", dir.display()))
        .arg(format!("-I{}", host_cxx_inc.display()))
        .arg(&cpp_main)
        .arg(&staticlib)
        .arg("-o")
        .arg(&exe);
    if cfg!(target_os = "linux") {
        build.args(["-lpthread", "-ldl", "-lm"]);
    }
    let b_out = build.output().expect("compile C++20 direct E2E");
    assert!(
        b_out.status.success(),
        "C++20 direct E2E compile failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&b_out.stdout),
        String::from_utf8_lossy(&b_out.stderr)
    );

    let run = Command::new(&exe).output().expect("run C++20 direct E2E");
    assert!(
        run.status.success(),
        "C++20 direct E2E failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&run.stdout),
        String::from_utf8_lossy(&run.stderr)
    );
    assert!(
        String::from_utf8_lossy(&run.stdout).contains("DIRECT_CPP_E2E_OK"),
        "missing success marker"
    );

    let _ = std::fs::remove_dir_all(&dir);
}