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
//! Proc macros for asupersync structured concurrency runtime.
//!
//! This crate provides procedural macros that simplify working with the asupersync
//! async runtime's structured concurrency primitives. The macros handle the boilerplate
//! for creating scopes, spawning tasks, joining results, and racing computations.
//!
//! # Available Macros
//!
//! - [`scope!`] - Create a structured concurrency scope
//! - [`spawn!`] - Spawn a task within the current scope
//! - [`join!`] - Join multiple futures, waiting for all to complete
//! - [`join_all!`] - Join multiple futures into an array
//! - [`race!`] - Race multiple futures, returning the first to complete
//! - [`select!`] - Select over heterogeneous branches with an optional `else` arm
//! - [`#[main]`](macro@main) / [`#[test]`](macro@test) - Production runtime entry attributes
//! - [`session_protocol!`] - Generate typestate session protocols
//! - [`conformance`] - Annotate conformance tests
//! - [`lab_test`] / [`explore_seeds`] - Run deterministic lab-runtime tests
//! - [`ProtoMessage`] / [`ProtoOneof`] - Derive the owned protobuf authoring contract
//!
//! # Contract With `asupersync`
//!
//! The root `asupersync` crate re-exports only the supported runtime DSL:
//! `scope!`, `spawn!`, `join!`, `join_all!`, `race!`, and `select!`, and only
//! when the `proc-macros` feature is enabled.
//!
//! This crate also defines `session_protocol!` and `#[conformance]`, but those
//! remain explicit-path macros on `asupersync_macros`; they are not part of the
//! default root macro contract.
//!
//! # Example
//!
//! ```ignore
//! use asupersync_macros::{scope, spawn, join, race};
//!
//! async fn example(cx: &Cx, state: &mut RuntimeState) {
//! scope!(cx, state: state, {
//! let handle1 = spawn!(async { compute_a().await });
//! let handle2 = spawn!(async { compute_b().await });
//!
//! // Wait for both
//! let (result_a, result_b) = join!(handle1, handle2);
//! });
//! }
//! ```
use TokenStream;
use parse_macro_input;
/// Derives the owned `asupersync::grpc::protobuf::ProtoMessage` contract.
///
/// Fields use `#[proto(kind, tag = N)]`, with explicit `optional`,
/// `repeated`, and `packed` modifiers. Maps use
/// `#[proto(map, key = "string", value = "uint64", tag = N)]`; oneofs use an
/// `Option<T>` field annotated with `#[proto(oneof, tags = "N, M")]`.
///
/// Expansion is deterministic and Cargo-only: it invokes no schema compiler
/// and reads no ambient files.
/// Derives the owned `asupersync::grpc::protobuf::ProtoOneof` contract.
///
/// Every enum variant must be a one-value tuple variant with its own
/// `#[proto(kind, tag = N)]` attribute.
/// Runs an async `main` function on an asupersync production runtime.
///
/// Supported signatures:
///
/// ```ignore
/// #[asupersync::main]
/// async fn main() {}
///
/// #[asupersync::main(flavor = "current_thread", workers = 1, budget = 128)]
/// async fn main(cx: &asupersync::Cx) -> Result<(), asupersync::Error> {
/// Ok(())
/// }
/// ```
/// Runs an async test function on an asupersync production runtime.
///
/// This is distinct from [`#[lab_test]`](macro@lab_test): `#[asupersync::test]`
/// uses the production runtime, while `#[lab_test]` uses deterministic lab
/// runtime seed matrices.
/// Creates a structured concurrency scope.
///
/// The `scope!` macro creates an `asupersync::Scope` binding for the
/// current `Cx` region and makes it available as `scope` inside the body.
///
/// Today this is an ergonomic binding helper, not a fresh child-region
/// boundary. For actual child-region ownership and quiescence, call
/// `asupersync::Scope::region` explicitly.
///
/// # Syntax
///
/// ```ignore
/// scope!(cx, {
/// // body with spawned tasks
/// })
/// scope!(cx, state: &mut state, {
/// let _child = spawn!(async { work().await });
/// })
/// ```
///
/// # Arguments
///
/// - `cx` - The capability context (`&Cx`)
/// - `body` - A block containing the scope's work
/// - `state` - Optional runtime state binding used by nested `spawn!` calls
///
/// # Returns
///
/// The result of the scope body.
///
/// # Example
///
/// ```ignore
/// scope!(cx, state: &mut state, {
/// spawn!(async { work_a().await });
/// spawn!(async { work_b().await });
/// // Both tasks are awaited before scope exits
/// })
/// ```
/// Spawns a task within the current scope.
///
/// The `spawn!` macro expands to `asupersync::Scope::spawn_registered`, so it requires
/// ambient `__state` and `__cx` bindings in addition to the target `Scope`.
///
/// The easiest supported path is to use it inside `scope!(..., state: ..., { ... })`.
///
/// # Syntax
///
/// ```ignore
/// spawn!(async { /* work */ })
/// spawn!(async move { /* work with captured values */ })
/// ```
///
/// # Returns
///
/// A `TaskHandle` that can be awaited to get the task's result.
///
/// # Example
///
/// ```ignore
/// let handle = spawn!(async {
/// expensive_computation().await
/// });
/// let result = handle.await;
/// ```
/// Joins multiple futures, waiting for all to complete.
///
/// The `join!` macro polls all branches concurrently inside the enclosing task
/// and returns their outputs as a tuple in input order. A pending branch never
/// blocks ready branches from making progress, so same-duration sleeps complete
/// in one duration rather than the sum of all durations.
///
/// # Syntax
///
/// ```ignore
/// join!(future1, future2, ...)
/// ```
///
/// # Returns
///
/// A tuple of all the futures' results in the order they were specified.
///
/// # Outcome Semantics
///
/// The combined outcome follows the severity lattice:
/// - If all succeed: `Outcome::Ok((r1, r2, ...))`
/// - If any fails: the most severe outcome is propagated
///
/// # Example
///
/// ```ignore
/// let (a, b, c) = join!(
/// fetch_user().await,
/// fetch_profile().await,
/// fetch_settings().await
/// );
/// ```
/// Joins multiple futures into an array, waiting for all to complete.
///
/// The `join_all!` macro is like `join!` but returns an array instead of a
/// tuple. It uses the same concurrent polling expansion, so all branches are
/// driven together within the enclosing task while preserving input order in
/// the returned array.
///
/// # Syntax
///
/// ```ignore
/// join_all!(future1, future2, ...)
/// ```
///
/// # Returns
///
/// An array of all the futures' results in the order they were specified.
/// Since all results must be the same type, this enables easier iteration.
///
/// # Example
///
/// ```ignore
/// let results: [i32; 3] = join_all!(
/// fetch_value(1).await,
/// fetch_value(2).await,
/// fetch_value(3).await
/// );
/// for result in results {
/// println!("{}", result);
/// }
/// ```
/// Races multiple futures, returning the first to complete — **losers are
/// drained**.
///
/// The `race!` macro expands to the drain-correct
/// `asupersync::Cx::race_drained*` family: each branch is
/// spawned as a region task and resolved through
/// `asupersync::Scope::race_all`, so every losing branch is
/// protocol-cancelled **and drained** (awaited to termination) before the macro
/// returns. This is the drain guarantee that differentiates `race!` from a
/// plain drop-the-losers select.
///
/// Because branches run as spawned tasks, each branch and its output must be
/// `Send + 'static`, and `cx` must be a runtime-wired context carrying spawn
/// authority. For a lower-level drop-on-cancel select over non-`'static`
/// inline futures, call `asupersync::Cx::race` directly.
///
/// # Syntax
///
/// ```ignore
/// race!(cx, { future1, future2, ... })
/// race!(cx, { "name" => future1, "other" => future2, ... })
/// race!(cx, timeout: Duration::from_secs(5), { future1, future2, ... })
/// ```
///
/// # Returns
///
/// The result of the winning future.
///
/// # Loser Cleanup
///
/// All non-winning branches are cancelled and drained: the macro does not
/// return until each loser task has terminated, so obligations and finalizers
/// held by a loser are resolved rather than abandoned. (On the `timeout:` path,
/// an elapsed deadline abandons the whole race by drop, matching
/// `asupersync::Cx::race_drained_timeout`.)
///
/// # Example
///
/// ```ignore
/// let result = race!(cx, {
/// primary_service.fetch().await,
/// backup_service.fetch().await,
/// });
/// // One completed; the loser was cancelled AND drained before this returned.
/// ```
/// Selects over heterogeneous branches — **losers are drained** — with an
/// optional non-blocking `else` arm.
///
/// `select!` is the N-ary, heterogeneous member of the race family. Each branch
/// awaits its own future (the branch types may differ) and runs a handler arm;
/// every handler must yield the same result type `R`. It lifts the fixed
/// `Race2`/`Race3`/`Race4` arity ceiling and is the drain-correct alternative
/// to `tokio::select!`.
///
/// # Two forms
///
/// **Blocking, drain-correct** (no `else` arm): each branch is rewritten into
/// `async move { let <pat> = <future>.await; <handler> }`, and the homogeneous
/// per-branch list routes through
/// `asupersync::Cx::race_drained`. The first branch to win
/// resolves the `select!`; every loser is protocol-cancelled **and drained**
/// (awaited to termination) before the macro returns. Resolves to
/// `Result<R, JoinError>`. Branch futures and `R` must be `Send + 'static`, and
/// `cx` must carry spawn authority (`Cx<cap::All>`).
///
/// **Non-blocking default** (trailing `else => <handler>` arm): each branch is
/// polled **exactly once** in source order; the first ready branch wins,
/// otherwise the `else` handler runs immediately. This is the Go-style
/// `default` arm — it never waits, so it does not drain; not-ready branches are
/// dropped. Resolves to `R`.
///
/// # Determinism / tie-break
///
/// Every `select!` is replay-deterministic: the same seed always produces the
/// same winner. The blocking form resolves through the runtime drain engine
/// (`asupersync::Scope::race_all`), which breaks ties among
/// same-turn-ready branches with the lab's **seeded** scheduler RNG — fixed by
/// the seed, not by source position. The `else` form polls in strict **source
/// order** and takes the first ready branch. The `biased` keyword is accepted
/// on the blocking form for `tokio::select!` familiarity and documents that
/// selection is deterministic; it does not impose strict source order — use the
/// `else` form for that.
///
/// # Syntax
///
/// ```ignore
/// // blocking, drain-correct
/// let r = select!(cx, {
/// a = primary.fetch() => use_primary(a),
/// b = backup.fetch() => use_backup(b),
/// })?;
///
/// // explicit source-order tie-break
/// let r = select!(cx, biased, {
/// a = fast() => a,
/// b = slow() => b,
/// })?;
///
/// // non-blocking Go-style default
/// let r = select!(cx, {
/// a = try_recv() => a,
/// else => default_value(),
/// });
/// ```
/// Instruments a function or impl method with a tracing span.
///
/// The generated wrapper uses `asupersync::tracing_compat`, so it creates real
/// spans when `tracing-integration` is enabled and becomes a no-op when tracing
/// is disabled.
///
/// Supported arguments:
///
/// - `name = "custom_name"` overrides the span name
/// - `level = "trace" | "debug" | "info" | "warn" | "error"` sets span level
/// - `skip(arg1, arg2, ...)` excludes arguments from captured fields
///
/// # Examples
///
/// ```ignore
/// use asupersync::tracing_compat::instrument;
///
/// #[instrument]
/// async fn load_user(user_id: u64) -> Result<(), Error> {
/// Ok(())
/// }
///
/// #[instrument(name = "cache_refresh", level = "debug", skip(secret))]
/// fn refresh(secret: &Secret, key: &str) {}
/// ```
/// Marks a test with the specification section and requirement it validates.
///
/// # Syntax
///
/// ```ignore
/// #[conformance(spec = "3.2.1", requirement = "Region close waits for all children")]
/// #[test]
/// fn test_region_close_waits() { /* ... */ }
/// ```
///
/// The macro is validation-only: it checks that `spec` and `requirement` are
/// present and string literals, then leaves the item unchanged.
/// Runs a deterministic lab-runtime test with optional seed matrices.
///
/// Supported function shapes:
///
/// ```ignore
/// #[lab_test]
/// fn raw_lab(lab: &mut asupersync::lab::LabRuntime) {
/// // create tasks, advance virtual time, inspect lab state
/// }
///
/// #[lab_test(seeds = 0..16, chaos)]
/// async fn async_body(cx: &asupersync::cx::Cx) {
/// // run under a root lab task with automatic quiescence/oracle checks
/// }
/// ```
/// Runs a deterministic lab-runtime body across a seed sweep.
///
/// The body is invoked once per seed with a fresh
/// `asupersync::lab::LabRuntime`. The generated test drains each
/// run to quiescence, aggregates trace equivalence-class coverage, and reports
/// failing seeds with replay-friendly reproducer commands.
///
/// Supported arguments:
///
/// - `base = N` or `base_seed = N` sets the first seed
/// - `count = N` sets the number of seeds
/// - `seeds = START..END` uses an exclusive range
/// - `workers = N` or `worker_count = N` sets the lab worker count
/// - `max_steps = N` sets the per-seed step limit
/// - `chaos` enables the light deterministic chaos profile
///
/// # Example
///
/// ```ignore
/// #[explore_seeds(seeds = 0..32, workers = 2)]
/// fn cancellation_matrix(lab: &mut asupersync::lab::LabRuntime) {
/// // build the per-seed scenario; the macro drains and checks it
/// }
/// ```
/// Generates typestate-encoded session types from a protocol DSL.
///
/// The macro takes a protocol specification and generates a module containing
/// message structs, paired session type aliases (initiator + responder), and
/// constructor functions. The responder type is the dual of the initiator:
/// `Send`↔`Recv`, `Select`↔`Offer`.
///
/// # Syntax
///
/// ```ignore
/// session_protocol! {
/// module_name<T> for ObligationVariant {
/// msg MessageName;
/// msg MessageWithFields { field: Type };
///
/// send MessageName => select {
/// send T => end,
/// send OtherMsg => end,
/// }
/// }
/// }
/// ```
///
/// # Body Actions
///
/// - `send Type => body` — send a value, then continue
/// - `recv Type => body` — receive a value, then continue
/// - `select { a, b }` — local choice (becomes `Offer` for responder)
/// - `offer { a, b }` — remote choice (becomes `Select` for responder)
/// - `loop { body }` — recursion point (generates `renew_loop` constructor)
/// - `continue` — jump back to enclosing `loop`
/// - `end` — protocol termination
///
/// # Generated Items
///
/// - `pub mod <name>` containing:
/// - Message structs with `Debug, Clone` (+ `Copy` for unit structs)
/// - `InitiatorSession` type alias
/// - `ResponderSession` type alias
/// - `new_session(channel_id) -> (Chan<Initiator, ...>, Chan<Responder, ...>)`
/// - (if `loop` used) `InitiatorLoop`, `ResponderLoop` type aliases
/// - (if `loop` used) `renew_loop(channel_id)` constructor
///
/// # Example
///
/// ```ignore
/// session_protocol! {
/// lease for Lease {
/// msg AcquireMsg;
/// msg RenewMsg;
/// msg ReleaseMsg;
///
/// send AcquireMsg => loop {
/// select {
/// send RenewMsg => continue,
/// send ReleaseMsg => end,
/// }
/// }
/// }
/// }
/// ```