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,340 @@
1
+ //! A filter as text, in the format `parity/matcher_serializer.rb` writes
2
+ //! for any Ruby object built with `Sexp::Matcher.parse` or the `s{}` DSL:
3
+ //!
4
+ //! ```text
5
+ //! object = "(" CLASS object* ")" a Sexp::Matcher (CLASS without "Sexp::"):
6
+ //! Matcher: its elements
7
+ //! Wild, Remaining, Atom: nothing
8
+ //! Any, All: options
9
+ //! Not, Include: value; Child: child
10
+ //! Pattern, Klass: pattern; Type: sexp_type
11
+ //! Sibling: subject sibling distance
12
+ //! | "(complex" object object ")" | "(range" object object BOOL ")"
13
+ //! | "nil" | "true" | "false"
14
+ //! | "i:" DECIMAL Integer
15
+ //! | "f:" HEX Float, its 8 bytes big-endian
16
+ //! | "rational:" DECIMAL ":" DECIMAL
17
+ //! | "sym:" ENCODING ":" HEX Symbol, its bytes
18
+ //! | "str:" ENCODING ":" HEX String
19
+ //! | "regexp:" ENCODING ":" OPTIONS ":" HEX Regexp: options, source
20
+ //! | "class:" MASK ":" HEX | "module:" MASK ":" HEX
21
+ //! Module: which TREE_CLASSES are kinds
22
+ //! of it, its name
23
+ //! ```
24
+
25
+ use std::sync::Mutex;
26
+
27
+ use super::parser::decimal;
28
+ use super::regexp::{CompileError, CompiledRegexp, US_ASCII};
29
+ use super::{Filter, Matcher, Module, Object, Result};
30
+ use crate::sexp::{self, Encoding, Integer, RubyString, Tree, Value, ASCII_8BIT, UTF_8};
31
+ use crate::RubyException;
32
+
33
+ /// Reads a filter.
34
+ pub fn read(text: &str) -> Result<Filter> {
35
+ let mut reader = Reader { tokens: tokens(text).into_iter(), symbols: Tree::default() };
36
+ let object = reader.object()?;
37
+ if reader.tokens.next().is_some() {
38
+ return Err(format_error("text after the filter"));
39
+ }
40
+ Ok(Filter { symbols: reader.symbols, object })
41
+ }
42
+
43
+ fn tokens(text: &str) -> Vec<&str> {
44
+ let mut tokens = Vec::new();
45
+ let mut start = None;
46
+ for (index, character) in text.char_indices() {
47
+ let separator = character.is_whitespace() || character == '(' || character == ')';
48
+ if separator {
49
+ if let Some(from) = start.take() {
50
+ tokens.push(&text[from..index]);
51
+ }
52
+ if character != ')' && character != '(' {
53
+ continue;
54
+ }
55
+ tokens.push(&text[index..index + 1]);
56
+ } else if start.is_none() {
57
+ start = Some(index);
58
+ }
59
+ }
60
+ if let Some(from) = start {
61
+ tokens.push(&text[from..]);
62
+ }
63
+ tokens
64
+ }
65
+
66
+ fn format_error(what: &str) -> RubyException {
67
+ RubyException { class: "ArgumentError", message: format!("flay_rs cannot read the serialized filter: {what}") }
68
+ }
69
+
70
+ struct Reader<'a> {
71
+ tokens: std::vec::IntoIter<&'a str>,
72
+ symbols: Tree,
73
+ }
74
+
75
+ impl<'a> Reader<'a> {
76
+ fn next(&mut self) -> Result<&'a str> {
77
+ self.tokens.next().ok_or_else(|| format_error("unexpected end"))
78
+ }
79
+
80
+ fn object(&mut self) -> Result<Object> {
81
+ let token = self.next()?;
82
+ if token == "(" {
83
+ let class = self.next()?.to_string();
84
+ let mut arguments = Vec::new();
85
+ loop {
86
+ match self.tokens.as_slice().first() {
87
+ Some(&")") => {
88
+ self.tokens.next();
89
+ break;
90
+ }
91
+ Some(_) => arguments.push(self.object()?),
92
+ None => return Err(format_error("unbalanced parentheses")),
93
+ }
94
+ }
95
+ return compound(&class, arguments);
96
+ }
97
+ self.atom(token)
98
+ }
99
+
100
+ fn atom(&mut self, token: &'a str) -> Result<Object> {
101
+ let value = match token {
102
+ "nil" => Value::Nil,
103
+ "true" => Value::True,
104
+ "false" => Value::False,
105
+ _ => {
106
+ let (kind, rest) = token.split_once(':').ok_or_else(|| format_error(token))?;
107
+ let fields: Vec<&str> = rest.splitn(if kind == "regexp" { 3 } else { 2 }, ':').collect();
108
+ match (kind, fields.as_slice()) {
109
+ ("i", [digits]) => Value::integer(signed_decimal(digits)?),
110
+ ("f", [bits]) => {
111
+ let bits = u64::from_str_radix(bits, 16).map_err(|_| format_error(token))?;
112
+ Value::Float(f64::from_bits(bits))
113
+ }
114
+ ("rational", [numerator, denominator]) => {
115
+ Value::Rational(Box::new((signed_decimal(numerator)?, signed_decimal(denominator)?)))
116
+ }
117
+ ("sym", [encoding, bytes]) => self.symbols.intern(&unhex(bytes)?, static_encoding(encoding)),
118
+ ("str", [encoding, bytes]) => Value::string(RubyString::new(unhex(bytes)?, static_encoding(encoding))),
119
+ ("regexp", [encoding, options, source]) => Value::Regexp(Box::new(sexp::Regexp {
120
+ source: unhex(source)?,
121
+ options: options.parse().map_err(|_| format_error(token))?,
122
+ encoding: static_encoding(encoding),
123
+ })),
124
+ ("class" | "module", [mask, name]) => {
125
+ return Ok(Object::Module(Module {
126
+ name: String::from_utf8_lossy(&unhex(name)?).into_owned(),
127
+ is_class: kind == "class",
128
+ tree_classes: mask.parse().map_err(|_| format_error(token))?,
129
+ }));
130
+ }
131
+ _ => return Err(format_error(token)),
132
+ }
133
+ }
134
+ };
135
+ Ok(Object::Value(value))
136
+ }
137
+ }
138
+
139
+ /// A `(CLASS ...)` object.
140
+ fn compound(class: &str, arguments: Vec<Object>) -> Result<Object> {
141
+ let count = arguments.len();
142
+ let mut arguments = arguments.into_iter();
143
+ let mut take = || arguments.next().ok_or_else(|| format_error(&format!("too few arguments for {class}")));
144
+ let exact = |expected: usize| {
145
+ if count == expected {
146
+ Ok(())
147
+ } else {
148
+ Err(format_error(&format!("{count} arguments for {class}")))
149
+ }
150
+ };
151
+ let matcher = match class {
152
+ "complex" => {
153
+ exact(2)?;
154
+ let (Object::Value(real), Object::Value(imaginary)) = (take()?, take()?) else {
155
+ return Err(format_error("a complex part that is not a number"));
156
+ };
157
+ return Ok(Object::Value(Value::Complex(Box::new((real, imaginary)))));
158
+ }
159
+ "range" => {
160
+ exact(3)?;
161
+ let bound = |object: Object| match object {
162
+ Object::Value(Value::Nil) => Ok(None),
163
+ Object::Value(Value::Integer(integer)) => Ok(Some(*integer)),
164
+ _ => Err(format_error("a range bound that is not an Integer or nil")),
165
+ };
166
+ let (first, last) = (bound(take()?)?, bound(take()?)?);
167
+ let exclusive = matches!(take()?, Object::Value(Value::True));
168
+ return Ok(Object::Value(Value::Range(Box::new((first, last, exclusive)))));
169
+ }
170
+ "Matcher" => Matcher::Matcher(arguments.collect()),
171
+ "Any" => Matcher::Any(arguments.collect()),
172
+ "All" => Matcher::All(arguments.collect()),
173
+ "Wild" | "Remaining" | "Atom" => {
174
+ exact(0)?;
175
+ match class {
176
+ "Wild" => Matcher::Wild,
177
+ "Remaining" => Matcher::Remaining,
178
+ _ => Matcher::Atom,
179
+ }
180
+ }
181
+ "Not" | "Child" | "Klass" | "Type" | "Include" | "Pattern" => {
182
+ exact(1)?;
183
+ let argument = take()?;
184
+ match class {
185
+ "Not" => Matcher::Not(argument),
186
+ "Child" => Matcher::Child(argument),
187
+ "Klass" => Matcher::Klass(argument),
188
+ "Type" => Matcher::Type(argument),
189
+ "Include" => Matcher::Include(argument),
190
+ _ => Matcher::Pattern(pattern(argument)?),
191
+ }
192
+ }
193
+ "Sibling" => {
194
+ exact(3)?;
195
+ Matcher::Sibling { subject: take()?, sibling: take()?, distance: take()? }
196
+ }
197
+ _ => return Err(format_error(&format!("unknown class {class}"))),
198
+ };
199
+ Ok(Object::Matcher(Box::new(matcher)))
200
+ }
201
+
202
+ /// The `pattern` of a `Sexp::Pattern`, compiled.
203
+ fn pattern(object: Object) -> Result<CompiledRegexp> {
204
+ let Object::Value(Value::Regexp(regexp)) = object else {
205
+ return Err(format_error("a Sexp::Pattern whose pattern is not a Regexp"));
206
+ };
207
+ CompiledRegexp::new(*regexp.clone()).map_err(|error| {
208
+ let source = String::from_utf8_lossy(&regexp.source).into_owned();
209
+ match error {
210
+ CompileError::Syntax(message) => format_error(&format!("{message}: /{source}/")),
211
+ CompileError::Unsupported(what) => RubyException {
212
+ class: "NotImplementedError",
213
+ message: format!("flay_rs does not support {what} in a Sexp::Pattern: /{source}/"),
214
+ },
215
+ }
216
+ })
217
+ }
218
+
219
+ fn signed_decimal(text: &str) -> Result<Integer> {
220
+ let (negative, digits) = match text.strip_prefix('-') {
221
+ Some(digits) => (true, digits),
222
+ None => (false, text),
223
+ };
224
+ if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
225
+ return Err(format_error(text));
226
+ }
227
+ let magnitude = decimal(digits);
228
+ Ok(Integer::new(negative, &magnitude.limbs))
229
+ }
230
+
231
+ fn unhex(text: &str) -> Result<Vec<u8>> {
232
+ if text.len() % 2 != 0 {
233
+ return Err(format_error(text));
234
+ }
235
+ (0..text.len())
236
+ .step_by(2)
237
+ .map(|index| u8::from_str_radix(&text[index..index + 2], 16).map_err(|_| format_error(text)))
238
+ .collect()
239
+ }
240
+
241
+ /// An encoding name as an [`Encoding`]: the ones the crate names, or the
242
+ /// name kept for the rest of the process.
243
+ fn static_encoding(name: &str) -> Encoding {
244
+ static NAMES: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
245
+ for known in [UTF_8, ASCII_8BIT, US_ASCII] {
246
+ if known == name {
247
+ return known;
248
+ }
249
+ }
250
+ let mut names = NAMES.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
251
+ if let Some(known) = names.iter().find(|known| **known == name) {
252
+ return known;
253
+ }
254
+ let leaked: &'static str = Box::leak(name.to_string().into_boxed_str());
255
+ names.push(leaked);
256
+ leaked
257
+ }
258
+
259
+ /// Writes a filter's object.
260
+ pub fn write(symbols: &Tree, object: &Object) -> String {
261
+ let mut text = String::new();
262
+ write_object(&mut text, symbols, object);
263
+ text
264
+ }
265
+
266
+ fn hex(bytes: &[u8]) -> String {
267
+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()
268
+ }
269
+
270
+ fn write_object(out: &mut String, symbols: &Tree, object: &Object) {
271
+ match object {
272
+ Object::Value(value) => write_value(out, symbols, value),
273
+ Object::Module(module) => {
274
+ let kind = if module.is_class { "class" } else { "module" };
275
+ out.push_str(&format!("{kind}:{}:{}", module.tree_classes, hex(module.name.as_bytes())));
276
+ }
277
+ Object::Matcher(matcher) => {
278
+ let list = |out: &mut String, class: &str, objects: &[&Object]| {
279
+ out.push('(');
280
+ out.push_str(class);
281
+ for object in objects {
282
+ out.push(' ');
283
+ write_object(out, symbols, object);
284
+ }
285
+ out.push(')');
286
+ };
287
+ match &**matcher {
288
+ Matcher::Matcher(elements) => list(out, "Matcher", &elements.iter().collect::<Vec<_>>()),
289
+ Matcher::Wild => list(out, "Wild", &[]),
290
+ Matcher::Remaining => list(out, "Remaining", &[]),
291
+ Matcher::Atom => list(out, "Atom", &[]),
292
+ Matcher::Any(options) => list(out, "Any", &options.iter().collect::<Vec<_>>()),
293
+ Matcher::All(options) => list(out, "All", &options.iter().collect::<Vec<_>>()),
294
+ Matcher::Not(value) => list(out, "Not", &[value]),
295
+ Matcher::Child(child) => list(out, "Child", &[child]),
296
+ Matcher::Include(value) => list(out, "Include", &[value]),
297
+ Matcher::Klass(pattern) => list(out, "Klass", &[pattern]),
298
+ Matcher::Type(sexp_type) => list(out, "Type", &[sexp_type]),
299
+ Matcher::Pattern(pattern) => {
300
+ out.push_str("(Pattern ");
301
+ write_value(out, symbols, &Value::Regexp(Box::new(pattern.regexp.clone())));
302
+ out.push(')');
303
+ }
304
+ Matcher::Sibling { subject, sibling, distance } => list(out, "Sibling", &[subject, sibling, distance]),
305
+ }
306
+ }
307
+ }
308
+ }
309
+
310
+ fn write_value(out: &mut String, symbols: &Tree, value: &Value) {
311
+ let text = match value {
312
+ Value::Nil => "nil".to_string(),
313
+ Value::True => "true".to_string(),
314
+ Value::False => "false".to_string(),
315
+ Value::Integer(integer) => format!("i:{}", integer.to_s()),
316
+ Value::Float(float) => format!("f:{:016x}", float.to_bits()),
317
+ Value::Rational(rational) => format!("rational:{}:{}", rational.0.to_s(), rational.1.to_s()),
318
+ Value::Symbol(id) => {
319
+ // Ruby gives an ASCII-only Symbol the encoding US-ASCII.
320
+ let (bytes, encoding) = symbols.symbol(*id);
321
+ format!("sym:{}:{}", if bytes.is_ascii() { US_ASCII } else { encoding }, hex(bytes))
322
+ }
323
+ Value::String(string) => format!("str:{}:{}", string.encoding, hex(&string.bytes)),
324
+ Value::Regexp(regexp) => format!("regexp:{}:{}:{}", regexp.encoding, regexp.options, hex(&regexp.source)),
325
+ Value::Complex(complex) => {
326
+ out.push_str("(complex ");
327
+ write_value(out, symbols, &complex.0);
328
+ out.push(' ');
329
+ write_value(out, symbols, &complex.1);
330
+ out.push(')');
331
+ return;
332
+ }
333
+ Value::Range(range) => {
334
+ let bound = |bound: &Option<Integer>| bound.as_ref().map_or("nil".to_string(), |integer| format!("i:{}", integer.to_s()));
335
+ format!("(range {} {} {})", bound(&range.0), bound(&range.1), range.2)
336
+ }
337
+ Value::Array(_) | Value::Sexp(_) => unreachable!("filters hold no Arrays or plain sexps"),
338
+ };
339
+ out.push_str(&text);
340
+ }