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,345 @@
1
+ //! `Sexp::Matcher::Parser`: `Sexp::Matcher.parse`.
2
+ //!
3
+ //! The parser resolves constants (`[k String]`) with `Object.const_get` in
4
+ //! Ruby. This port knows the constants in [`constant`]; any other name
5
+ //! raises `NameError` as an undefined constant does.
6
+
7
+ use std::collections::VecDeque;
8
+
9
+ use super::regexp::{self, CompileError, CompiledRegexp, FIXEDENCODING, US_ASCII};
10
+ use super::ruby_text::{object_inspect, object_to_s, string_inspect};
11
+ use super::{Filter, Matcher, Module, Object, Result, TREE_CLASSES};
12
+ use crate::sexp::{self, Integer, RubyString, Tree, Value, UTF_8};
13
+ use crate::RubyException;
14
+
15
+ /// `Sexp::Matcher.parse(s)`: `Parser.new(s).parse`.
16
+ pub fn parse(source: &str) -> Result<Filter> {
17
+ let mut parser = Parser { tokens: lex(source), symbols: Tree::default() };
18
+ let object = parser.parse()?;
19
+ Ok(Filter { symbols: parser.symbols, object })
20
+ }
21
+
22
+ /// `Parser#lex`: `s.scan %r%[()\[\]]|\"[^"]*\"|/[^/]*/|:?[\w?!=~-]+%`.
23
+ /// Text that no alternative matches is skipped.
24
+ fn lex(source: &str) -> VecDeque<&str> {
25
+ let bytes = source.as_bytes();
26
+ let is_word = |byte: u8| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'?' | b'!' | b'=' | b'~' | b'-');
27
+ let mut tokens = VecDeque::new();
28
+ let mut index = 0;
29
+ while index < bytes.len() {
30
+ let start = index;
31
+ let end = match bytes[index] {
32
+ b'(' | b')' | b'[' | b']' => Some(index + 1),
33
+ quote @ (b'"' | b'/') => bytes[index + 1..].iter().position(|byte| *byte == quote).map(|offset| index + offset + 2),
34
+ b':' if bytes.get(index + 1).is_some_and(|byte| is_word(*byte)) => {
35
+ Some(index + 1 + bytes[index + 1..].iter().take_while(|byte| is_word(**byte)).count())
36
+ }
37
+ byte if is_word(byte) => Some(index + bytes[index..].iter().take_while(|byte| is_word(**byte)).count()),
38
+ _ => None,
39
+ };
40
+ match end {
41
+ Some(end) => {
42
+ tokens.push_back(&source[start..end]);
43
+ index = end;
44
+ }
45
+ None => index += 1,
46
+ }
47
+ }
48
+ tokens
49
+ }
50
+
51
+ fn syntax_error(message: String) -> RubyException {
52
+ RubyException { class: "SyntaxError", message }
53
+ }
54
+
55
+ fn argument_error(message: String) -> RubyException {
56
+ RubyException { class: "ArgumentError", message }
57
+ }
58
+
59
+ struct Parser<'a> {
60
+ tokens: VecDeque<&'a str>,
61
+ symbols: Tree,
62
+ }
63
+
64
+ impl<'a> Parser<'a> {
65
+ /// `result = parse_sexp until tokens.empty?`: the last object parsed,
66
+ /// `nil` when there are no tokens.
67
+ fn parse(&mut self) -> Result<Object> {
68
+ let mut result = Object::Value(Value::Nil);
69
+ while !self.tokens.is_empty() {
70
+ result = self.parse_sexp()?;
71
+ }
72
+ Ok(result)
73
+ }
74
+
75
+ /// `next_token`.
76
+ fn next_token(&mut self) -> Result<&'a str> {
77
+ self.tokens.pop_front().ok_or_else(|| syntax_error("unbalanced input".to_string()))
78
+ }
79
+
80
+ /// `parse_sexp`. The `when` regexps use `^` and `$`, so they match any
81
+ /// line of a token (`"..."` and `/.../` tokens can span lines).
82
+ fn parse_sexp(&mut self) -> Result<Object> {
83
+ let token = self.next_token()?;
84
+ let lines = || token.split('\n');
85
+ match token {
86
+ "(" => return self.parse_list(),
87
+ "[" => return self.parse_cmd(),
88
+ "nil" => return Ok(Object::Value(Value::Nil)),
89
+ _ => {}
90
+ }
91
+ // when /^\d+$/ then token.to_i
92
+ if lines().any(|line| !line.is_empty() && line.bytes().all(|byte| byte.is_ascii_digit())) {
93
+ let integer = if token.bytes().all(|byte| byte.is_ascii_digit()) { decimal(token) } else { Integer::from_i64(0) };
94
+ return Ok(Object::Value(Value::integer(integer)));
95
+ }
96
+ match token {
97
+ "___" => return Ok(matcher(Matcher::Remaining)),
98
+ "_" => return Ok(matcher(Matcher::Wild)),
99
+ _ => {}
100
+ }
101
+ // when %r%^/(.*)/$%
102
+ if let Some(source) = lines().find_map(|line| enclosed(line, '/')) {
103
+ return self.regexp_literal(source);
104
+ }
105
+ // when /^"(.*)"$/ then $1
106
+ if let Some(text) = lines().find_map(|line| enclosed(line, '"')) {
107
+ return Ok(Object::Value(Value::string(RubyString::new(text, UTF_8))));
108
+ }
109
+ // when /^([A-Z]\w*)$/ then Object.const_get $1
110
+ let is_constant_name = |line: &str| {
111
+ line.starts_with(|first: char| first.is_ascii_uppercase())
112
+ && line.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
113
+ };
114
+ if let Some(name) = lines().find(|line| is_constant_name(line)) {
115
+ return constant(name).map(Object::Module);
116
+ }
117
+ // when /^:?([\w?!=~-]+)$/ then $1.to_sym
118
+ let is_name = |text: &str| {
119
+ !text.is_empty()
120
+ && text.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'?' | b'!' | b'=' | b'~' | b'-'))
121
+ };
122
+ let name = lines().find_map(|line| match line.strip_prefix(':') {
123
+ Some(rest) if is_name(rest) => Some(rest),
124
+ _ => is_name(line).then_some(line),
125
+ });
126
+ if let Some(name) = name {
127
+ return Ok(Object::Value(self.symbols.intern(name.as_bytes(), US_ASCII)));
128
+ }
129
+ let inspected = string_inspect(token.as_bytes(), UTF_8)?;
130
+ Err(syntax_error(format!("unhandled token: {}", String::from_utf8_lossy(&inspected))))
131
+ }
132
+
133
+ /// A `/.../` token: only `[\w()|.*+^$]` may appear in it, then
134
+ /// `Regexp.new re`.
135
+ fn regexp_literal(&mut self, source: &str) -> Result<Object> {
136
+ let allowed = |byte: u8| byte.is_ascii_alphanumeric() || b"_()|.*+^$".contains(&byte);
137
+ if source.is_empty() || !source.bytes().all(allowed) {
138
+ let inspected = string_inspect(source.as_bytes(), UTF_8)?;
139
+ return Err(syntax_error(format!("Not allowed: /{}/", String::from_utf8_lossy(&inspected))));
140
+ }
141
+ let regexp = sexp::Regexp { source: source.as_bytes().to_vec(), options: 0, encoding: US_ASCII };
142
+ compile(regexp.clone())?;
143
+ Ok(Object::Value(Value::Regexp(Box::new(regexp))))
144
+ }
145
+
146
+ /// `parse_list`: objects up to `)`, as a `Sexp::Matcher`.
147
+ fn parse_list(&mut self) -> Result<Object> {
148
+ let elements = self.parse_until(")")?;
149
+ Ok(matcher(Matcher::Matcher(elements)))
150
+ }
151
+
152
+ /// Objects up to `close`, then `next_token` (which raises at the end).
153
+ fn parse_until(&mut self, close: &str) -> Result<Vec<Object>> {
154
+ let mut objects = Vec::new();
155
+ while self.tokens.front().is_some_and(|token| *token != close) {
156
+ objects.push(self.parse_sexp()?);
157
+ }
158
+ self.next_token()?;
159
+ Ok(objects)
160
+ }
161
+
162
+ /// `parse_cmd`: `[cmd args...]` calls `Sexp.cmd(*args)` for a command
163
+ /// in `ALLOWED`.
164
+ fn parse_cmd(&mut self) -> Result<Object> {
165
+ let mut args = self.parse_until("]")?;
166
+ let cmd = if args.is_empty() { Object::Value(Value::Nil) } else { args.remove(0) };
167
+ let name = match &cmd {
168
+ Object::Value(Value::Symbol(id)) => self.symbols.symbol(*id).0,
169
+ _ => b"",
170
+ };
171
+ let one = |args: Vec<Object>| -> Result<Object> {
172
+ let given = args.len();
173
+ let mut args = args.into_iter();
174
+ match (args.next(), args.next()) {
175
+ (Some(arg), None) => Ok(arg),
176
+ _ => Err(argument_error(format!("wrong number of arguments (given {given}, expected 1)"))),
177
+ }
178
+ };
179
+ Ok(matcher(match name {
180
+ b"t" => Matcher::Type(one(args)?),
181
+ b"m" => self.m(&args)?,
182
+ b"k" => Matcher::Klass(one(args)?),
183
+ b"atom" if args.is_empty() => Matcher::Atom,
184
+ b"atom" => return Err(argument_error(format!("wrong number of arguments (given {}, expected 0)", args.len()))),
185
+ b"not?" | b"-" => Matcher::Not(one(args)?),
186
+ b"any" => Matcher::Any(args),
187
+ b"child" => Matcher::Child(one(args)?),
188
+ b"include" => Matcher::Include(one(args)?),
189
+ _ => {
190
+ let inspected = object_inspect(&self.symbols, &cmd)?;
191
+ return Err(syntax_error(format!("bad cmd: {}", String::from_utf8_lossy(&inspected))));
192
+ }
193
+ }))
194
+ }
195
+
196
+ /// `Sexp.m(*values)`: a Regexp as is, anything else as
197
+ /// `Regexp.new "\\A%s\\Z" % Regexp.escape(value.to_s)`, all joined with
198
+ /// `Regexp.union`, in a `Sexp::Pattern`.
199
+ fn m(&self, values: &[Object]) -> Result<Matcher> {
200
+ let mut regexps = Vec::new();
201
+ for value in values {
202
+ let regexp = match value {
203
+ Object::Value(Value::Regexp(regexp)) => (**regexp).clone(),
204
+ other => {
205
+ let text = object_to_s(&self.symbols, other)?;
206
+ new_regexp([b"\\A".as_slice(), &regexp::escape(&text), b"\\Z"].concat())
207
+ }
208
+ };
209
+ regexps.push(regexp);
210
+ }
211
+ let union = match regexps.len() {
212
+ 0 => new_regexp(b"(?!)".to_vec()),
213
+ 1 => regexps.pop().unwrap(),
214
+ _ => {
215
+ let mut parts = Vec::new();
216
+ for regexp in &regexps {
217
+ parts.push(regexp::to_s(regexp, None)?);
218
+ }
219
+ new_regexp(parts.join(b"|".as_slice()))
220
+ }
221
+ };
222
+ Ok(Matcher::Pattern(compile(union)?))
223
+ }
224
+ }
225
+
226
+ fn matcher(matcher: Matcher) -> Object {
227
+ Object::Matcher(Box::new(matcher))
228
+ }
229
+
230
+ /// The text between `quote` characters that start and end `line`.
231
+ fn enclosed(line: &str, quote: char) -> Option<&str> {
232
+ (line.len() >= 2).then_some(())?;
233
+ line.strip_prefix(quote)?.strip_suffix(quote)
234
+ }
235
+
236
+ /// `Regexp.new(source)` for a source built from UTF-8 text: US-ASCII
237
+ /// when the source is ASCII, UTF-8 with a fixed encoding otherwise.
238
+ fn new_regexp(source: Vec<u8>) -> sexp::Regexp {
239
+ if source.is_ascii() {
240
+ sexp::Regexp { source, options: 0, encoding: US_ASCII }
241
+ } else {
242
+ sexp::Regexp { source, options: FIXEDENCODING, encoding: UTF_8 }
243
+ }
244
+ }
245
+
246
+ /// Compiles a regexp, raising `RegexpError` as `Regexp.new` does.
247
+ fn compile(regexp: sexp::Regexp) -> Result<CompiledRegexp> {
248
+ let source = regexp::inspect(&regexp)?;
249
+ CompiledRegexp::new(regexp).map_err(|error| match error {
250
+ CompileError::Syntax(message) => RubyException {
251
+ class: "RegexpError",
252
+ message: format!("{message}: {}", String::from_utf8_lossy(&source)),
253
+ },
254
+ CompileError::Unsupported(what) => RubyException {
255
+ class: "NotImplementedError",
256
+ message: format!("flay_rs does not support {what} in {}", String::from_utf8_lossy(&source)),
257
+ },
258
+ })
259
+ }
260
+
261
+ /// An Integer from ASCII decimal digits.
262
+ pub fn decimal(digits: &str) -> Integer {
263
+ let mut limbs: Vec<u32> = Vec::new();
264
+ for digit in digits.bytes() {
265
+ let mut carry = u64::from(digit - b'0');
266
+ for limb in &mut limbs {
267
+ let wide = u64::from(*limb) * 10 + carry;
268
+ *limb = wide as u32;
269
+ carry = wide >> 32;
270
+ }
271
+ if carry > 0 {
272
+ limbs.push(carry as u32);
273
+ }
274
+ }
275
+ Integer::new(false, &limbs)
276
+ }
277
+
278
+ /// `Object.const_get(name)` for the constants this port knows: the classes
279
+ /// of tree values, their ancestors, and some other core classes and
280
+ /// modules (which no tree value is a kind of).
281
+ fn constant(name: &str) -> Result<Module> {
282
+ let bit = |class: &str| 1u16 << TREE_CLASSES.iter().position(|candidate| *candidate == class).unwrap();
283
+ let bits = |classes: &[&str]| classes.iter().fold(0, |mask, class| mask | bit(class));
284
+ let all = (1u16 << TREE_CLASSES.len()) - 1;
285
+ let (is_class, tree_classes) = match name {
286
+ "BasicObject" | "Object" => (true, all),
287
+ "Kernel" => (false, all),
288
+ "Comparable" => (false, bits(&["Symbol", "String", "Integer", "Float", "Rational", "Complex"])),
289
+ "Enumerable" => (false, bits(&["Range", "Array", "Sexp"])),
290
+ "Numeric" => (true, bits(&["Integer", "Float", "Rational", "Complex"])),
291
+ "Array" => (true, bits(&["Array", "Sexp"])),
292
+ _ if TREE_CLASSES.contains(&name) => (true, bit(name)),
293
+ "Hash" | "Struct" | "Proc" | "Method" | "Class" | "Module" | "Exception" | "StandardError" | "Time"
294
+ | "IO" | "File" | "Dir" | "Encoding" | "Thread" | "Random" | "Data" => (true, 0),
295
+ "Math" | "Process" | "GC" | "ObjectSpace" | "Signal" | "Marshal" | "Errno" => (false, 0),
296
+ _ => {
297
+ return Err(RubyException { class: "NameError", message: format!("uninitialized constant {name}") });
298
+ }
299
+ };
300
+ Ok(Module { name: name.to_string(), is_class, tree_classes })
301
+ }
302
+
303
+ #[cfg(test)]
304
+ mod tests {
305
+ use super::*;
306
+
307
+ fn error(source: &str) -> (String, String) {
308
+ let error = parse(source).unwrap_err();
309
+ (error.class.to_string(), error.message)
310
+ }
311
+
312
+ #[test]
313
+ fn lexes_like_string_scan() {
314
+ assert_eq!(Vec::from(lex("q(:call, nil, ___)")), ["q", "(", ":call", "nil", "___", ")"]);
315
+ assert_eq!(Vec::from(lex("\"a b\" /x/ \"open")), ["\"a b\"", "/x/", "open"]);
316
+ }
317
+
318
+ #[test]
319
+ fn raises_as_ruby_does() {
320
+ let pair = |class: &str, message: &str| (class.to_string(), message.to_string());
321
+ assert_eq!(error("(a"), pair("SyntaxError", "unbalanced input"));
322
+ assert_eq!(error(")"), pair("SyntaxError", "unhandled token: \")\""));
323
+ assert_eq!(error("[bad x]"), pair("SyntaxError", "bad cmd: :bad"));
324
+ assert_eq!(error("[]"), pair("SyntaxError", "bad cmd: nil"));
325
+ assert_eq!(error("/a b/"), pair("SyntaxError", "Not allowed: /\"a b\"/"));
326
+ assert_eq!(error("/(a/"), pair("RegexpError", "end pattern with unmatched parenthesis: /(a/"));
327
+ assert_eq!(error("[t a b]"), pair("ArgumentError", "wrong number of arguments (given 2, expected 1)"));
328
+ assert_eq!(error("[m [t a]]"), pair("ArgumentError", "wrong number of arguments (given 0, expected 1)"));
329
+ assert_eq!(error("Foo"), pair("NameError", "uninitialized constant Foo"));
330
+ }
331
+
332
+ #[test]
333
+ fn builds_the_regexps_sexp_m_builds() {
334
+ let serialized = |source: &str| parse(source).unwrap().serialize();
335
+ assert_eq!(serialized("[m a]"), format!("(Pattern regexp:US-ASCII:0:{})", hex(b"\\Aa\\Z")));
336
+ assert_eq!(serialized("[m (a b)]"), format!("(Pattern regexp:US-ASCII:0:{})", hex(b"\\As\\(:a,\\ :b\\)\\Z")));
337
+ let union = b"(?-mix:\\Aa\\Z)|(?-mix:\\Ab\\Z)";
338
+ assert_eq!(serialized("[m a b]"), format!("(Pattern regexp:US-ASCII:0:{})", hex(union)));
339
+ assert_eq!(serialized("\"x\n12\ny\""), "i:0");
340
+ }
341
+
342
+ fn hex(bytes: &[u8]) -> String {
343
+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()
344
+ }
345
+ }