rogue_machines 0.1.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ //! `RogueMachines::Rogue`: one core `Rogue`, method for method.
2
+ //!
3
+ //! Every mutating method checks frozen first, then converts and checks
4
+ //! everything it was given and looks up every class it will build, before it
5
+ //! calls the core. `arm` and
6
+ //! `disarm` answer with values built by Ruby (`Replaced`, `Disarmed`), so they
7
+ //! run in `matryona_machines`'s clone-then-keep: the core decides on a copy,
8
+ //! the answer is built, and the copy is stored only if the Rogue is neither
9
+ //! frozen (`FrozenError`) nor changed (`RuntimeError`) meanwhile; a raise
10
+ //! while building applies nothing. No `RefCell` borrow is held while Ruby code runs: arguments are
11
+ //! converted first, the core value is copied out under a short borrow, and
12
+ //! only then is an answer built.
13
+
14
+ use std::cell::RefCell;
15
+
16
+ use magnus::typed_data::Obj;
17
+ use magnus::{Error, RModule, Ruby, Value, function, method, prelude::*};
18
+ use matryona_machines::ruby::{Class, SymbolNames, duration, keep};
19
+ use rogue_machines::{Arming, Decision, Disarming, Rogue};
20
+
21
+ use crate::values::{classes, draw, experiment, slot};
22
+
23
+ matryona_machines::symbols! {
24
+ /// What `arm` answers: `:armed`, `:already_armed`, or a `Replaced`.
25
+ Armings for Arming as "an arming" => names_only {
26
+ Armed => "armed",
27
+ Replaced(..) => "replaced",
28
+ AlreadyArmed => "already_armed",
29
+ }
30
+ }
31
+
32
+ matryona_machines::symbols! {
33
+ /// What `disarm` answers: a `Disarmed`, or `:not_armed`.
34
+ Disarmings for Disarming as "a disarming" => names_only {
35
+ Disarmed(..) => "disarmed",
36
+ NotArmed => "not_armed",
37
+ }
38
+ }
39
+
40
+ matryona_machines::symbols! {
41
+ /// What `decide` answers: `:pass`, or an `Inject`.
42
+ Decisions for Decision as "a decision" => names_only {
43
+ Pass => "pass",
44
+ Inject(..) => "inject",
45
+ }
46
+ }
47
+
48
+ #[magnus::wrap(class = "RogueMachines::Rogue", free_immediately, size)]
49
+ struct Wrapper(RefCell<Rogue>);
50
+
51
+ impl Wrapper {
52
+ const fn new() -> Self {
53
+ Self(RefCell::new(Rogue::new()))
54
+ }
55
+
56
+ /// An unfrozen copy holding the same experiments.
57
+ fn dup(&self) -> Self {
58
+ Self(RefCell::new(self.0.borrow().clone()))
59
+ }
60
+
61
+ /// `:armed`, a `Replaced` holding what the slot held, or `:already_armed`.
62
+ fn arm(ruby: &Ruby, this: Obj<Self>, given_slot: Value, given: Value) -> Result<Value, Error> {
63
+ this.check_frozen()?;
64
+ let (slot, experiment) = (slot(ruby, given_slot)?, experiment(ruby, given)?);
65
+ let classes = classes(ruby)?;
66
+ keep(
67
+ ruby,
68
+ this,
69
+ &this.0,
70
+ |rogue| rogue.arm(slot, experiment),
71
+ |arming| match arming {
72
+ Arming::Replaced(previous) => classes.replaced(ruby, previous),
73
+ Arming::Armed | Arming::AlreadyArmed => {
74
+ Ok(Armings::symbol(ruby, &arming).as_value())
75
+ }
76
+ },
77
+ )
78
+ }
79
+
80
+ /// A `Disarmed` holding what the slot held, or `:not_armed`.
81
+ fn disarm(ruby: &Ruby, this: Obj<Self>, given_slot: Value) -> Result<Value, Error> {
82
+ this.check_frozen()?;
83
+ let slot = slot(ruby, given_slot)?;
84
+ let classes = classes(ruby)?;
85
+ keep(
86
+ ruby,
87
+ this,
88
+ &this.0,
89
+ |rogue| rogue.disarm(slot),
90
+ |disarming| match disarming {
91
+ Disarming::Disarmed(previous) => classes.disarmed(ruby, previous),
92
+ Disarming::NotArmed => Ok(Disarmings::symbol(ruby, &disarming).as_value()),
93
+ },
94
+ )
95
+ }
96
+
97
+ fn disarm_all(this: Obj<Self>) -> Result<u32, Error> {
98
+ this.check_frozen()?;
99
+ Ok(this.0.borrow_mut().disarm_all())
100
+ }
101
+
102
+ fn sweep(this: Obj<Self>, now: Value) -> Result<u32, Error> {
103
+ this.check_frozen()?;
104
+ let now = duration(now, "now")?;
105
+ Ok(this.0.borrow_mut().sweep(now))
106
+ }
107
+
108
+ fn any_armed(&self) -> bool {
109
+ self.0.borrow().any_armed()
110
+ }
111
+
112
+ fn armed_count(&self) -> u32 {
113
+ self.0.borrow().armed_count()
114
+ }
115
+
116
+ fn live_count(&self, now: Value) -> Result<u32, Error> {
117
+ let now = duration(now, "now")?;
118
+ Ok(self.0.borrow().live_count(now))
119
+ }
120
+
121
+ fn vacant(ruby: &Ruby, this: &Self) -> Result<Option<Value>, Error> {
122
+ let vacant = this.0.borrow().vacant();
123
+ vacant
124
+ .map(|slot| classes(ruby)?.slot(ruby, slot))
125
+ .transpose()
126
+ }
127
+
128
+ fn experiment(ruby: &Ruby, this: &Self, given_slot: Value) -> Result<Option<Value>, Error> {
129
+ let slot = slot(ruby, given_slot)?;
130
+ let held = this.0.borrow().experiment(slot);
131
+ held.map(|held| classes(ruby)?.experiment(ruby, held))
132
+ .transpose()
133
+ }
134
+
135
+ fn active(
136
+ ruby: &Ruby,
137
+ this: &Self,
138
+ given_slot: Value,
139
+ now: Value,
140
+ ) -> Result<Option<Value>, Error> {
141
+ let (slot, now) = (slot(ruby, given_slot)?, duration(now, "now")?);
142
+ let live = this.0.borrow().active(slot, now);
143
+ live.map(|live| classes(ruby)?.experiment(ruby, live))
144
+ .transpose()
145
+ }
146
+
147
+ /// `:pass`, or an `Inject` naming the fault.
148
+ fn decide(
149
+ ruby: &Ruby,
150
+ this: &Self,
151
+ given_slot: Value,
152
+ now: Value,
153
+ given_draw: Value,
154
+ ) -> Result<Value, Error> {
155
+ let (slot, now) = (slot(ruby, given_slot)?, duration(now, "now")?);
156
+ let drawn = draw(ruby, given_draw)?;
157
+ let decision = this.0.borrow().decide(slot, now, drawn);
158
+ match decision {
159
+ Decision::Pass => Ok(Decisions::symbol(ruby, &decision).as_value()),
160
+ Decision::Inject(fault) => classes(ruby)?.inject(ruby, fault),
161
+ }
162
+ }
163
+
164
+ fn inspect(&self) -> String {
165
+ let rogue = self.0.borrow();
166
+ format!(
167
+ "#<RogueMachines::Rogue armed={} of {}>",
168
+ rogue.armed_count(),
169
+ rogue_machines::EXPERIMENTS
170
+ )
171
+ }
172
+ }
173
+
174
+ pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
175
+ let class = module.define_class("Rogue", ruby.class_object())?;
176
+ class.undef_default_alloc_func();
177
+ class.define_singleton_method("new", function!(Wrapper::new, 0))?;
178
+ class.define_method("dup", method!(Wrapper::dup, 0))?;
179
+ class.define_method("arm", method!(Wrapper::arm, 2))?;
180
+ class.define_method("disarm", method!(Wrapper::disarm, 1))?;
181
+ class.define_method("disarm_all", method!(Wrapper::disarm_all, 0))?;
182
+ class.define_method("sweep", method!(Wrapper::sweep, 1))?;
183
+ class.define_method("any_armed?", method!(Wrapper::any_armed, 0))?;
184
+ class.define_method("armed_count", method!(Wrapper::armed_count, 0))?;
185
+ class.define_method("live_count", method!(Wrapper::live_count, 1))?;
186
+ class.define_method("vacant", method!(Wrapper::vacant, 0))?;
187
+ class.define_method("experiment", method!(Wrapper::experiment, 1))?;
188
+ class.define_method("active", method!(Wrapper::active, 2))?;
189
+ class.define_method("decide", method!(Wrapper::decide, 3))?;
190
+ class.define_method("inspect", method!(Wrapper::inspect, 0))?;
191
+ // Fix magnus's class for `Wrapper` now: building a Rogue (`new`, `dup`)
192
+ // then runs no `Object.const_get` and always answers this class.
193
+ Class::pin_wrapped::<Wrapper>(ruby, class).map(drop)
194
+ }
@@ -0,0 +1,288 @@
1
+ //! The `Data` values mirroring the core's types: validated on the way in
2
+ //! through the core's own constructors, built on the way out from what the
3
+ //! core returned.
4
+ //!
5
+ //! The classes are defined in Ruby before the extension loads; each one's
6
+ //! `initialize` calls a private hook here, so a hand-built value is held to
7
+ //! the same rule as one the binding returns.
8
+
9
+ use magnus::{Error, RArray, RModule, Ruby, Value, function, prelude::*};
10
+ use matryona_machines::ruby::{
11
+ Bounded, Choice, Class, Refused, SymbolNames, class_name, duration, exact_fields, integer,
12
+ nanoseconds, symbol_or_fields_why,
13
+ };
14
+ use rogue_machines::{Draw, Experiment, Fault, Fraction, Slot};
15
+
16
+ /// The `Data` classes, looked up once at load and pinned, so that nothing
17
+ /// after a core call has a lookup left that could raise.
18
+ pub struct Classes {
19
+ slot: Class,
20
+ fraction: Class,
21
+ draw: Class,
22
+ delay: Class,
23
+ experiment: Class,
24
+ inject: Class,
25
+ replaced: Class,
26
+ disarmed: Class,
27
+ }
28
+
29
+ matryona_machines::registry! {
30
+ static CLASSES: Classes = "rogue_machines";
31
+ /// The classes, or a `NameError` when the extension was loaded without
32
+ /// `rogue_machines.rb` defining them first.
33
+ pub fn classes;
34
+ }
35
+
36
+ fn range_error(ruby: &Ruby, message: String) -> Error {
37
+ Error::new(ruby.exception_range_error(), message)
38
+ }
39
+
40
+ /// The `N` fields of `value` when it is an instance of exactly `class`,
41
+ /// `TypeError` with `message` otherwise: a subclass's constant leaks past the
42
+ /// seal, so `is_a?` is not enough, and an opened singleton class changes
43
+ /// nothing. The fields are read from the struct itself, so a redefined reader
44
+ /// is never called, then rebuilt through the core's constructors, which
45
+ /// `Marshal.load` skipped.
46
+ fn fields<const N: usize>(
47
+ ruby: &Ruby,
48
+ value: Value,
49
+ class: Class,
50
+ message: &'static str,
51
+ ) -> Result<[Value; N], Error> {
52
+ exact_fields(ruby, value, class.get(ruby), message)
53
+ }
54
+
55
+ /// An Integer the core's constructor `build` accepts: `TypeError` for a
56
+ /// non-Integer, `RangeError` naming `rule` for anything `build` rejects.
57
+ fn constructed<N: Bounded, T>(
58
+ ruby: &Ruby,
59
+ name: &str,
60
+ value: Value,
61
+ build: impl FnOnce(N) -> Option<T>,
62
+ rule: impl FnOnce() -> String,
63
+ ) -> Result<T, Error> {
64
+ build(integer::<N>(value, name)?).ok_or_else(|| range_error(ruby, rule()))
65
+ }
66
+
67
+ fn slot_index(ruby: &Ruby, index: Value) -> Result<Slot, Error> {
68
+ constructed(ruby, "index", index, Slot::new, || {
69
+ format!("a slot is below {}", rogue_machines::EXPERIMENTS)
70
+ })
71
+ }
72
+
73
+ fn fraction_millionths(ruby: &Ruby, millionths: Value) -> Result<Fraction, Error> {
74
+ constructed(ruby, "millionths", millionths, Fraction::new, || {
75
+ format!("a fraction is at most {}", rogue_machines::PER_MILLION)
76
+ })
77
+ }
78
+
79
+ fn draw_millionths(ruby: &Ruby, millionths: Value) -> Result<Draw, Error> {
80
+ constructed(ruby, "millionths", millionths, Draw::new, || {
81
+ format!("a draw is below {}", rogue_machines::PER_MILLION)
82
+ })
83
+ }
84
+
85
+ /// The core `Slot` of a `RogueMachines::Slot`.
86
+ pub fn slot(ruby: &Ruby, value: Value) -> Result<Slot, Error> {
87
+ let [index] = fields(
88
+ ruby,
89
+ value,
90
+ classes(ruby)?.slot,
91
+ "expected a RogueMachines::Slot",
92
+ )?;
93
+ slot_index(ruby, index)
94
+ }
95
+
96
+ /// The core `Draw` of a `RogueMachines::Draw`.
97
+ pub fn draw(ruby: &Ruby, value: Value) -> Result<Draw, Error> {
98
+ let [millionths] = fields(
99
+ ruby,
100
+ value,
101
+ classes(ruby)?.draw,
102
+ "expected a RogueMachines::Draw",
103
+ )?;
104
+ draw_millionths(ruby, millionths)
105
+ }
106
+
107
+ fn fraction(ruby: &Ruby, value: Value) -> Result<Fraction, Error> {
108
+ let message = "expected a RogueMachines::Fraction";
109
+ let [millionths] = fields(ruby, value, classes(ruby)?.fraction, message)?;
110
+ fraction_millionths(ruby, millionths)
111
+ }
112
+
113
+ matryona_machines::symbols! {
114
+ /// A fault as Ruby holds it: `:raise`, `:garble`, or a `Delay`.
115
+ Faults for Fault as "a fault" => names_only {
116
+ Raise => "raise",
117
+ Delay(..) => "delay",
118
+ Garble => "garble",
119
+ }
120
+ }
121
+
122
+ /// `:raise`, `:garble` or a `RogueMachines::Delay`: `RangeError` for any
123
+ /// other Symbol, `TypeError` for anything else, each naming what it got.
124
+ fn fault(ruby: &Ruby, value: Value) -> Result<Fault, Error> {
125
+ let delay = classes(ruby)?.delay.get(ruby);
126
+ let read = symbol_or_fields_why(ruby, value, Faults, &[delay], |why| {
127
+ let got = match why {
128
+ Refused::UnknownSymbol(symbol) => symbol.inspect(),
129
+ _ => class_name(value),
130
+ };
131
+ format!("a fault is :raise, :garble or a Delay, got {got}")
132
+ })?;
133
+ match read {
134
+ Choice::Symbol(fault) => Ok(fault),
135
+ Choice::Struct(_, [span]) => Ok(Fault::Delay(duration(span, "duration")?)),
136
+ }
137
+ }
138
+
139
+ /// The core `Experiment` of a `RogueMachines::Experiment`.
140
+ pub fn experiment(ruby: &Ruby, value: Value) -> Result<Experiment, Error> {
141
+ let message = "expected a RogueMachines::Experiment";
142
+ let [given_fault, given_fraction, expires_at] =
143
+ fields(ruby, value, classes(ruby)?.experiment, message)?;
144
+ Ok(Experiment::new(
145
+ fault(ruby, given_fault)?,
146
+ fraction(ruby, given_fraction)?,
147
+ duration(expires_at, "expires_at")?,
148
+ ))
149
+ }
150
+
151
+ impl Classes {
152
+ /// `Data.new` with positional fields, which `initialize` validates.
153
+ fn build(ruby: &Ruby, class: Class, fields: impl magnus::ArgList) -> Result<Value, Error> {
154
+ class.get(ruby).funcall("new", fields)
155
+ }
156
+
157
+ pub fn slot(&self, ruby: &Ruby, slot: Slot) -> Result<Value, Error> {
158
+ Self::build(ruby, self.slot, (slot.index(),))
159
+ }
160
+
161
+ pub fn fault(&self, ruby: &Ruby, fault: Fault) -> Result<Value, Error> {
162
+ match fault {
163
+ Fault::Raise | Fault::Garble => Ok(Faults::symbol(ruby, &fault).as_value()),
164
+ Fault::Delay(span) => Self::build(ruby, self.delay, (nanoseconds(ruby, span),)),
165
+ }
166
+ }
167
+
168
+ pub fn experiment(&self, ruby: &Ruby, experiment: Experiment) -> Result<Value, Error> {
169
+ let fraction = Self::build(ruby, self.fraction, (experiment.fraction.millionths(),))?;
170
+ let fault = self.fault(ruby, experiment.fault)?;
171
+ let expires_at = nanoseconds(ruby, experiment.expires_at);
172
+ Self::build(ruby, self.experiment, (fault, fraction, expires_at))
173
+ }
174
+
175
+ pub fn inject(&self, ruby: &Ruby, fault: Fault) -> Result<Value, Error> {
176
+ Self::build(ruby, self.inject, (self.fault(ruby, fault)?,))
177
+ }
178
+
179
+ pub fn replaced(&self, ruby: &Ruby, experiment: Experiment) -> Result<Value, Error> {
180
+ self.held(ruby, self.replaced, experiment)
181
+ }
182
+
183
+ pub fn disarmed(&self, ruby: &Ruby, experiment: Experiment) -> Result<Value, Error> {
184
+ self.held(ruby, self.disarmed, experiment)
185
+ }
186
+
187
+ /// A `Replaced` or `Disarmed`: the experiment, and `garbled` nil. The
188
+ /// core keeps no substitute; the one these carry is the runtime's.
189
+ fn held(&self, ruby: &Ruby, class: Class, experiment: Experiment) -> Result<Value, Error> {
190
+ let garbled = ruby.qnil().as_value();
191
+ Self::build(ruby, class, (self.experiment(ruby, experiment)?, garbled))
192
+ }
193
+ }
194
+
195
+ /// `Slot.new` validates through this: the index as `Slot::new` holds it.
196
+ fn checked_slot(ruby: &Ruby, index: Value) -> Result<usize, Error> {
197
+ slot_index(ruby, index).map(Slot::index)
198
+ }
199
+
200
+ /// `Fraction.new`: the millionths as `Fraction::new` holds them.
201
+ fn checked_fraction(ruby: &Ruby, millionths: Value) -> Result<u32, Error> {
202
+ fraction_millionths(ruby, millionths).map(Fraction::millionths)
203
+ }
204
+
205
+ /// `Draw.new`: the millionths as `Draw::new` holds them.
206
+ fn checked_draw(ruby: &Ruby, millionths: Value) -> Result<u32, Error> {
207
+ draw_millionths(ruby, millionths).map(Draw::millionths)
208
+ }
209
+
210
+ /// Integer nanoseconds as a `Duration` holds them.
211
+ fn checked_nanos(ruby: &Ruby, name: &str, value: Value) -> Result<Value, Error> {
212
+ duration(value, name).map(|span| nanoseconds(ruby, span).as_value())
213
+ }
214
+
215
+ /// `Delay.new`: its duration.
216
+ fn checked_delay(ruby: &Ruby, duration: Value) -> Result<Value, Error> {
217
+ checked_nanos(ruby, "duration", duration)
218
+ }
219
+
220
+ /// `Experiment.new`: the fields unchanged once each is the core's own type.
221
+ fn checked_experiment(
222
+ ruby: &Ruby,
223
+ given_fault: Value,
224
+ given_fraction: Value,
225
+ expires_at: Value,
226
+ ) -> Result<RArray, Error> {
227
+ fault(ruby, given_fault)?;
228
+ fraction(ruby, given_fraction)?;
229
+ let expires_at = checked_nanos(ruby, "expires_at", expires_at)?;
230
+ Ok(ruby.ary_new_from_values(&[given_fault, given_fraction, expires_at]))
231
+ }
232
+
233
+ /// `Inject.new`: a fault.
234
+ fn checked_fault(ruby: &Ruby, given: Value) -> Result<Value, Error> {
235
+ fault(ruby, given).map(|_| given)
236
+ }
237
+
238
+ /// `__delay_of`: what the runtime's `arm` bounds before it arms, read as
239
+ /// every fault is read (`fault`'s errors, a `Delay` by exact class from the
240
+ /// struct): nil for `:raise` and `:garble`, a `Delay`'s Integer nanoseconds.
241
+ fn delay_of(ruby: &Ruby, given: Value) -> Result<Option<Value>, Error> {
242
+ Ok(match fault(ruby, given)? {
243
+ Fault::Delay(span) => Some(nanoseconds(ruby, span).as_value()),
244
+ Fault::Raise | Fault::Garble => None,
245
+ })
246
+ }
247
+
248
+ /// `Replaced.new` and `Disarmed.new`: an `Experiment` (their `garbled` is
249
+ /// any object and is not read here).
250
+ fn checked_held(ruby: &Ruby, given: Value) -> Result<Value, Error> {
251
+ experiment(ruby, given).map(|_| given)
252
+ }
253
+
254
+ /// `Experiment#spent?`: the core's `Experiment::spent`.
255
+ fn spent(ruby: &Ruby, given: Value, now: Value) -> Result<bool, Error> {
256
+ Ok(experiment(ruby, given)?.spent(duration(now, "now")?))
257
+ }
258
+
259
+ /// `Fraction#covers?`: the core's `Fraction::covers`.
260
+ fn covers(ruby: &Ruby, given: Value, given_draw: Value) -> Result<bool, Error> {
261
+ Ok(fraction(ruby, given)?.covers(draw(ruby, given_draw)?))
262
+ }
263
+
264
+ pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
265
+ let class = |name| Class::resolve(ruby, module, name);
266
+ let classes = Classes {
267
+ slot: class("Slot")?,
268
+ fraction: class("Fraction")?,
269
+ draw: class("Draw")?,
270
+ delay: class("Delay")?,
271
+ experiment: class("Experiment")?,
272
+ inject: class("Inject")?,
273
+ replaced: class("Replaced")?,
274
+ disarmed: class("Disarmed")?,
275
+ };
276
+ CLASSES.set(ruby, classes)?;
277
+ module.define_singleton_method("__slot", function!(checked_slot, 1))?;
278
+ module.define_singleton_method("__fraction", function!(checked_fraction, 1))?;
279
+ module.define_singleton_method("__draw", function!(checked_draw, 1))?;
280
+ module.define_singleton_method("__delay", function!(checked_delay, 1))?;
281
+ module.define_singleton_method("__experiment", function!(checked_experiment, 3))?;
282
+ module.define_singleton_method("__fault", function!(checked_fault, 1))?;
283
+ module.define_singleton_method("__delay_of", function!(delay_of, 1))?;
284
+ module.define_singleton_method("__held", function!(checked_held, 1))?;
285
+ module.define_singleton_method("__spent", function!(spent, 2))?;
286
+ module.define_singleton_method("__covers", function!(covers, 2))?;
287
+ Ok(())
288
+ }