odem-rs-core 0.1.0

Core components of the ODEM-rs simulation framework
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! The `job` module supplies integrated threads of execution, known as
//! [`Job`], within the context of the simulation library.
//!
//! # Overview
//!
//! Jobs represent the combination of a [`Continuation`] and a [`Future`],
//! allowing them to share state with other related jobs of the same [`Agent`].
//! Unlike continuations, which only support simple *success*/*failure* return
//! values, jobs record their actual return value. This enables their creator
//! to retrieve it upon termination.
//!
//! Jobs may also be terminated prematurely, removing them from the simulation
//! calendar, releasing resources, and recording their result as a *failure* for
//! any interested parties.
//!
//! # Examples
//!
//! Creating and activating a simple job in a simulation context:
//!
//! ```
//! # use odem_rs_core::{simulator::Sim, job::Job};
//! # use core::pin::pin;
//! async fn sim_main(sim: &Sim) {
//!     // create and initialize a local variable
//!     let c = 3;
//!
//!     // create a job referring to it and the simulation context
//!     let fib = pin!(Job::new(async {
//!         for i in 0..c {
//!             println!("Hello {i}");
//!             sim.advance(1.0).await;
//!         }
//!     }));
//!
//!     // activate the job
//!     sim.activate(fib);
//!
//!     // pass time
//!     sim.advance((c + 1) as f64).await;
//! }
//! ```
//!
//! [`Agent`]: crate::agent::Agent

use core::{
	any::Any,
	cell::RefCell,
	fmt,
	future::{Future, IntoFuture, Pending},
	marker::PhantomData,
	mem::ManuallyDrop,
	panic::Location,
	pin::Pin,
	task::{Context, Poll},
};

use crate::{
	Active, Dispatch, ExitStatus,
	config::{Config, DefaultConfig},
	continuation::{Continuation, Label, Share, erased::State, token},
	error,
	fsm::*,
	ptr::{AsIrc, IntrusivelyCounted, Irc, IrcBox, Lease, LeasedMut},
	simulator::{Prec, Sim},
};

/* ******************************************************************** Job */

/// Light-weight thread of execution that shares state with other jobs
/// within the same [`Agent`].
///
/// Jobs are fundamentally ([`Continuation`], [`Future`]) pairs that can
/// reference shared state and each other, as long as that state outlives them.
/// Since continuations don't support return values other than a simple
/// *success*/*failure*, jobs erase their actual return value but record it,
/// allowing their parent to retrieve it upon their termination.
///
/// Jobs may also be terminated before completion, which will remove them from
/// the calendar, release all of their resources and record their result as
/// *failure* to any interested party.
///
/// # Examples
/// As stated, Jobs are light-weight and can easily refer to the variables
/// in their lexical scope.
/// ```
/// # use {odem_rs_core::{simulator::Sim, job::Job}, core::pin::pin};
/// async fn sim_main(sim: &Sim) {
///     // create and initialize a local variable
///     let c = 3;
///     
///     // create a job referring to it and the simulation context
///     let job = pin!(Job::new(async {
///         for i in 0..c {
///             println!("Hello {i}");
///             sim.advance(1.0).await;
///         }
///     }));
///     
///     // activate the job
///     sim.activate(job);
///     
///     // pass time
///     sim.advance((c + 1) as f64).await;
/// }
/// ```
///
/// [`Agent`]: crate::agent::Agent
#[pin_project::pin_project(PinnedDrop, !Unpin)]
pub struct Job<'brand, C: ?Sized + Config, F: Future, T = Unchecked> {
	/// A type-erased handle to the future contained within this job.
	#[pin]
	cont: Continuation<'brand, C>,
	/// The return-type-erased future instance representing the inner state
	/// of this job.
	#[pin]
	state: RefCell<Inner<F, T>>,
}

impl<C: ?Sized + Config, F: Future> Job<'static, C, F> {
	/// Creates a new job with a sequence of actions, expressed as a [`Future`].
	#[track_caller]
	pub fn new<'p, A>(actions: A) -> Lease<'p, Self>
	where
		A: IntoFuture<IntoFuture = F>,
	{
		Job::build().with_actions(actions).finish()
	}
}

impl Job<'static, DefaultConfig, Pending<()>> {
	/// Creates and returns a [Builder] for jobs, that is useful if complex
	/// initialization is required.
	pub const fn build() -> Builder {
		Builder::new()
	}
}

impl<C: ?Sized + Config, F: Future, T> Job<'static, C, F, T> {
	/// Used during startup of a simulation run to initialize the root job.
	pub(crate) fn boot<'p>(
		this: Pin<LeasedMut<'p, Self>>,
		share: Pin<&'p Share<C>>,
	) -> Puck<'p, C, F, T>
	where
		T: Settle<F::Output>,
	{
		// create a reference counted type
		let mut this = Irc::new(this);

		// set the most-specialized vptr for the continuation
		unsafe {
			let vptr = Irc::into_raw(this);
			this = Irc::from_raw(vptr);
			this.cont.set_vptr(vptr);
		}

		this.get_pin_mut().unwrap().brand(move |job, once| {
			let born = job.token(once).into_born().unwrap();

			// bind the shared agent data to it
			unsafe { job.bind(born, share.get_ref()) };
		});

		// initialize the pinned job reference
		Puck(this, PhantomData)
	}
}

impl<'brand, C: ?Sized + Config, F: Future, T> Job<'brand, C, F, T> {
	/// Sets the precedence of the job.
	pub fn set_prec(&self, prec: Prec) {
		self.cont.set_prec(prec);
	}

	/// Returns a copy of the job's [`State`].
	pub fn state(&self) -> State {
		self.cont.state().borrow().erased()
	}

	/// Extracts the return value if the job is terminated.
	pub fn result(&self) -> Result<F::Output, error::NotDone> {
		self.brand(|job, once| Ok(job.inner_result(job.token(once).into_done()?).1))
	}

	/// Aborts the execution of this job, removing it from the calendar,
	/// dropping the inner future and the return value if applicable.
	pub fn abort(&self) {
		self.brand(|job, once| {
			job.inner_abort(job.token(once));
		});
	}

	/// Converts the specific brand into a generic brand, breaking the
	/// connection with the equally branded token.
	pub fn detach(&self) -> &Job<'static, C, F, T> {
		// SAFETY: the branding has no impact regarding the object layout
		// and over-counting the number of token can not be source of unsafety.
		unsafe { core::mem::transmute(self) }
	}

	/// Returns an enumeration copy of the internal [State](token::State).
	pub fn token(&self, once: Ephemeral<'brand>) -> token::State<'brand> {
		self.cont.token(once)
	}

	/// Returns an exclusive reference to the finalizer if in state [`Born`].
	///
	/// [`Born`]: token::Born
	pub fn finalizer(self: Pin<&mut Self>, born: &token::Born<'brand>) -> Pin<&mut T> {
		let _ = born;

		// SAFETY: mutable access to the finalizer is unproblematic as long as
		// the job hasn't been activated.
		unsafe { self.map_unchecked_mut(move |job| &mut *job.state.get_mut().future.1) }
	}

	/// Aborts the execution of this job, removing it from the calendar,
	/// dropping the inner future and the return value if applicable.
	fn inner_abort(&self, state: token::State<'brand>) -> token::Gone<'brand> {
		use token::State::*;

		// drop impls should not be able to perform further continuation transitions
		// but we better check to be sure
		let task = &self.cont;

		// set the correct span
		let _span = task.enter_span();

		// analyze the state
		let once: Ephemeral<'_> = match state {
			// the future has already been dropped -> quit
			Gone(gone) => return gone,
			// the return value is pending -> drop it and quit
			Done(done) => return self.inner_result(done).0,
			// the job is scheduled -> remove it from the calendar
			Next(next) => task.deschedule(next).into(),
			// the job is active -> remove it from the active slot
			Busy(busy) => task.deactivate(busy).into(),
			// the job is born or idle -> drop the future and transition
			state @ (Born(_) | Idle(_)) => state.into(),
		};

		// drop the future before performing extra transitions to prevent
		// undefined behavior in user-defined drop impls that rely on the
		// current continuation state
		let (once, ()) = self.debrand(once, |job| unsafe {
			job.state.borrow_mut().unchecked_drop();
		});

		// perform the final transition into the `Gone`-state
		let gone = match task.token(once) {
			Born(born) => task.state().transition(born, Err(crate::Failure)),
			Idle(idle) => task.state().transition(idle, Err(crate::Failure)),
			state => unreachable!(
				"expected task to be 'Born' or 'Idle' but it is \
				 in state '{:?}' instead",
				state.erased()
			),
		};

		// now reactivate pending continuations
		task.wake_pending();

		// return the corresponding token to the caller
		gone
	}

	/// Extracts the return value of a terminated job.
	fn inner_result(&self, done: token::Done<'brand>) -> (token::Gone<'brand>, F::Output) {
		let task = &self.cont;
		let rc = task.branded_result(&done);

		// set the correct span
		let _span = task.enter_span();

		// SAFETY: we know that the result has been written and not been read
		// in state 'Done'
		unsafe {
			(
				task.state().transition(done, rc),
				self.state
					.borrow_mut()
					.unchecked_result()
					.unwrap_unchecked(),
			)
		}
	}

	/// Binds shared data to an unbound job.
	///
	/// # Safety
	/// The caller has to ensure that the shared-data-reference outlives the
	/// (active) part of the continuations' life.
	pub(crate) unsafe fn bind(
		self: Pin<&mut Self>,
		born: token::Born<'brand>,
		share: &Share<C>,
	) -> token::Idle<'brand> {
		unsafe { self.project().cont.bind(born, share) }
	}
}

impl<'b, C: ?Sized + Config, F: Future, T> Stateful for Job<'b, C, F, T> {
	type Brand = &'b ();

	unsafe fn enter(&self) {
		unsafe {
			self.cont.enter();
		}
	}

	unsafe fn leave(&self) {
		unsafe {
			self.cont.leave();
		}
	}
}

impl<'b, C: ?Sized + Config, F: Future, T> Rebrand<'b> for Job<'b, C, F, T> {
	type Kind<'a> = Job<'a, C, F, T>;
}

impl<C: ?Sized + Config, F: Future, T> fmt::Debug for Job<'_, C, F, T> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut s = f.debug_struct("Job");
		s.field("continuation", &self.cont)
			.field("future", &core::any::type_name::<F>())
			.finish()
	}
}

impl<C: ?Sized + Config, F: Future, T: Settle<F::Output>> Dispatch for Job<'_, C, F, T> {
	fn poll(self: Pin<&Self>, cx: &mut Context<'_>) -> Poll<ExitStatus> {
		assert!(
			self.state().is_busy(),
			"only active continuations can be polled"
		);

		let mut state = self.state.borrow_mut();

		// SAFETY: self is pinned and access to future is defined in state Busy
		unsafe { Pin::new_unchecked(&mut *state.future.0) }
			.poll(cx)
			.map(move |rv| {
				// SAFETY: the future just terminated
				unsafe { state.unchecked_terminate(rv) }
			})
	}
}

impl<C: ?Sized + Config, F: Future, T: Settle<F::Output>> Active<C> for Job<'static, C, F, T> {
	type Output = F::Output;
	type Puck<'p>
		= Puck<'p, C, F, T>
	where
		Self: 'p;

	fn bind<'p>(this: Pin<LeasedMut<'p, Self>>, sctx: &'p Share<C>) -> Self::Puck<'p> {
		let mut irc = Irc::new(this);

		irc.get_pin_mut().unwrap().brand(move |mut job, once| {
			let born = job.token(once).into_born().unwrap();

			// SAFETY: the shared data of the root-job outlives the
			// newly bound job, because jobs have to terminate
			// before their agent does, which is enforced by the
			// borrow-checker
			unsafe {
				job.as_mut().bind(born, sctx);
			}
		});

		Puck(irc, PhantomData)
	}
}

// SAFETY: the `IrcBox`-method points to an inner `IrcBox`.
unsafe impl<'brand, C, F, T> IntrusivelyCounted for Job<'brand, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
{
	type Inner = <Continuation<'brand, C> as IntrusivelyCounted>::Inner;

	fn irc_box(&self) -> &IrcBox<Self::Inner> {
		self.cont.irc_box()
	}
}

impl<'brand, C, F, T> AsRef<Continuation<'brand, C>> for Job<'brand, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
{
	fn as_ref(&self) -> &Continuation<'brand, C> {
		&self.cont
	}
}

#[pin_project::pinned_drop]
impl<C: ?Sized + Config, F: Future, T> PinnedDrop for Job<'_, C, F, T> {
	fn drop(self: Pin<&mut Self>) {
		// prevent `reclaim` from being called, even if the reference counter
		// drops to zero due to `abort`; creating the mutable reference would be
		// undefined behavior, even if it isn't used
		self.cont.clear_vptr();

		// abort the execution without running reclaim
		self.abort();
	}
}

/* ********************************************************************* Puck */

/// An exclusive reference to a pinned [`Job`].
///
/// The underlying [`Continuation`] does not expire at the end of its scope but
/// is continued until it either terminates normally or its destructor is
/// executed. This is safe because pinning guarantees that the job will not be
/// moved before it is dropped.
pub struct Puck<'p, C: ?Sized + Config, F: Future, T = Unchecked>(
	Irc<Job<'static, C, F, T>>,
	PhantomDrop<Pin<&'p mut Job<'static, C, F, T>>>,
);

impl<C: ?Sized + Config, F: Future, T> Puck<'_, C, F, T> {
	/// Returns a reference to the [shared context](Share) bound to this job.
	pub fn share(&self) -> &Share<C> {
		// SAFETY: Pucks can only be created during initialization, after
		// which they have shared data bound to them
		unsafe { self.0.cont.share().unwrap_unchecked() }
	}

	/// Terminates the referenced job prematurely.
	///
	/// This method consumes the reference to prevent it from being called twice
	/// or used to extract the return value later.
	pub fn abort(self) {
		self.0.abort();
	}
}

impl<C, F, T> fmt::Debug for Puck<'_, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
	T: Settle<F::Output>,
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl<C, F, T> crate::Puck<C> for Puck<'_, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
	T: Settle<F::Output>,
{
	fn result(&mut self) -> Option<Self::Output> {
		self.0.result().ok()
	}

	fn wake(&mut self) -> Result<(), error::NotIdle> {
		Continuation::wake(Irc::map(self.0.clone(), |inner| &inner.cont))
	}

	fn subject(&self) -> &dyn Any {
		self.share().item()
	}

	fn sim(&self) -> &Sim<C> {
		self.share().sim()
	}

	fn label(&self) -> Label {
		self.share().label()
	}

	fn time(&self) -> Option<C::Time> {
		self.0.cont.time()
	}

	fn rank(&self) -> C::Rank {
		self.share().rank()
	}
	
	fn prec(&self) -> Prec {
		self.0.cont.prec()
	}

	fn state(&self) -> State {
		self.0.cont.state().borrow().erased()
	}

	fn location(&self) -> &'static Location<'static> {
		self.0.cont.location()
	}
}

impl<C, F, T> From<Puck<'_, C, F, T>> for Irc<Job<'static, C, F, T>>
where
	C: ?Sized + Config,
	F: Future,
	T: Settle<F::Output>,
{
	fn from(value: Puck<'_, C, F, T>) -> Self {
		value.0
	}
}

impl<C, F, T> AsRef<Continuation<'static, C>> for Puck<'_, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
	T: Settle<F::Output>,
{
	fn as_ref(&self) -> &Continuation<'static, C> {
		&self.0.cont
	}
}

impl<C, F, T> AsIrc<Continuation<'static, C>> for Puck<'_, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
	T: Settle<F::Output>,
{
	fn as_irc(&self) -> Irc<Continuation<'static, C>> {
		Irc::map(self.0.clone(), |inner| &inner.cont)
	}
}

impl<C, F, T> IntoFuture for Puck<'_, C, F, T>
where
	C: ?Sized + Config,
	F: Future,
	T: Settle<F::Output>,
{
	type Output = F::Output;
	type IntoFuture = crate::ops::Join<C, Self>;

	#[inline]
	fn into_future(self) -> Self::IntoFuture {
		crate::ops::join(self)
	}
}

/* **************************************** Return-Type-Erased Future Adapter */

/// Internal helper type erasing the return type of future.
///
/// This generic type is used to implement the [`Future`] trait with an
/// [`Output`](Future::Output) of `Result<(),()>` but allows extraction of the
/// result using its methods.
///
/// The type is implemented as a union to save space, because either the future
/// is still pending (and there is no result yet) or it is ready (and it doesn't
/// need a future anymore).
union Inner<F: Future, T> {
	/// A future and finalization routine.
	///
	/// The future still contains a user-defined return type but the [`Settle`]
	/// routine knows how to convert it into a result of type [`ExitStatus`].
	/// The pair is used to erase the return-type of the future.
	future: (ManuallyDrop<F>, ManuallyDrop<T>),
	/// The result of the future stored after its termination.
	result: ManuallyDrop<Option<F::Output>>,
}

impl<F: Future, T> Inner<F, T> {
	/// Initializes a new return-type-erased instance from a future returning
	/// a `Result`.
	#[inline]
	const fn new(actions: F, settle: T) -> Self {
		Inner {
			future: (ManuallyDrop::new(actions), ManuallyDrop::new(settle)),
		}
	}

	/// Unconditionally (and unsafely) drops the inner future.
	///
	/// # Safety
	/// The caller is responsible for calling this method not more than once
	/// and only if the future hasn't terminated.
	#[inline]
	unsafe fn unchecked_drop(&mut self) {
		unsafe {
			ManuallyDrop::drop(&mut self.future.0);
			ManuallyDrop::drop(&mut self.future.1);
		}
	}

	/// Unconditionally (and unsafely) returns the result of the inner future.
	///
	/// # Safety
	/// The caller is responsible for calling this method only after the future
	/// has terminated, but it is allowed to be called multiple times.
	#[inline]
	unsafe fn unchecked_result(&mut self) -> Option<F::Output> {
		unsafe { self.result.take() }
	}

	/// Unconditionally (and unsafely) drops the inner future and writes out
	/// the result.
	///
	/// # Safety
	/// The caller is responsible for only calling this method once at the end
	/// of the future's life.
	#[inline]
	unsafe fn unchecked_terminate(&mut self, result: F::Output) -> ExitStatus
	where
		T: Settle<F::Output>,
	{
		unsafe {
			// prepare a drop guard to ensure that the result is written back even
			// in case of a panic by `settle` or `drop`
			let mut guard = scopeguard::guard((self, result), |(this, result)| {
				this.result = ManuallyDrop::new(Some(result));
			});

			// move the finalizer out of the state before calling any functions
			// that may panic in order to prevent resource leaks
			let term = ManuallyDrop::take(&mut guard.0.future.1);

			// carefully drop the pinned future without moving it
			ManuallyDrop::drop(&mut guard.0.future.0);

			// call the finalizer
			term.settle(&mut guard.1)
		}
	}
}

/* ************************************************ Canonical Future Adapters */

/// A trait for converting the result of a [Job] into an [ExitStatus].
///
/// The trait has a blanket implementation for [`FnOnce`]-closures but can
/// also be further specialized for user-defined types if needed.
pub trait Settle<R> {
	/// Method hook that is called once a job completes with a return value.
	/// The return value of this method indicates whether the result is counted
	/// as success (`Ok`) or failure (`Err`).
	fn settle(self, result: &mut R) -> ExitStatus;
}

// blanket implementation for closures
impl<R, F> Settle<R> for F
where
	F: FnOnce(&mut R) -> ExitStatus,
{
	fn settle(self, result: &mut R) -> ExitStatus {
		self(result)
	}
}

/// Finalization adapter that converts `Poll::Ready` values into the `Ok`
/// variant of a `Result<Success,Failure>`.
pub struct Unchecked;

impl<R> Settle<R> for Unchecked {
	fn settle(self, _result: &mut R) -> ExitStatus {
		Ok(crate::Success)
	}
}

/// Finalization adapter that converts `Poll::Ready` values into an
/// [`ExitStatus`] for `bool`, [`Option`], and [`Result`], using the
/// `Ok`-variant for `true`, `Some`, and `Ok` respectively, and the `Err`
/// variant otherwise.
pub struct Checked;

impl Settle<bool> for Checked {
	fn settle(self, result: &mut bool) -> ExitStatus {
		if *result {
			Ok(crate::Success)
		} else {
			Err(crate::Failure)
		}
	}
}

impl<R, T> Settle<Result<R, T>> for Checked {
	fn settle(self, result: &mut Result<R, T>) -> ExitStatus {
		if result.is_ok() {
			Ok(crate::Success)
		} else {
			Err(crate::Failure)
		}
	}
}

impl<T> Settle<Option<T>> for Checked {
	fn settle(self, result: &mut Option<T>) -> ExitStatus {
		if result.is_some() {
			Ok(crate::Success)
		} else {
			Err(crate::Failure)
		}
	}
}

/* ************************************************************ Job Builder */

/// Builder-type providing support to configuring jobs in more detail.
///
/// # Examples
/// ```
/// # use {odem_rs_core::{simulator::{Sim, Prec}, job::Job}, core::pin::pin};
/// # async fn sim_main(sim: &Sim) {
///     # let job =
/// Job::build()                       // create builder
///     .with_actions(async { true })  // specify lifecycle
///     .with_precedence(Prec::new())  // initialize precedence
///     .checked()                     // store result as exit code
///     .finish()                      // instantiate job
///     # ;
///     # sim.activate(pin!(job));
/// # }
/// ```
pub struct Builder<const R: bool = false, F = (), S = Unchecked> {
	future: F,
	location: Option<&'static Location<'static>>,
	finalizer: S,
	precedence: Prec,
}

impl Builder {
	/// Constructs a new (default) Builder.
	pub const fn new() -> Self {
		Builder {
			future: (),
			location: None,
			finalizer: Unchecked,
			precedence: Prec::new(),
		}
	}

	/// Constructs a new (default) Builder
	pub const fn root() -> Builder<true> {
		Builder {
			future: (),
			location: None,
			finalizer: Unchecked,
			precedence: Prec::new(),
		}
	}
}

impl<const R: bool, S> Builder<R, (), S> {
	/// Sets a future for the lifecycle of the [`Job`].
	///
	/// This method also sets the source code [`Location`] if it isn't set
	/// explicitly through [`with_location`].
	///
	/// [`with_location`]: Builder::with_location
	#[track_caller]
	pub fn with_actions<F: IntoFuture>(self, future: F) -> Builder<R, F, S> {
		let Builder {
			location,
			finalizer,
			precedence,
			..
		} = self;

		Builder {
			future,
			location: Some(location.unwrap_or(Location::caller())),
			finalizer,
			precedence,
		}
	}
}

impl<const R: bool, F> Builder<R, F> {
	/// Sets a user-defined [`Settle`] that is run once the lifecycle of the
	/// [`Job`] terminates.
	pub fn with_finalizer<S>(self, finalizer: S) -> Builder<R, F, S> {
		let Builder {
			future,
			location,
			precedence,
			..
		} = self;

		Builder {
			future,
			location,
			finalizer,
			precedence,
		}
	}

	/// Sets a specific [`Settle`] routine that is used to convert a `bool`,
	/// [`Option`], or [`Result`] return type into an [`ExitStatus`] that may
	/// be observed by other agents or jobs.
	pub fn checked(self) -> Builder<R, F, Checked> {
		self.with_finalizer(Checked)
	}
}

impl<const R: bool, F, S> Builder<R, F, S> {
	/// Sets the [Precedence](Prec) of the [`Job`].
	pub const fn with_precedence(mut self, precedence: Prec) -> Self {
		self.precedence = precedence;
		self
	}

	/// Sets an explicit source-code [`Location`] for the [`Job`].
	///
	/// Not setting the location will use the location during [`with_actions`].
	///
	/// [`with_actions`]: Builder::with_actions
	pub const fn with_location(mut self, location: &'static Location<'static>) -> Self {
		self.location = Some(location);
		self
	}
}

impl<const R: bool, F: IntoFuture, S: Settle<F::Output>> Builder<R, F, S> {
	/// Finalizes the construction of the [`Job`] and returns it.
	pub fn finish<'p, C>(self) -> Lease<'p, Job<'static, C, F::IntoFuture, S>>
	where
		C: ?Sized + Config,
	{
		let location = self.location.unwrap();

		// create a new span if it's not a root fiber
		#[cfg(feature = "tracing")]
		let _span = if R {
			tracing::Span::current()
		} else {
			tracing::error_span!("Job", line = location.line()).or_current()
		}
		.entered();

		Lease::new(Job {
			cont: Continuation::new(self.precedence, location),
			state: RefCell::new(Inner::new(self.future.into_future(), self.finalizer)),
		})
	}
}

impl Default for Builder {
	fn default() -> Self {
		Self::new()
	}
}

/* ******************************************************* PhantomDrop helper */

/// This type-alias combines [`PhantomData`] with a Drop-check, ensuring that
/// even phantom types that don't implement the Drop traits themselves present
/// like they would. This is necessary to prevent code like in the following
/// example to compile which would lead to a runtime error due to increased
/// reference counts during drop.
///
/// ```compile_fail,E0716
/// # use odem_rs_core::{simulator::Sim, job::Job};
/// # use core::pin::pin;
///
/// async fn sim_main(sim: &Sim) {
///     let puck = sim.activate(pin!(Job::new(async {})));
/// }
/// ```
type PhantomDrop<T> = PhantomData<PhantomDropInner<T>>;

/// Newtype wrapping a `T` and explicitly implementing the [Drop]-trait.
struct PhantomDropInner<T: ?Sized>(T);

impl<T: ?Sized> Drop for PhantomDropInner<T> {
	fn drop(&mut self) {}
}