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.
- checksums.yaml +7 -0
- data/Cargo.lock +495 -0
- data/Cargo.toml +23 -0
- data/DIVERGENCES.md +23 -0
- data/LICENSE +22 -0
- data/README.md +111 -0
- data/THIRD_PARTY_NOTICES.md +70 -0
- data/crates/flay-cli/Cargo.toml +22 -0
- data/crates/flay-cli/src/bin/flay-matcher-parity.rs +195 -0
- data/crates/flay-cli/src/main.rs +202 -0
- data/crates/flay-core/Cargo.toml +20 -0
- data/crates/flay-core/src/attach_comments.rs +353 -0
- data/crates/flay-core/src/erb.rs +418 -0
- data/crates/flay-core/src/lib.rs +488 -0
- data/crates/flay-core/src/matcher/parser.rs +345 -0
- data/crates/flay-core/src/matcher/regexp.rs +1243 -0
- data/crates/flay-core/src/matcher/ruby_text.rs +413 -0
- data/crates/flay-core/src/matcher/serialized.rs +340 -0
- data/crates/flay-core/src/matcher.rs +487 -0
- data/crates/flay-core/src/process.rs +312 -0
- data/crates/flay-core/src/report.rs +567 -0
- data/crates/flay-core/src/ruby2ruby.rs +3291 -0
- data/crates/flay-core/src/ruby_format.rs +163 -0
- data/crates/flay-core/src/ruby_sort.rs +246 -0
- data/crates/flay-core/src/sexp.rs +639 -0
- data/crates/flay-core/src/translate.rs +2290 -0
- data/crates/flay-core/tests/ruby2ruby_parity.rs +101 -0
- data/ext/flay_rs/Cargo.toml +17 -0
- data/ext/flay_rs/extconf.rb +6 -0
- data/ext/flay_rs/src/filters.rs +186 -0
- data/ext/flay_rs/src/lib.rs +544 -0
- data/lib/flay_rs/version.rb +8 -0
- data/lib/flay_rs.rb +18 -0
- metadata +94 -0
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
//! The ruby_parser `Sexp` tree that `Prism::Translation::RubyParser` builds,
|
|
2
|
+
//! stored in an arena, with the `Sexp` methods Flay 2.14.5 uses: `==`,
|
|
3
|
+
//! `mass`, `structural_hash` and `deep_each`.
|
|
4
|
+
|
|
5
|
+
use crate::ruby_format::{float_to_s, integer_to_s};
|
|
6
|
+
|
|
7
|
+
/// Index of a sexp in its [`Tree`].
|
|
8
|
+
pub type SexpId = u32;
|
|
9
|
+
|
|
10
|
+
/// A Ruby encoding name, as `Encoding#name` gives it ("UTF-8", "ASCII-8BIT").
|
|
11
|
+
pub type Encoding = &'static str;
|
|
12
|
+
|
|
13
|
+
pub const UTF_8: Encoding = "UTF-8";
|
|
14
|
+
pub const ASCII_8BIT: Encoding = "ASCII-8BIT";
|
|
15
|
+
|
|
16
|
+
/// A Ruby String or Symbol: its bytes and encoding.
|
|
17
|
+
#[derive(Clone, Debug)]
|
|
18
|
+
pub struct RubyString {
|
|
19
|
+
pub bytes: Vec<u8>,
|
|
20
|
+
pub encoding: Encoding,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
impl RubyString {
|
|
24
|
+
pub fn new(bytes: impl Into<Vec<u8>>, encoding: Encoding) -> Self {
|
|
25
|
+
RubyString { bytes: bytes.into(), encoding }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// `String#==` (and Symbol identity): the same bytes, in the same
|
|
29
|
+
/// encoding unless the bytes are all ASCII.
|
|
30
|
+
pub fn ruby_eq(&self, other: &RubyString) -> bool {
|
|
31
|
+
self.bytes == other.bytes && (self.encoding == other.encoding || self.bytes.is_ascii())
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// A Ruby Integer: sign and little-endian base 2**32 digits, without
|
|
36
|
+
/// leading zero digits. Zero is `{ negative: false, limbs: [] }`.
|
|
37
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
38
|
+
pub struct Integer {
|
|
39
|
+
pub negative: bool,
|
|
40
|
+
pub limbs: Vec<u32>,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
impl Integer {
|
|
44
|
+
pub fn new(negative: bool, limbs: &[u32]) -> Self {
|
|
45
|
+
let mut limbs = limbs.to_vec();
|
|
46
|
+
while limbs.last() == Some(&0) {
|
|
47
|
+
limbs.pop();
|
|
48
|
+
}
|
|
49
|
+
let negative = negative && !limbs.is_empty();
|
|
50
|
+
Integer { negative, limbs }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
pub fn from_i64(value: i64) -> Self {
|
|
54
|
+
let magnitude = value.unsigned_abs();
|
|
55
|
+
Integer::new(value < 0, &[magnitude as u32, (magnitude >> 32) as u32])
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pub fn is_zero(&self) -> bool {
|
|
59
|
+
self.limbs.is_empty()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
fn is_one(&self) -> bool {
|
|
63
|
+
!self.negative && self.limbs == [1]
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// The value as a float, as Ruby converts a Fixnum (`(double)n`).
|
|
67
|
+
fn to_f64(&self) -> f64 {
|
|
68
|
+
let magnitude = self.limbs.iter().rev().fold(0.0, |sum, limb| sum * 4_294_967_296.0 + f64::from(*limb));
|
|
69
|
+
if self.negative {
|
|
70
|
+
-magnitude
|
|
71
|
+
} else {
|
|
72
|
+
magnitude
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// The integer equal to `value`, or `None` when `value` has a fraction
|
|
77
|
+
/// or is not finite.
|
|
78
|
+
fn from_integral_f64(value: f64) -> Option<Self> {
|
|
79
|
+
if !value.is_finite() || value.fract() != 0.0 {
|
|
80
|
+
return None;
|
|
81
|
+
}
|
|
82
|
+
let bits = value.abs().to_bits();
|
|
83
|
+
let exponent = ((bits >> 52) & 0x7ff) as i32;
|
|
84
|
+
if exponent == 0 {
|
|
85
|
+
return Some(Integer::new(false, &[]));
|
|
86
|
+
}
|
|
87
|
+
let mantissa = (bits & ((1 << 52) - 1)) | (1 << 52);
|
|
88
|
+
let shift = exponent - 1075;
|
|
89
|
+
let mut limbs: Vec<u32> = vec![mantissa as u32, (mantissa >> 32) as u32];
|
|
90
|
+
if shift < 0 {
|
|
91
|
+
let shifted = mantissa >> (-shift);
|
|
92
|
+
limbs = vec![shifted as u32, (shifted >> 32) as u32];
|
|
93
|
+
} else {
|
|
94
|
+
let (whole, bits) = ((shift / 32) as usize, (shift % 32) as u32);
|
|
95
|
+
let mut shifted = vec![0u32; whole];
|
|
96
|
+
let mut carry = 0u32;
|
|
97
|
+
for limb in limbs {
|
|
98
|
+
let wide = (u64::from(limb) << bits) | u64::from(carry);
|
|
99
|
+
shifted.push(wide as u32);
|
|
100
|
+
carry = (wide >> 32) as u32;
|
|
101
|
+
}
|
|
102
|
+
shifted.push(carry);
|
|
103
|
+
limbs = shifted;
|
|
104
|
+
}
|
|
105
|
+
Some(Integer::new(value < 0.0, &limbs))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
pub fn to_s(&self) -> String {
|
|
109
|
+
integer_to_s(self.negative, &self.limbs)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/// A Ruby Regexp built by `Regexp.new(source, options)`.
|
|
114
|
+
#[derive(Clone, Debug)]
|
|
115
|
+
pub struct Regexp {
|
|
116
|
+
pub source: Vec<u8>,
|
|
117
|
+
/// `Regexp#options`.
|
|
118
|
+
pub options: u32,
|
|
119
|
+
pub encoding: Encoding,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// Index of a Symbol: below `STATIC_SYMBOLS.len()` a name from
|
|
123
|
+
/// [`STATIC_SYMBOLS`], above it a Symbol interned in the [`Tree`].
|
|
124
|
+
pub type SymbolId = u32;
|
|
125
|
+
|
|
126
|
+
/// The Symbols the translator writes in its own source (sexp types and a
|
|
127
|
+
/// few names), shared by every tree. All are ASCII.
|
|
128
|
+
pub const STATIC_SYMBOLS: &[&str] = &[
|
|
129
|
+
"!@", "&&", "*", "[]=", "||", "$!", "alias", "and", "arglist", "args", "array", "array_pat", "attrasgn",
|
|
130
|
+
"back_ref", "begin", "block", "block_pass", "break", "call", "case", "cdecl", "class", "colon2", "colon3",
|
|
131
|
+
"const", "cvar", "cvasgn", "cvdecl", "defined", "defn", "defs", "dot2", "dot3", "dregx", "dstr", "dsym",
|
|
132
|
+
"dxstr", "Encoding", "ensure", "evstr", "false", "find_pat", "flip2", "flip3", "for", "forward_args", "gasgn",
|
|
133
|
+
"gvar", "hash", "hash_pat", "iasgn", "if", "in", "it", "iter", "ivar", "kwarg", "kwrest", "kwsplat", "lambda",
|
|
134
|
+
"lasgn", "lit", "lvar", "masgn", "match", "match2", "match3", "module", "&nil", "**nil", "next", "nil", "not",
|
|
135
|
+
"nth_ref", "op_asgn", "op_asgn1", "op_asgn2", "op_asgn_and", "op_asgn_or", "or", "postexe", "preexe", "redo",
|
|
136
|
+
"resbody", "rescue", "retry", "return", "safe_attrasgn", "safe_call", "safe_op_asgn", "safe_op_asgn2",
|
|
137
|
+
"sclass", "self", "shadow", "space", "splat", "str", "super", "svalue", "to_ary", "true", "undef", "until",
|
|
138
|
+
"UTF_8", "valias", "when", "while", "xstr", "yield", "zsuper",
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
/// One element of a sexp: another sexp or a Ruby value. Kept to 16 bytes:
|
|
142
|
+
/// Symbols are interned and rarer values are boxed.
|
|
143
|
+
#[derive(Clone, Debug)]
|
|
144
|
+
pub enum Value {
|
|
145
|
+
Nil,
|
|
146
|
+
True,
|
|
147
|
+
False,
|
|
148
|
+
Symbol(SymbolId),
|
|
149
|
+
String(Box<RubyString>),
|
|
150
|
+
Integer(Box<Integer>),
|
|
151
|
+
Float(f64),
|
|
152
|
+
/// A normalized Rational: numerator, positive denominator.
|
|
153
|
+
Rational(Box<(Integer, Integer)>),
|
|
154
|
+
/// `Complex(real, imaginary)`.
|
|
155
|
+
Complex(Box<(Value, Value)>),
|
|
156
|
+
/// `Range.new(first, last, exclude_end)` with Integer or nil bounds.
|
|
157
|
+
Range(Box<(Option<Integer>, Option<Integer>, bool)>),
|
|
158
|
+
Regexp(Box<Regexp>),
|
|
159
|
+
/// A plain Ruby Array (not a Sexp).
|
|
160
|
+
Array(Box<Vec<Value>>),
|
|
161
|
+
Sexp(SexpId),
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
impl Value {
|
|
165
|
+
/// A Symbol from [`STATIC_SYMBOLS`].
|
|
166
|
+
pub fn static_symbol(name: &str) -> Value {
|
|
167
|
+
match STATIC_SYMBOLS.iter().position(|candidate| *candidate == name) {
|
|
168
|
+
Some(index) => Value::Symbol(index as SymbolId),
|
|
169
|
+
None => panic!("{name:?} is not in STATIC_SYMBOLS"),
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
pub fn integer(integer: Integer) -> Value {
|
|
174
|
+
Value::Integer(Box::new(integer))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
pub fn string(string: RubyString) -> Value {
|
|
178
|
+
Value::String(Box::new(string))
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
pub fn as_sexp(&self) -> Option<SexpId> {
|
|
182
|
+
match self {
|
|
183
|
+
Value::Sexp(id) => Some(*id),
|
|
184
|
+
_ => None,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/// One sexp: its elements (the first is its type), its line and `line_max`.
|
|
190
|
+
#[derive(Clone, Debug)]
|
|
191
|
+
pub struct Sexp {
|
|
192
|
+
pub elements: Vec<Value>,
|
|
193
|
+
pub line: i32,
|
|
194
|
+
pub line_max: i32,
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/// All the sexps one file's translation created.
|
|
198
|
+
#[derive(Clone, Debug, Default)]
|
|
199
|
+
pub struct Tree {
|
|
200
|
+
pub sexps: Vec<Sexp>,
|
|
201
|
+
/// Symbols from the source, indexed by `SymbolId - STATIC_SYMBOLS.len()`.
|
|
202
|
+
symbols: Vec<RubyString>,
|
|
203
|
+
/// Finds an interned Symbol while the tree is built.
|
|
204
|
+
symbol_index: std::collections::HashMap<(Vec<u8>, Encoding), SymbolId>,
|
|
205
|
+
/// `mass` of each sexp, filled in by [`Tree::finish`].
|
|
206
|
+
masses: Vec<u64>,
|
|
207
|
+
/// `structural_hash` of each sexp, filled in by [`Tree::finish`].
|
|
208
|
+
structural_hashes: Vec<u32>,
|
|
209
|
+
/// Each `class`, `module`, `defn` and `defs` sexp, with the byte offset
|
|
210
|
+
/// of its keyword: the translator's `attach_comments` gives these sexps
|
|
211
|
+
/// the comments before that offset.
|
|
212
|
+
definition_starts: Vec<(SexpId, u32)>,
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
impl Tree {
|
|
216
|
+
pub fn add(&mut self, elements: Vec<Value>, line: i32, line_max: i32) -> SexpId {
|
|
217
|
+
self.sexps.push(Sexp { elements, line, line_max });
|
|
218
|
+
(self.sexps.len() - 1) as SexpId
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/// Records that `value`, a `class`, `module`, `defn` or `defs` sexp, is
|
|
222
|
+
/// for the node whose keyword starts at byte offset `start`.
|
|
223
|
+
pub fn add_definition_start(&mut self, value: &Value, start: u32) {
|
|
224
|
+
if let Some(id) = value.as_sexp() {
|
|
225
|
+
self.definition_starts.push((id, start));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/// The sexps recorded by [`Tree::add_definition_start`], with their
|
|
230
|
+
/// keyword offsets.
|
|
231
|
+
pub fn definition_starts(&self) -> &[(SexpId, u32)] {
|
|
232
|
+
&self.definition_starts
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// Interns a Symbol from the source.
|
|
236
|
+
pub fn intern(&mut self, bytes: &[u8], encoding: Encoding) -> Value {
|
|
237
|
+
if bytes.is_ascii() {
|
|
238
|
+
if let Some(index) = STATIC_SYMBOLS.iter().position(|name| name.as_bytes() == bytes) {
|
|
239
|
+
return Value::Symbol(index as SymbolId);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
let key = (bytes.to_vec(), encoding);
|
|
243
|
+
if let Some(id) = self.symbol_index.get(&key) {
|
|
244
|
+
return Value::Symbol(*id);
|
|
245
|
+
}
|
|
246
|
+
let id = (STATIC_SYMBOLS.len() + self.symbols.len()) as SymbolId;
|
|
247
|
+
self.symbols.push(RubyString::new(bytes, encoding));
|
|
248
|
+
self.symbol_index.insert(key, id);
|
|
249
|
+
Value::Symbol(id)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/// The bytes and encoding of a Symbol.
|
|
253
|
+
pub fn symbol(&self, id: SymbolId) -> (&[u8], Encoding) {
|
|
254
|
+
match STATIC_SYMBOLS.get(id as usize) {
|
|
255
|
+
Some(name) => (name.as_bytes(), UTF_8),
|
|
256
|
+
None => {
|
|
257
|
+
let string = &self.symbols[id as usize - STATIC_SYMBOLS.len()];
|
|
258
|
+
(&string.bytes, string.encoding)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/// Whether `value` is the Symbol `name`.
|
|
264
|
+
pub fn is_symbol(&self, value: &Value, name: &str) -> bool {
|
|
265
|
+
matches!(value, Value::Symbol(id) if self.symbol(*id).0 == name.as_bytes())
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
pub fn get(&self, id: SexpId) -> &Sexp {
|
|
269
|
+
&self.sexps[id as usize]
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
pub fn get_mut(&mut self, id: SexpId) -> &mut Sexp {
|
|
273
|
+
&mut self.sexps[id as usize]
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/// `sexp_type`: the first element.
|
|
277
|
+
pub fn sexp_type(&self, id: SexpId) -> Option<&Value> {
|
|
278
|
+
self.get(id).elements.first()
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/// The sexp type's name, for a sexp whose first element is a Symbol.
|
|
282
|
+
pub fn type_name(&self, id: SexpId) -> &[u8] {
|
|
283
|
+
match self.sexp_type(id) {
|
|
284
|
+
Some(Value::Symbol(symbol)) => self.symbol(*symbol).0,
|
|
285
|
+
_ => b"",
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
pub fn line(&self, id: SexpId) -> i32 {
|
|
290
|
+
self.get(id).line
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/// The sexp children of a sexp, in order (`each_sexp`).
|
|
294
|
+
pub fn each_sexp(&self, id: SexpId) -> impl Iterator<Item = SexpId> + '_ {
|
|
295
|
+
self.get(id).elements.iter().filter_map(Value::as_sexp)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/// Computes every sexp's `mass` and `structural_hash`. The tree must not
|
|
299
|
+
/// change afterwards (Flay caches both).
|
|
300
|
+
pub fn finish(&mut self) {
|
|
301
|
+
self.symbol_index = Default::default();
|
|
302
|
+
self.sexps.shrink_to_fit();
|
|
303
|
+
for sexp in &mut self.sexps {
|
|
304
|
+
sexp.elements.shrink_to_fit();
|
|
305
|
+
}
|
|
306
|
+
let count = self.sexps.len();
|
|
307
|
+
self.masses = vec![0; count];
|
|
308
|
+
self.structural_hashes = vec![0; count];
|
|
309
|
+
let mut done = vec![false; count];
|
|
310
|
+
for root in 0..count as SexpId {
|
|
311
|
+
if done[root as usize] {
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
// Post-order without recursion: deep trees must not overflow the stack.
|
|
315
|
+
let mut stack: Vec<(SexpId, bool)> = vec![(root, false)];
|
|
316
|
+
while let Some((id, children_done)) = stack.pop() {
|
|
317
|
+
if done[id as usize] {
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if !children_done {
|
|
321
|
+
stack.push((id, true));
|
|
322
|
+
for child in self.each_sexp(id).collect::<Vec<_>>() {
|
|
323
|
+
if !done[child as usize] {
|
|
324
|
+
stack.push((child, false));
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
let mass = 1 + self.each_sexp(id).map(|child| self.masses[child as usize]).sum::<u64>();
|
|
330
|
+
let hash = self.pure_ruby_hash(id);
|
|
331
|
+
self.masses[id as usize] = mass;
|
|
332
|
+
self.structural_hashes[id as usize] = hash;
|
|
333
|
+
done[id as usize] = true;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/// `Sexp#mass`: 1 plus the mass of each sexp child.
|
|
339
|
+
pub fn mass(&self, id: SexpId) -> u64 {
|
|
340
|
+
self.masses[id as usize]
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/// `Sexp#mass` of a sexp with the given elements, whose sexp elements
|
|
344
|
+
/// are sexps of this tree.
|
|
345
|
+
pub fn elements_mass(&self, elements: &[Value]) -> u64 {
|
|
346
|
+
1 + elements.iter().filter_map(Value::as_sexp).map(|child| self.mass(child)).sum::<u64>()
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/// `Sexp#structural_hash`.
|
|
350
|
+
pub fn structural_hash(&self, id: SexpId) -> u32 {
|
|
351
|
+
self.structural_hashes[id as usize]
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/// `Sexp#pure_ruby_hash` from flay.rb, once the children's are known:
|
|
355
|
+
///
|
|
356
|
+
/// ```ruby
|
|
357
|
+
/// hash += n & MAX_INT32
|
|
358
|
+
/// hash += hash << 10 & MAX_INT32
|
|
359
|
+
/// hash ^= hash >> 6 & MAX_INT32
|
|
360
|
+
/// each { |o| next unless Sexp === o
|
|
361
|
+
/// hash = hash + o.pure_ruby_hash & MAX_INT32
|
|
362
|
+
/// hash = (hash + (hash << 10)) & MAX_INT32
|
|
363
|
+
/// hash = (hash ^ (hash >> 6)) & MAX_INT32 }
|
|
364
|
+
/// hash = (hash + (hash << 3)) & MAX_INT32
|
|
365
|
+
/// hash = (hash ^ (hash >> 11)) & MAX_INT32
|
|
366
|
+
/// hash = (hash + (hash << 15)) & MAX_INT32
|
|
367
|
+
/// ```
|
|
368
|
+
///
|
|
369
|
+
/// The `&` binds tighter than `+=` but looser than `<<` and `+`, so the
|
|
370
|
+
/// first three steps are not reduced to 32 bits.
|
|
371
|
+
fn pure_ruby_hash(&self, id: SexpId) -> u32 {
|
|
372
|
+
self.elements_structural_hash(&self.get(id).elements)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/// `Sexp#structural_hash` of a sexp with the given elements, whose sexp
|
|
376
|
+
/// elements are sexps of this tree (see [`Tree::pure_ruby_hash`]).
|
|
377
|
+
pub fn elements_structural_hash(&self, elements: &[Value]) -> u32 {
|
|
378
|
+
const MAX_INT32: u64 = (1 << 32) - 1;
|
|
379
|
+
let name = match elements.first() {
|
|
380
|
+
Some(value) => self.type_name_text(value),
|
|
381
|
+
None => b"".to_vec(),
|
|
382
|
+
};
|
|
383
|
+
// NODE_NAMES[sexp_type] is Zlib.crc32(sexp_type.to_s).
|
|
384
|
+
let n = u64::from(crc32fast::hash(&name));
|
|
385
|
+
let mut hash: u64 = 0;
|
|
386
|
+
hash += n & MAX_INT32;
|
|
387
|
+
hash += (hash << 10) & MAX_INT32;
|
|
388
|
+
hash ^= (hash >> 6) & MAX_INT32;
|
|
389
|
+
for child in elements.iter().filter_map(Value::as_sexp) {
|
|
390
|
+
hash = (hash + u64::from(self.structural_hashes[child as usize])) & MAX_INT32;
|
|
391
|
+
hash = (hash + (hash << 10)) & MAX_INT32;
|
|
392
|
+
hash = (hash ^ (hash >> 6)) & MAX_INT32;
|
|
393
|
+
}
|
|
394
|
+
hash = (hash + (hash << 3)) & MAX_INT32;
|
|
395
|
+
hash = (hash ^ (hash >> 11)) & MAX_INT32;
|
|
396
|
+
hash = (hash + (hash << 15)) & MAX_INT32;
|
|
397
|
+
hash as u32
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/// `Sexp#deep_each`: every sexp below `id` in pre-order, not `id`
|
|
401
|
+
/// itself. `visit` returns `false` to skip a sexp's children (`:skip`).
|
|
402
|
+
pub fn deep_each(&self, id: SexpId, mut visit: impl FnMut(SexpId) -> bool) {
|
|
403
|
+
let mut stack: Vec<SexpId> = self.each_sexp(id).collect();
|
|
404
|
+
stack.reverse();
|
|
405
|
+
while let Some(current) = stack.pop() {
|
|
406
|
+
if visit(current) {
|
|
407
|
+
let start = stack.len();
|
|
408
|
+
stack.extend(self.each_sexp(current));
|
|
409
|
+
stack[start..].reverse();
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
impl Tree {
|
|
416
|
+
/// `sexp_type.to_s` for the type values the translator produces.
|
|
417
|
+
fn type_name_text(&self, value: &Value) -> Vec<u8> {
|
|
418
|
+
match value {
|
|
419
|
+
Value::Symbol(id) => self.symbol(*id).0.to_vec(),
|
|
420
|
+
Value::String(string) => string.bytes.clone(),
|
|
421
|
+
Value::Nil => Vec::new(),
|
|
422
|
+
other => dump(self, other).into_bytes(),
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/// `a == b` between sexps of two trees: `Sexp#==` (same class, then
|
|
428
|
+
/// `Array#==`, which compares elements with `==`).
|
|
429
|
+
pub fn sexp_eq(tree_a: &Tree, a: SexpId, tree_b: &Tree, b: SexpId) -> bool {
|
|
430
|
+
elements_eq(tree_a, &tree_a.get(a).elements, tree_b, &tree_b.get(b).elements)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/// `a == b` between sexps given by their elements (see [`sexp_eq`]).
|
|
434
|
+
pub fn elements_eq(tree_a: &Tree, elements_a: &[Value], tree_b: &Tree, elements_b: &[Value]) -> bool {
|
|
435
|
+
elements_a.len() == elements_b.len()
|
|
436
|
+
&& elements_a.iter().zip(elements_b).all(|(x, y)| value_eq(tree_a, x, tree_b, y))
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/// Ruby's `==` for the values a translated tree holds.
|
|
440
|
+
pub fn value_eq(tree_a: &Tree, a: &Value, tree_b: &Tree, b: &Value) -> bool {
|
|
441
|
+
use Value::*;
|
|
442
|
+
match (a, b) {
|
|
443
|
+
(Sexp(x), Sexp(y)) => sexp_eq(tree_a, *x, tree_b, *y),
|
|
444
|
+
(Nil, Nil) | (True, True) | (False, False) => true,
|
|
445
|
+
(Symbol(x), Symbol(y)) => {
|
|
446
|
+
let ((bytes_x, encoding_x), (bytes_y, encoding_y)) = (tree_a.symbol(*x), tree_b.symbol(*y));
|
|
447
|
+
bytes_x == bytes_y && (encoding_x == encoding_y || bytes_x.is_ascii())
|
|
448
|
+
}
|
|
449
|
+
(String(x), String(y)) => x.ruby_eq(y),
|
|
450
|
+
(Regexp(x), Regexp(y)) => {
|
|
451
|
+
// rb_reg_equal: same source bytes, options and encoding. It
|
|
452
|
+
// ignores `Regexp::NOENCODING` (32): `/a/ == /a/n`.
|
|
453
|
+
const NOENCODING: u32 = 32;
|
|
454
|
+
x.source == y.source
|
|
455
|
+
&& x.options & !NOENCODING == y.options & !NOENCODING
|
|
456
|
+
&& (x.encoding == y.encoding || x.source.is_ascii())
|
|
457
|
+
}
|
|
458
|
+
(Range(x), Range(y)) => x == y,
|
|
459
|
+
(Array(x), Array(y)) => {
|
|
460
|
+
x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| value_eq(tree_a, p, tree_b, q))
|
|
461
|
+
}
|
|
462
|
+
_ => numeric_eq(a, b).unwrap_or(false),
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/// `==` between numbers of any of Ruby's numeric classes, or `None` when
|
|
467
|
+
/// either value is not a number.
|
|
468
|
+
fn numeric_eq(a: &Value, b: &Value) -> Option<bool> {
|
|
469
|
+
use Value::*;
|
|
470
|
+
let result = match (a, b) {
|
|
471
|
+
(Integer(x), Integer(y)) => x == y,
|
|
472
|
+
(Float(x), Float(y)) => x == y,
|
|
473
|
+
(Integer(x), Float(y)) | (Float(y), Integer(x)) => {
|
|
474
|
+
crate::sexp::Integer::from_integral_f64(*y).is_some_and(|integral| integral == **x)
|
|
475
|
+
}
|
|
476
|
+
(Rational(x), Rational(y)) => x == y,
|
|
477
|
+
(Rational(rational), Integer(x)) | (Integer(x), Rational(rational)) => {
|
|
478
|
+
rational.1.is_one() && rational.0 == **x
|
|
479
|
+
}
|
|
480
|
+
// Rational#== converts itself to a Float.
|
|
481
|
+
(Rational(rational), Float(x)) | (Float(x), Rational(rational)) => {
|
|
482
|
+
rational.0.to_f64() / rational.1.to_f64() == *x
|
|
483
|
+
}
|
|
484
|
+
(Complex(x), Complex(y)) => numeric_eq(&x.0, &y.0)? && numeric_eq(&x.1, &y.1)?,
|
|
485
|
+
// Complex#== with a real number: the imaginary part is zero and the
|
|
486
|
+
// real parts are equal.
|
|
487
|
+
(Complex(complex), other) | (other, Complex(complex)) => {
|
|
488
|
+
is_numeric(other) && is_zero(&complex.1) && numeric_eq(&complex.0, other)?
|
|
489
|
+
}
|
|
490
|
+
_ => return None,
|
|
491
|
+
};
|
|
492
|
+
Some(result)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
fn is_numeric(value: &Value) -> bool {
|
|
496
|
+
matches!(value, Value::Integer(_) | Value::Float(_) | Value::Rational(..) | Value::Complex(..))
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
fn is_zero(value: &Value) -> bool {
|
|
500
|
+
match value {
|
|
501
|
+
Value::Integer(integer) => integer.is_zero(),
|
|
502
|
+
Value::Float(float) => *float == 0.0,
|
|
503
|
+
Value::Rational(rational) => rational.0.is_zero(),
|
|
504
|
+
_ => false,
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/// The tree as text, in the format `parity/oracle.rb` writes for a Ruby
|
|
509
|
+
/// `Sexp`, so the two compare as strings. See `parity/README` in
|
|
510
|
+
/// `parity/oracle.rb` for the format.
|
|
511
|
+
pub fn dump(tree: &Tree, value: &Value) -> String {
|
|
512
|
+
let mut out = String::new();
|
|
513
|
+
dump_value(tree, value, &mut out);
|
|
514
|
+
out
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
fn dump_value(tree: &Tree, value: &Value, out: &mut String) {
|
|
518
|
+
match value {
|
|
519
|
+
Value::Sexp(id) => {
|
|
520
|
+
let sexp = tree.get(*id);
|
|
521
|
+
out.push_str(&format!("(@{}", sexp.line));
|
|
522
|
+
for element in &sexp.elements {
|
|
523
|
+
out.push(' ');
|
|
524
|
+
dump_value(tree, element, out);
|
|
525
|
+
}
|
|
526
|
+
out.push(')');
|
|
527
|
+
}
|
|
528
|
+
Value::Nil => out.push_str("nil"),
|
|
529
|
+
Value::True => out.push_str("true"),
|
|
530
|
+
Value::False => out.push_str("false"),
|
|
531
|
+
Value::Symbol(id) => {
|
|
532
|
+
let (bytes, encoding) = tree.symbol(*id);
|
|
533
|
+
out.push(':');
|
|
534
|
+
push_escaped(out, bytes, encoding);
|
|
535
|
+
}
|
|
536
|
+
Value::String(string) => {
|
|
537
|
+
out.push('"');
|
|
538
|
+
push_escaped(out, &string.bytes, string.encoding);
|
|
539
|
+
}
|
|
540
|
+
Value::Integer(integer) => out.push_str(&integer.to_s()),
|
|
541
|
+
Value::Float(float) => {
|
|
542
|
+
out.push('f');
|
|
543
|
+
out.push_str(&float_to_s(*float));
|
|
544
|
+
}
|
|
545
|
+
Value::Rational(rational) => {
|
|
546
|
+
out.push_str(&format!("r({}/{})", rational.0.to_s(), rational.1.to_s()));
|
|
547
|
+
}
|
|
548
|
+
Value::Complex(complex) => {
|
|
549
|
+
out.push_str("c(");
|
|
550
|
+
dump_value(tree, &complex.0, out);
|
|
551
|
+
out.push(',');
|
|
552
|
+
dump_value(tree, &complex.1, out);
|
|
553
|
+
out.push(')');
|
|
554
|
+
}
|
|
555
|
+
Value::Range(range) => {
|
|
556
|
+
let (first, last, exclusive) = &**range;
|
|
557
|
+
let bound = |bound: &Option<Integer>| bound.as_ref().map_or("nil".to_string(), Integer::to_s);
|
|
558
|
+
let operator = if *exclusive { "..." } else { ".." };
|
|
559
|
+
out.push_str(&format!("rng({}{}{})", bound(first), operator, bound(last)));
|
|
560
|
+
}
|
|
561
|
+
Value::Regexp(regexp) => {
|
|
562
|
+
out.push_str("re(");
|
|
563
|
+
push_escaped(out, ®exp.source, regexp.encoding);
|
|
564
|
+
out.push_str(&format!("|{})", regexp.options));
|
|
565
|
+
}
|
|
566
|
+
Value::Array(elements) => {
|
|
567
|
+
out.push('[');
|
|
568
|
+
for (index, element) in elements.iter().enumerate() {
|
|
569
|
+
if index > 0 {
|
|
570
|
+
out.push(' ');
|
|
571
|
+
}
|
|
572
|
+
dump_value(tree, element, out);
|
|
573
|
+
}
|
|
574
|
+
out.push(']');
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/// Bytes as text: ASCII letters, digits and `_` as they are, every other
|
|
580
|
+
/// byte as `\xHH`; then `%` and the encoding name when a byte is not ASCII.
|
|
581
|
+
fn push_escaped(out: &mut String, bytes: &[u8], encoding: Encoding) {
|
|
582
|
+
for byte in bytes {
|
|
583
|
+
if byte.is_ascii_alphanumeric() || *byte == b'_' {
|
|
584
|
+
out.push(*byte as char);
|
|
585
|
+
} else {
|
|
586
|
+
out.push_str(&format!("\\x{byte:02X}"));
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
if !bytes.is_ascii() {
|
|
590
|
+
out.push('%');
|
|
591
|
+
out.push_str(encoding);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
#[cfg(test)]
|
|
596
|
+
mod tests {
|
|
597
|
+
use super::*;
|
|
598
|
+
|
|
599
|
+
#[test]
|
|
600
|
+
fn integral_floats_convert_exactly() {
|
|
601
|
+
assert_eq!(Integer::from_integral_f64(3.0), Some(Integer::from_i64(3)));
|
|
602
|
+
assert_eq!(Integer::from_integral_f64(-1.0), Some(Integer::from_i64(-1)));
|
|
603
|
+
assert_eq!(Integer::from_integral_f64(0.5), None);
|
|
604
|
+
assert_eq!(Integer::from_integral_f64(4294967296.0), Some(Integer::new(false, &[0, 1])));
|
|
605
|
+
assert_eq!(Integer::from_integral_f64(1e20).map(|integer| integer.to_s()), Some("100000000000000000000".to_string()));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
#[test]
|
|
609
|
+
fn value_is_sixteen_bytes() {
|
|
610
|
+
assert_eq!(std::mem::size_of::<Value>(), 16);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
#[test]
|
|
614
|
+
fn numbers_compare_as_ruby_does() {
|
|
615
|
+
let int = |value| Value::integer(Integer::from_i64(value));
|
|
616
|
+
assert_eq!(numeric_eq(&int(1), &Value::Float(1.0)), Some(true));
|
|
617
|
+
let two = Value::Rational(Box::new((Integer::from_i64(2), Integer::from_i64(1))));
|
|
618
|
+
assert_eq!(numeric_eq(&two, &int(2)), Some(true));
|
|
619
|
+
let zero_i = Value::Complex(Box::new((int(0), int(0))));
|
|
620
|
+
assert_eq!(numeric_eq(&zero_i, &int(0)), Some(true));
|
|
621
|
+
let two_i = Value::Complex(Box::new((int(0), int(2))));
|
|
622
|
+
assert_eq!(numeric_eq(&two_i, &int(0)), Some(false));
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
#[test]
|
|
626
|
+
fn structural_hash_matches_flay() {
|
|
627
|
+
// s(:lit, 1).structural_hash and s(:call, nil, :a).structural_hash in Ruby.
|
|
628
|
+
let mut tree = Tree::default();
|
|
629
|
+
let lit = tree.add(vec![Value::static_symbol("lit"), Value::integer(Integer::from_i64(1))], 1, 1);
|
|
630
|
+
let a = tree.intern(b"a", UTF_8);
|
|
631
|
+
let call = tree.add(vec![Value::static_symbol("call"), Value::Nil, a], 1, 1);
|
|
632
|
+
let array = tree.add(vec![Value::static_symbol("array"), Value::Sexp(lit), Value::Sexp(call)], 1, 1);
|
|
633
|
+
tree.finish();
|
|
634
|
+
assert_eq!(tree.mass(array), 3);
|
|
635
|
+
assert_eq!(tree.structural_hash(lit), 1_518_675_050);
|
|
636
|
+
assert_eq!(tree.structural_hash(call), 4_245_643_647);
|
|
637
|
+
assert_eq!(tree.structural_hash(array), 2_031_342_527);
|
|
638
|
+
}
|
|
639
|
+
}
|