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,353 @@
1
+ //! The exceptions `Prism::Translation::RubyParser`'s `attach_comments` raises.
2
+ //!
3
+ //! For every `class`, `module` and `def`, the translator (prism 2.1.0,
4
+ //! `translation/ruby_parser.rb`) collects the comments before the keyword:
5
+ //!
6
+ //! ```ruby
7
+ //! leading.reverse_each do |comment|
8
+ //! gap = source_string[comment.location.end_offset...boundary]
9
+ //! break if gap.match?(/\S/)
10
+ //! result.unshift(comment)
11
+ //! boundary = comment.location.start_offset
12
+ //! end
13
+ //! sexp.comments = source_string[result.first.location.start_offset...node_start].gsub(...)
14
+ //! ```
15
+ //!
16
+ //! The offsets are byte offsets but `String#[]` counts characters, so in a
17
+ //! source with multibyte characters a comment can end past the string's
18
+ //! character length. The slice is then `nil` and `match?` raises
19
+ //! `NoMethodError`. A slice holding an invalid byte sequence makes `match?`
20
+ //! or `gsub` raise `ArgumentError`. Flay then skips the whole file.
21
+ //!
22
+ //! `source_string` is `Prism.parse(source).source.source`: the bytes in the
23
+ //! encoding Prism detected from a magic comment (UTF-8 without one), except
24
+ //! that a binary source that is valid UTF-8 becomes UTF-8.
25
+
26
+ use std::ffi::{c_char, CStr};
27
+
28
+ use ruby_prism::{ParseResult, Visit};
29
+ use ruby_prism_sys::{pm_arena_free, pm_arena_new, pm_parse, pm_parser_free, pm_parser_new, pm_parser_t};
30
+
31
+ use crate::sexp::{Encoding, RubyString};
32
+ use crate::RubyException;
33
+
34
+ extern "C" {
35
+ // Exported by prism (include/prism/parser.h) but not bound by ruby-prism-sys.
36
+ fn pm_parser_encoding_name(parser: *const pm_parser_t) -> *const c_char;
37
+ fn pm_parser_encoding_char_width(parser: *const pm_parser_t, start: *const u8, remaining: isize) -> usize;
38
+ }
39
+
40
+ /// The exception the translator raises while attaching comments to `source`,
41
+ /// if any. Sources of ASCII characters only never raise.
42
+ pub fn attach_comments_exception(source: &[u8], parse_result: &ParseResult<'_>) -> Option<RubyException> {
43
+ if source.is_ascii() {
44
+ return None;
45
+ }
46
+ let source_string = SourceString::new(source);
47
+ let comments: Vec<(usize, usize)> = parse_result
48
+ .comments()
49
+ .map(|comment| {
50
+ let location = comment.location();
51
+ (location.start() as usize, location.end() as usize)
52
+ })
53
+ .collect();
54
+ let mut visitor = CommentAttacher { source, source_string: &source_string, comments: &comments, exception: None };
55
+ visitor.visit(&parse_result.node());
56
+ visitor.exception
57
+ }
58
+
59
+ /// `source_string` as Ruby sees it: where each character starts, and which
60
+ /// characters are invalid byte sequences in its encoding.
61
+ struct SourceString {
62
+ encoding_name: Encoding,
63
+ /// Byte offset of each character, then the source length.
64
+ char_starts: Vec<usize>,
65
+ /// For each character index, how many invalid characters come before it.
66
+ invalid_before: Vec<usize>,
67
+ }
68
+
69
+ impl SourceString {
70
+ fn new(source: &[u8]) -> Self {
71
+ let detected = DetectedEncoding::new(source);
72
+ let detected_name = detected.name();
73
+ let valid_utf8 = std::str::from_utf8(source).is_ok();
74
+ let encoding_name = if detected_name == "ASCII-8BIT" && valid_utf8 { "UTF-8" } else { detected_name };
75
+
76
+ let mut char_starts = Vec::with_capacity(source.len() + 1);
77
+ let mut invalid_before = Vec::with_capacity(source.len() + 1);
78
+ let mut invalid = 0;
79
+ let mut offset = 0;
80
+ while offset < source.len() {
81
+ let width = if encoding_name == "UTF-8" {
82
+ utf8_char_width(&source[offset..])
83
+ } else {
84
+ detected.char_width(&source[offset..])
85
+ };
86
+ char_starts.push(offset);
87
+ invalid_before.push(invalid);
88
+ // Ruby counts each byte of an invalid sequence as one character.
89
+ if width == 0 {
90
+ invalid += 1;
91
+ offset += 1;
92
+ } else {
93
+ offset += width;
94
+ }
95
+ }
96
+ char_starts.push(source.len());
97
+ invalid_before.push(invalid);
98
+ SourceString { encoding_name, char_starts, invalid_before }
99
+ }
100
+
101
+ fn char_length(&self) -> usize {
102
+ self.char_starts.len() - 1
103
+ }
104
+
105
+ /// `source_string[start...finish]` with character indexes: `None` when
106
+ /// `start` is past the end (Ruby's `nil`), otherwise the byte range.
107
+ fn slice(&self, start: usize, finish: usize) -> Option<(usize, usize)> {
108
+ if start > self.char_length() {
109
+ return None;
110
+ }
111
+ let finish = finish.clamp(start, self.char_length());
112
+ Some((start, finish))
113
+ }
114
+
115
+ fn has_invalid_byte_sequence(&self, (start, finish): (usize, usize)) -> bool {
116
+ self.invalid_before[finish] > self.invalid_before[start]
117
+ }
118
+
119
+ /// `/\S/` in Ruby matches anything but space, tab, newline, vertical tab,
120
+ /// form feed and carriage return.
121
+ fn has_non_whitespace(&self, source: &[u8], (start, finish): (usize, usize)) -> bool {
122
+ source[self.char_starts[start]..self.char_starts[finish]]
123
+ .iter()
124
+ .any(|byte| !matches!(byte, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r'))
125
+ }
126
+
127
+ fn invalid_byte_sequence(&self) -> RubyException {
128
+ RubyException { class: "ArgumentError", message: format!("invalid byte sequence in {}", self.encoding_name) }
129
+ }
130
+ }
131
+
132
+ /// The width of the UTF-8 character at the start of `bytes`, or 0 when it is
133
+ /// an invalid byte sequence.
134
+ fn utf8_char_width(bytes: &[u8]) -> usize {
135
+ let width = match bytes[0] {
136
+ 0x00..=0x7f => return 1,
137
+ 0xc2..=0xdf => 2,
138
+ 0xe0..=0xef => 3,
139
+ 0xf0..=0xf4 => 4,
140
+ _ => return 0,
141
+ };
142
+ match bytes.get(..width) {
143
+ Some(candidate) if std::str::from_utf8(candidate).is_ok() => width,
144
+ _ => 0,
145
+ }
146
+ }
147
+
148
+ /// The encoding Prism detects for a source. A magic comment only counts on
149
+ /// the first line, or on the second after a shebang, so parsing those two
150
+ /// lines is enough.
151
+ struct DetectedEncoding {
152
+ arena: *mut ruby_prism_sys::pm_arena_t,
153
+ parser: *mut pm_parser_t,
154
+ _prefix: Vec<u8>,
155
+ }
156
+
157
+ impl DetectedEncoding {
158
+ fn new(source: &[u8]) -> Self {
159
+ let prefix_length = source
160
+ .iter()
161
+ .enumerate()
162
+ .filter(|(_, byte)| **byte == b'\n')
163
+ .nth(1)
164
+ .map_or(source.len(), |(index, _)| index + 1);
165
+ let prefix = source[..prefix_length].to_vec();
166
+ // SAFETY: the parser reads `prefix`, which lives as long as the
167
+ // parser; both are freed in `drop`.
168
+ unsafe {
169
+ let arena = pm_arena_new();
170
+ let parser = pm_parser_new(arena, prefix.as_ptr(), prefix.len(), std::ptr::null());
171
+ pm_parse(parser);
172
+ DetectedEncoding { arena, parser, _prefix: prefix }
173
+ }
174
+ }
175
+
176
+ fn name(&self) -> Encoding {
177
+ // SAFETY: prism returns a static, NUL-terminated encoding name.
178
+ let name = unsafe { CStr::from_ptr(pm_parser_encoding_name(self.parser)) };
179
+ name.to_str().unwrap_or("UTF-8")
180
+ }
181
+
182
+ /// The width of the character at the start of `bytes`, or 0 when it is
183
+ /// an invalid byte sequence.
184
+ fn char_width(&self, bytes: &[u8]) -> usize {
185
+ // SAFETY: prism reads at most `bytes.len()` bytes from `bytes`.
186
+ unsafe { pm_parser_encoding_char_width(self.parser, bytes.as_ptr(), bytes.len() as isize) }
187
+ }
188
+ }
189
+
190
+ impl Drop for DetectedEncoding {
191
+ fn drop(&mut self) {
192
+ // SAFETY: created in `new` and freed only here.
193
+ unsafe {
194
+ pm_parser_free(self.parser);
195
+ pm_arena_free(self.arena);
196
+ }
197
+ }
198
+ }
199
+
200
+ /// Walks the tree in the translator's order: a `def` attaches its comments
201
+ /// after its receiver and before its parameters and body; a `class` or
202
+ /// `module` after its name, superclass and body.
203
+ struct CommentAttacher<'a> {
204
+ source: &'a [u8],
205
+ source_string: &'a SourceString,
206
+ comments: &'a [(usize, usize)],
207
+ exception: Option<RubyException>,
208
+ }
209
+
210
+ impl CommentAttacher<'_> {
211
+ fn attach_comments(&mut self, node_start: u32) {
212
+ let node_start = node_start as usize;
213
+ if self.exception.is_some() {
214
+ return;
215
+ }
216
+ let source_string = self.source_string;
217
+ let mut first_attached = None;
218
+ let mut boundary = node_start;
219
+ for &(start, end) in self.comments.iter().filter(|(start, _)| *start < node_start).rev() {
220
+ let Some(gap) = source_string.slice(end, boundary) else {
221
+ self.exception = Some(RubyException {
222
+ class: "NoMethodError",
223
+ message: "undefined method `match?' for nil".to_string(),
224
+ });
225
+ return;
226
+ };
227
+ if source_string.has_invalid_byte_sequence(gap) {
228
+ self.exception = Some(source_string.invalid_byte_sequence());
229
+ return;
230
+ }
231
+ if source_string.has_non_whitespace(self.source, gap) {
232
+ break;
233
+ }
234
+ first_attached = Some(start);
235
+ boundary = start;
236
+ }
237
+ // The comment text `gsub` reads; it is never nil, because the first
238
+ // attached comment ends within the string.
239
+ if let Some(start) = first_attached {
240
+ if let Some(text) = source_string.slice(start, node_start) {
241
+ if source_string.has_invalid_byte_sequence(text) {
242
+ self.exception = Some(source_string.invalid_byte_sequence());
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ impl<'pr> Visit<'pr> for CommentAttacher<'_> {
250
+ fn visit_class_node(&mut self, node: &ruby_prism::ClassNode<'pr>) {
251
+ ruby_prism::visit_class_node(self, node);
252
+ self.attach_comments(node.location().start());
253
+ }
254
+
255
+ fn visit_module_node(&mut self, node: &ruby_prism::ModuleNode<'pr>) {
256
+ ruby_prism::visit_module_node(self, node);
257
+ self.attach_comments(node.location().start());
258
+ }
259
+
260
+ fn visit_def_node(&mut self, node: &ruby_prism::DefNode<'pr>) {
261
+ if let Some(receiver) = node.receiver() {
262
+ self.visit(&receiver);
263
+ }
264
+ self.attach_comments(node.location().start());
265
+ if let Some(parameters) = node.parameters() {
266
+ self.visit_parameters_node(&parameters);
267
+ }
268
+ if let Some(body) = node.body() {
269
+ self.visit(&body);
270
+ }
271
+ }
272
+ }
273
+
274
+ /// The name of the encoding Prism reads `source` in: from a magic comment,
275
+ /// UTF-8 without one. Strings and symbols the translator builds have this
276
+ /// encoding unless an escape forces another.
277
+ pub fn source_encoding(source: &[u8]) -> &'static str {
278
+ let detected = DetectedEncoding::new(source);
279
+ // SAFETY: prism's encoding names are static, NUL-terminated strings.
280
+ let name = unsafe { CStr::from_ptr(pm_parser_encoding_name(detected.parser)) };
281
+ name.to_str().unwrap_or("UTF-8")
282
+ }
283
+
284
+ /// The `comments` that `attach_comments` sets on the sexp of each `class`,
285
+ /// `module` or `def` whose keyword starts at the given byte offset, for a
286
+ /// source the translator accepted: the source from the first attached
287
+ /// comment up to the keyword, with `gsub(/^ +#/, "#").gsub(/^ +$/, "")`
288
+ /// applied, or `None` when no comment is attached.
289
+ pub(crate) fn leading_comments(source: &[u8], node_starts: &[u32]) -> Vec<Option<RubyString>> {
290
+ let options = ruby_prism::Options::default().partial_script(true).build();
291
+ let parse_result = ruby_prism::parse_with_options(source, &options);
292
+ let comments: Vec<(usize, usize)> = parse_result
293
+ .comments()
294
+ .map(|comment| {
295
+ let location = comment.location();
296
+ (location.start() as usize, location.end() as usize)
297
+ })
298
+ .collect();
299
+ let source_string = SourceString::new(source);
300
+ node_starts
301
+ .iter()
302
+ .map(|node_start| leading_comment(source, &source_string, &comments, *node_start as usize))
303
+ .collect()
304
+ }
305
+
306
+ /// `attach_comments` for one node: walks back from the last comment
307
+ /// before the node while only whitespace separates each comment from what
308
+ /// follows it.
309
+ fn leading_comment(
310
+ source: &[u8],
311
+ source_string: &SourceString,
312
+ comments: &[(usize, usize)],
313
+ node_start: usize,
314
+ ) -> Option<RubyString> {
315
+ let leading = comments.partition_point(|(start, _)| *start < node_start);
316
+ let mut first_attached = None;
317
+ let mut boundary = node_start;
318
+ for &(start, end) in comments[..leading].iter().rev() {
319
+ let gap = source_string.slice(end, boundary)?;
320
+ if source_string.has_non_whitespace(source, gap) {
321
+ break;
322
+ }
323
+ first_attached = Some(start);
324
+ boundary = start;
325
+ }
326
+ let (start, finish) = source_string.slice(first_attached?, node_start)?;
327
+ let text = &source[source_string.char_starts[start]..source_string.char_starts[finish]];
328
+ let text = remove_spaces_at_line_starts(text, |rest| rest.first() == Some(&b'#'));
329
+ let text = remove_spaces_at_line_starts(&text, |rest| rest.is_empty() || rest[0] == b'\n');
330
+ Some(RubyString::new(text, source_string.encoding_name))
331
+ }
332
+
333
+ /// `gsub(/^ +X/, "X")`: the spaces that start a line are removed when what
334
+ /// follows them satisfies `followed_by`.
335
+ fn remove_spaces_at_line_starts(text: &[u8], followed_by: impl Fn(&[u8]) -> bool) -> Vec<u8> {
336
+ let mut result = Vec::with_capacity(text.len());
337
+ let mut line_start = true;
338
+ let mut position = 0;
339
+ while position < text.len() {
340
+ if line_start && text[position] == b' ' {
341
+ let spaces = text[position..].iter().take_while(|byte| **byte == b' ').count();
342
+ if followed_by(&text[position + spaces..]) {
343
+ position += spaces;
344
+ line_start = false;
345
+ continue;
346
+ }
347
+ }
348
+ line_start = text[position] == b'\n';
349
+ result.push(text[position]);
350
+ position += 1;
351
+ }
352
+ result
353
+ }