flay-rs 0.1.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,487 @@
1
+ //! Flay's `filters` option: `Flay#filter_sexp` and the `Sexp::Matcher`
2
+ //! classes of sexp_processor 4.17.6 (`sexp_matcher.rb`) it calls
3
+ //! `satisfy?` on.
4
+ //!
5
+ //! An entry of `option[:filters]` is usually built with
6
+ //! `Sexp::Matcher.parse("(call nil :puts ___)")` ([`Filter::parse`]) or the
7
+ //! `s{ q(:call, nil, :puts, ___) }` DSL. The Ruby side hands one over as the
8
+ //! text `parity/matcher_serializer.rb` writes ([`Filter::from_serialized`]).
9
+ //!
10
+ //! `satisfy?` can raise in Ruby (a `Sexp::Klass` whose `pattern` is not a
11
+ //! class, `child` of a non-matcher, a `Sexp::Pattern` matched against an
12
+ //! invalid string); those come back as `Err` with Ruby's exception class and
13
+ //! message. Flay does not rescue them, so `Flay#process` raises.
14
+
15
+ mod parser;
16
+ mod regexp;
17
+ mod ruby_text;
18
+ mod serialized;
19
+
20
+ use crate::sexp::{value_eq, SexpId, Tree, Value};
21
+ use crate::RubyException;
22
+
23
+ pub use regexp::{CompileError, CompiledRegexp};
24
+ pub use ruby_text::to_s;
25
+
26
+ type Result<T> = std::result::Result<T, RubyException>;
27
+
28
+ /// One entry of Flay's `option[:filters]`: the object `Sexp::Matcher.parse`
29
+ /// or the DSL returned (usually a `Sexp::Matcher`), with the symbol table
30
+ /// its Symbols are interned in.
31
+ #[derive(Clone, Debug)]
32
+ pub struct Filter {
33
+ symbols: Tree,
34
+ object: Object,
35
+ }
36
+
37
+ /// A Ruby object held by a filter.
38
+ #[derive(Clone, Debug)]
39
+ pub enum Object {
40
+ /// `nil`, `true`, `false`, a Symbol (interned in the filter's symbol
41
+ /// table), String, Integer, Float, Rational, Complex, Range or Regexp.
42
+ Value(Value),
43
+ /// A class or module, such as `String` in `[k String]`.
44
+ Module(Module),
45
+ /// An instance of `Sexp::Matcher` or one of its subclasses.
46
+ Matcher(Box<Matcher>),
47
+ }
48
+
49
+ /// A Ruby class or module: its name, and which classes of the values a
50
+ /// translated tree holds are kinds of it.
51
+ #[derive(Clone, Debug, PartialEq)]
52
+ pub struct Module {
53
+ pub name: String,
54
+ /// A `Class`, not just a `Module` (Ruby's error messages differ).
55
+ pub is_class: bool,
56
+ /// Bit `i` is set when `TREE_CLASSES[i] <= module`.
57
+ pub tree_classes: u16,
58
+ }
59
+
60
+ /// The classes of the values in a translated tree. A [`Module`]'s
61
+ /// `tree_classes` indexes this list.
62
+ pub const TREE_CLASSES: [&str; 13] = [
63
+ "NilClass", "TrueClass", "FalseClass", "Symbol", "String", "Integer", "Float", "Rational", "Complex", "Range",
64
+ "Regexp", "Array", "Sexp",
65
+ ];
66
+
67
+ /// An instance of `Sexp::Matcher` or a subclass, one variant per class,
68
+ /// with the attributes `satisfy?` reads.
69
+ #[derive(Clone, Debug)]
70
+ pub enum Matcher {
71
+ /// `Sexp::Matcher` itself (`q(...)`, `(...)` in `parse`): its elements.
72
+ Matcher(Vec<Object>),
73
+ /// `Sexp::Wild` (`_`).
74
+ Wild,
75
+ /// `Sexp::Remaining` (`___`).
76
+ Remaining,
77
+ /// `Sexp::Any`: its `options`.
78
+ Any(Vec<Object>),
79
+ /// `Sexp::All`: its `options`.
80
+ All(Vec<Object>),
81
+ /// `Sexp::Not`: its `value`.
82
+ Not(Object),
83
+ /// `Sexp::Child`: its `child`.
84
+ Child(Object),
85
+ /// `Sexp::Atom`.
86
+ Atom,
87
+ /// `Sexp::Pattern`: its `pattern`, a Regexp.
88
+ Pattern(CompiledRegexp),
89
+ /// `Sexp::Klass`: its `pattern`, normally a class.
90
+ Klass(Object),
91
+ /// `Sexp::Type`: its `sexp_type`.
92
+ Type(Object),
93
+ /// `Sexp::Include`: its `value`.
94
+ Include(Object),
95
+ /// `Sexp::Sibling`: its `subject`, `sibling` and `distance`.
96
+ Sibling { subject: Object, sibling: Object, distance: Object },
97
+ }
98
+
99
+ impl Filter {
100
+ /// `Sexp::Matcher.parse(source)`.
101
+ pub fn parse(source: &str) -> Result<Filter> {
102
+ parser::parse(source)
103
+ }
104
+
105
+ /// Reads a filter in the format `parity/matcher_serializer.rb` writes.
106
+ pub fn from_serialized(text: &str) -> Result<Filter> {
107
+ serialized::read(text)
108
+ }
109
+
110
+ /// The filter in the format `parity/matcher_serializer.rb` writes.
111
+ pub fn serialize(&self) -> String {
112
+ serialized::write(&self.symbols, &self.object)
113
+ }
114
+
115
+ /// `pattern.satisfy?(o)` for `o`, a value in `tree` (`Value::Sexp` for
116
+ /// a sexp).
117
+ pub fn satisfy(&self, tree: &Tree, o: &Value) -> Result<bool> {
118
+ Satisfy { symbols: &self.symbols, tree }.object_satisfy(&self.object, o)
119
+ }
120
+ }
121
+
122
+ /// `Flay#filter_sexp`: deletes, at every depth below `root`, each sexp
123
+ /// that a filter is satisfied by, checking a sexp before filtering inside
124
+ /// it:
125
+ ///
126
+ /// ```ruby
127
+ /// def filter_sexp exp
128
+ /// exp.delete_if { |sexp|
129
+ /// if Sexp === sexp then
130
+ /// del = option[:filters].any? { |pattern| pattern.satisfy? sexp }
131
+ /// del or (filter_sexp(sexp); false)
132
+ /// end
133
+ /// }
134
+ /// end
135
+ /// ```
136
+ ///
137
+ /// The root itself is never deleted. Call [`Tree::finish`] afterwards: the
138
+ /// masses and structural hashes change. On `Err` the tree is left as Ruby
139
+ /// leaves it when `satisfy?` raises.
140
+ pub fn filter_sexp(tree: &mut Tree, root: SexpId, filters: &[Filter]) -> Result<()> {
141
+ /// A sexp whose elements are being filtered: the elements not yet
142
+ /// checked and those kept so far.
143
+ struct Frame {
144
+ sexp: SexpId,
145
+ unchecked: std::vec::IntoIter<Value>,
146
+ kept: Vec<Value>,
147
+ }
148
+ let open = |tree: &mut Tree, sexp: SexpId| {
149
+ let elements = std::mem::take(&mut tree.get_mut(sexp).elements);
150
+ Frame { sexp, kept: Vec::with_capacity(elements.len()), unchecked: elements.into_iter() }
151
+ };
152
+
153
+ let mut stack = vec![open(tree, root)];
154
+ while let Some(frame) = stack.last_mut() {
155
+ let Some(element) = frame.unchecked.next() else {
156
+ let frame = stack.pop().expect("the loop checked for a frame");
157
+ tree.get_mut(frame.sexp).elements = frame.kept;
158
+ continue;
159
+ };
160
+ let Value::Sexp(child) = element else {
161
+ frame.kept.push(element);
162
+ continue;
163
+ };
164
+ match any_satisfied(tree, child, filters) {
165
+ Ok(true) => {}
166
+ Ok(false) => {
167
+ frame.kept.push(element);
168
+ stack.push(open(tree, child));
169
+ }
170
+ Err(exception) => {
171
+ // `delete_if` keeps the element being checked and the rest.
172
+ frame.kept.push(element);
173
+ for mut frame in stack.into_iter().rev() {
174
+ frame.kept.extend(frame.unchecked);
175
+ tree.get_mut(frame.sexp).elements = frame.kept;
176
+ }
177
+ return Err(exception);
178
+ }
179
+ }
180
+ }
181
+ Ok(())
182
+ }
183
+
184
+ /// `option[:filters].any? { |pattern| pattern.satisfy? sexp }`.
185
+ fn any_satisfied(tree: &Tree, sexp: SexpId, filters: &[Filter]) -> Result<bool> {
186
+ for filter in filters {
187
+ if filter.satisfy(tree, &Value::Sexp(sexp))? {
188
+ return Ok(true);
189
+ }
190
+ }
191
+ Ok(false)
192
+ }
193
+
194
+ /// `nil`, for `o.at i` past the end of `o`.
195
+ static NIL: Value = Value::Nil;
196
+
197
+ /// `satisfy?` and `==` between a filter's objects (with its symbol table)
198
+ /// and the values of a tree.
199
+ struct Satisfy<'a> {
200
+ symbols: &'a Tree,
201
+ tree: &'a Tree,
202
+ }
203
+
204
+ impl Satisfy<'_> {
205
+ /// `object.satisfy?(o)`: only matchers have `satisfy?`.
206
+ fn object_satisfy(&self, object: &Object, o: &Value) -> Result<bool> {
207
+ match object {
208
+ Object::Matcher(matcher) => self.matcher_satisfy(matcher, o),
209
+ other => Err(RubyException {
210
+ class: "NoMethodError",
211
+ message: format!("undefined method `satisfy?' for {}", ruby_text::receiver_description(other)),
212
+ }),
213
+ }
214
+ }
215
+
216
+ /// `satisfy?` of each `Sexp::Matcher` class.
217
+ fn matcher_satisfy(&self, matcher: &Matcher, o: &Value) -> Result<bool> {
218
+ match matcher {
219
+ Matcher::Matcher(elements) => self.matcher_elements_satisfy(elements, o),
220
+ Matcher::Wild | Matcher::Remaining => Ok(true),
221
+ Matcher::Any(options) => {
222
+ // `Sexp === exp && exp.satisfy?(o) || exp == o`; a matcher is
223
+ // never `==` to a value of the tree.
224
+ for option in options {
225
+ let satisfied = match option {
226
+ Object::Matcher(matcher) => self.matcher_satisfy(matcher, o)?,
227
+ _ => self.equals(option, o),
228
+ };
229
+ if satisfied {
230
+ return Ok(true);
231
+ }
232
+ }
233
+ Ok(false)
234
+ }
235
+ Matcher::All(options) => {
236
+ for option in options {
237
+ if !self.satisfy_or_equal(option, o)? {
238
+ return Ok(false);
239
+ }
240
+ }
241
+ Ok(true)
242
+ }
243
+ Matcher::Not(value) => Ok(!self.satisfy_or_equal(value, o)?),
244
+ Matcher::Child(child) => {
245
+ if self.object_satisfy(child, o)? {
246
+ return Ok(true);
247
+ }
248
+ match (o, child) {
249
+ (Value::Sexp(sexp), Object::Matcher(child)) => self.search_each_any(child, *sexp),
250
+ _ => Ok(false),
251
+ }
252
+ }
253
+ Matcher::Atom => Ok(!matches!(o, Value::Sexp(_))),
254
+ Matcher::Pattern(pattern) => {
255
+ // `!o.kind_of?(Sexp) && o.to_s =~ pattern`
256
+ if matches!(o, Value::Sexp(_)) {
257
+ return Ok(false);
258
+ }
259
+ pattern.matches(&to_s(self.tree, o)?)
260
+ }
261
+ Matcher::Klass(pattern) => self.kind_of(o, pattern),
262
+ Matcher::Type(sexp_type) => {
263
+ // `o.kind_of?(Sexp) && o.sexp_type == sexp_type`
264
+ let Value::Sexp(sexp) = o else { return Ok(false) };
265
+ let first = self.tree.get(*sexp).elements.first().unwrap_or(&NIL);
266
+ Ok(self.equals(sexp_type, first))
267
+ }
268
+ Matcher::Include(value) => {
269
+ // `Sexp === o && o.any? { |c| Sexp === value ? value.satisfy?(c) : value == c }`
270
+ let Value::Sexp(sexp) = o else { return Ok(false) };
271
+ for element in &self.tree.get(*sexp).elements {
272
+ if self.satisfy_or_equal(value, element)? {
273
+ return Ok(true);
274
+ }
275
+ }
276
+ Ok(false)
277
+ }
278
+ Matcher::Sibling { subject, sibling, distance } => self.sibling_satisfy(subject, sibling, distance, o),
279
+ }
280
+ }
281
+
282
+ /// `Sexp::Matcher#satisfy?`:
283
+ ///
284
+ /// ```ruby
285
+ /// return unless o.kind_of?(Sexp) &&
286
+ /// (length == o.length || Matcher === last && last.greedy?)
287
+ /// each_with_index.all? { |child, i|
288
+ /// sexp = o.at i
289
+ /// if Sexp === child then
290
+ /// sexp = o.sexp_body i if child.respond_to?(:greedy?) && child.greedy?
291
+ /// child.satisfy? sexp
292
+ /// else
293
+ /// child == sexp
294
+ /// end
295
+ /// }
296
+ /// ```
297
+ ///
298
+ /// Only `Sexp::Remaining` is greedy, and it is satisfied by anything.
299
+ fn matcher_elements_satisfy(&self, elements: &[Object], o: &Value) -> Result<bool> {
300
+ let Value::Sexp(sexp) = o else { return Ok(false) };
301
+ let o_elements = &self.tree.get(*sexp).elements;
302
+ let last_is_greedy = matches!(elements.last(), Some(Object::Matcher(last)) if matches!(**last, Matcher::Remaining));
303
+ if elements.len() != o_elements.len() && !last_is_greedy {
304
+ return Ok(false);
305
+ }
306
+ for (index, child) in elements.iter().enumerate() {
307
+ let sexp = o_elements.get(index).unwrap_or(&NIL);
308
+ let satisfied = match child {
309
+ Object::Matcher(child) => self.matcher_satisfy(child, sexp)?,
310
+ _ => self.equals(child, sexp),
311
+ };
312
+ if !satisfied {
313
+ return Ok(false);
314
+ }
315
+ }
316
+ Ok(true)
317
+ }
318
+
319
+ /// `exp.kind_of?(Sexp) ? exp.satisfy?(o) : exp == o`.
320
+ fn satisfy_or_equal(&self, object: &Object, o: &Value) -> Result<bool> {
321
+ match object {
322
+ Object::Matcher(matcher) => self.matcher_satisfy(matcher, o),
323
+ _ => Ok(self.equals(object, o)),
324
+ }
325
+ }
326
+
327
+ /// `o.search_each(child).any?`: whether `child` is satisfied by `o` or
328
+ /// a sexp below it, in pre-order.
329
+ fn search_each_any(&self, child: &Matcher, sexp: SexpId) -> Result<bool> {
330
+ let mut pending = vec![sexp];
331
+ while let Some(sexp) = pending.pop() {
332
+ if self.matcher_satisfy(child, &Value::Sexp(sexp))? {
333
+ return Ok(true);
334
+ }
335
+ let start = pending.len();
336
+ pending.extend(self.tree.each_sexp(sexp));
337
+ pending[start..].reverse();
338
+ }
339
+ Ok(false)
340
+ }
341
+
342
+ /// `o.kind_of?(pattern)`.
343
+ fn kind_of(&self, o: &Value, pattern: &Object) -> Result<bool> {
344
+ let Object::Module(module) = pattern else {
345
+ return Err(RubyException { class: "TypeError", message: "class or module required".to_string() });
346
+ };
347
+ Ok(module.tree_classes & (1 << tree_class(o)) != 0)
348
+ }
349
+
350
+ /// `Sexp::Sibling#satisfy?`: an element satisfying `subject` comes
351
+ /// before one satisfying `sibling`, `distance` elements later when
352
+ /// `distance` is given.
353
+ fn sibling_satisfy(&self, subject: &Object, sibling: &Object, distance: &Object, o: &Value) -> Result<bool> {
354
+ let subject_matches = self.index_matches(subject, o)?;
355
+ if subject_matches.is_empty() {
356
+ return Ok(false);
357
+ }
358
+ let sibling_matches = self.index_matches(sibling, o)?;
359
+ if sibling_matches.is_empty() {
360
+ return Ok(false);
361
+ }
362
+ let has_distance = !matches!(distance, Object::Value(Value::Nil | Value::False));
363
+ Ok(subject_matches.iter().any(|first| {
364
+ sibling_matches.iter().any(|second| {
365
+ if has_distance {
366
+ // `i2 - i1 == distance`
367
+ let difference = *second as i64 - *first as i64;
368
+ let difference = Value::integer(crate::sexp::Integer::from_i64(difference));
369
+ match distance {
370
+ Object::Value(distance) => value_eq(self.tree, &difference, self.symbols, distance),
371
+ _ => false,
372
+ }
373
+ } else {
374
+ second > first
375
+ }
376
+ })
377
+ }))
378
+ }
379
+
380
+ /// `Sexp::Sibling#index_matches`: the indexes of the elements of `o`
381
+ /// that `pattern` is satisfied by (or `==` to).
382
+ fn index_matches(&self, pattern: &Object, o: &Value) -> Result<Vec<usize>> {
383
+ let Value::Sexp(sexp) = o else { return Ok(Vec::new()) };
384
+ let mut indexes = Vec::new();
385
+ for (index, element) in self.tree.get(*sexp).elements.iter().enumerate() {
386
+ if self.satisfy_or_equal(pattern, element)? {
387
+ indexes.push(index);
388
+ }
389
+ }
390
+ Ok(indexes)
391
+ }
392
+
393
+ /// `object == o`. A matcher (a `Sexp` subclass) or a module is never
394
+ /// `==` to a value of a translated tree.
395
+ fn equals(&self, object: &Object, o: &Value) -> bool {
396
+ match object {
397
+ Object::Value(value) => value_eq(self.symbols, value, self.tree, o),
398
+ Object::Module(_) | Object::Matcher(_) => false,
399
+ }
400
+ }
401
+ }
402
+
403
+ /// The index in [`TREE_CLASSES`] of a tree value's class.
404
+ fn tree_class(value: &Value) -> usize {
405
+ match value {
406
+ Value::Nil => 0,
407
+ Value::True => 1,
408
+ Value::False => 2,
409
+ Value::Symbol(_) => 3,
410
+ Value::String(_) => 4,
411
+ Value::Integer(_) => 5,
412
+ Value::Float(_) => 6,
413
+ Value::Rational(_) => 7,
414
+ Value::Complex(_) => 8,
415
+ Value::Range(_) => 9,
416
+ Value::Regexp(_) => 10,
417
+ Value::Array(_) => 11,
418
+ Value::Sexp(_) => 12,
419
+ }
420
+ }
421
+
422
+ #[cfg(test)]
423
+ mod tests {
424
+ use super::*;
425
+ use crate::sexp::{Integer, UTF_8};
426
+
427
+ /// `s(:block, s(:call, nil, :puts, s(:str, "x")), s(:lit, 1))`.
428
+ fn sample() -> (Tree, SexpId) {
429
+ let mut tree = Tree::default();
430
+ let puts = tree.intern(b"puts", UTF_8);
431
+ let string = Value::string(crate::sexp::RubyString::new("x", UTF_8));
432
+ let str_sexp = tree.add(vec![Value::static_symbol("str"), string], 1, 1);
433
+ let call = tree.add(vec![Value::static_symbol("call"), Value::Nil, puts, Value::Sexp(str_sexp)], 1, 1);
434
+ let lit = tree.add(vec![Value::static_symbol("lit"), Value::integer(Integer::from_i64(1))], 2, 2);
435
+ let block = tree.add(vec![Value::static_symbol("block"), Value::Sexp(call), Value::Sexp(lit)], 1, 2);
436
+ (tree, block)
437
+ }
438
+
439
+ fn satisfied(source: &str) -> Vec<bool> {
440
+ let (tree, block) = sample();
441
+ let filter = Filter::parse(source).unwrap();
442
+ let mut sexps = vec![block];
443
+ tree.deep_each(block, |sexp| {
444
+ sexps.push(sexp);
445
+ true
446
+ });
447
+ sexps.iter().map(|sexp| filter.satisfy(&tree, &Value::Sexp(*sexp)).unwrap()).collect()
448
+ }
449
+
450
+ #[test]
451
+ fn satisfies_like_sexp_matcher() {
452
+ // Pre-order: block, call, str, lit.
453
+ assert_eq!(satisfied("(call nil :puts ___)"), [false, true, false, false]);
454
+ assert_eq!(satisfied("(call nil :puts _)"), [false, true, false, false]);
455
+ assert_eq!(satisfied("(call nil :puts)"), [false, false, false, false]);
456
+ assert_eq!(satisfied("[t lit]"), [false, false, false, true]);
457
+ assert_eq!(satisfied("[any [t lit] [t str]]"), [false, false, true, true]);
458
+ assert_eq!(satisfied("[child (str ___)]"), [true, true, true, false]);
459
+ assert_eq!(satisfied("[include [m /^pu/]]"), [false, true, false, false]);
460
+ assert_eq!(satisfied("(_ [k Integer])"), [false, false, false, true]);
461
+ assert_eq!(satisfied("[not? [t block]]"), [false, true, true, true]);
462
+ }
463
+
464
+ #[test]
465
+ fn filter_sexp_deletes_satisfying_sexps_below_the_root() {
466
+ let (mut tree, block) = sample();
467
+ let filters = [Filter::parse("(call nil :puts ___)").unwrap(), Filter::parse("[t block]").unwrap()];
468
+ filter_sexp(&mut tree, block, &filters).unwrap();
469
+ assert_eq!(crate::sexp::dump(&tree, &Value::Sexp(block)), "(@1 :block (@2 :lit 1))");
470
+ tree.finish();
471
+ tree.finish();
472
+ assert_eq!(tree.mass(block), 2);
473
+ }
474
+
475
+ #[test]
476
+ fn raises_as_ruby_does() {
477
+ let (mut tree, block) = sample();
478
+ let before = crate::sexp::dump(&tree, &Value::Sexp(block));
479
+ let filters = [Filter::parse("[child foo]").unwrap()];
480
+ let error = filter_sexp(&mut tree, block, &filters).unwrap_err();
481
+ assert_eq!(error.class, "NoMethodError");
482
+ assert_eq!(error.message, "undefined method `satisfy?' for an instance of Symbol");
483
+ assert_eq!(crate::sexp::dump(&tree, &Value::Sexp(block)), before);
484
+ let error = Filter::parse("[k foo]").unwrap().satisfy(&tree, &Value::Sexp(block)).unwrap_err();
485
+ assert_eq!((error.class, error.message.as_str()), ("TypeError", "class or module required"));
486
+ }
487
+ }