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,418 @@
1
+ //! ERB templates, as Flay's plugin `flay_erb.rb` processes them.
2
+ //!
3
+ //! `Flay#process_erb(file)` reads the template with `File.read`, converts it
4
+ //! to Ruby with `Flay::Erubi.new(erb).src` (a subclass of `Erubi::Engine`
5
+ //! 1.13.1), and parses that Ruby as `Flay#process_rb` parses a `.rb` file:
6
+ //!
7
+ //! ```ruby
8
+ //! erb = File.read file
9
+ //! ruby = Erubi.new(erb).src
10
+ //! begin
11
+ //! parser = option[:parser].new
12
+ //! parser.process(ruby, file, option[:timeout])
13
+ //! rescue => e
14
+ //! warn ruby if option[:verbose]
15
+ //! raise e
16
+ //! end
17
+ //! ```
18
+ //!
19
+ //! `Flay::Erubi` sets `postamble: "_buf.to_s"`, `bufvar: "_buf"` and
20
+ //! `freeze_template_literals: false`, leaves every other option at Erubi's
21
+ //! default (`DEFAULT_REGEXP`, `trim: true`, no escaping, preamble
22
+ //! `"_buf = ::String.new;"`), and overrides `add_text`, `add_expression`,
23
+ //! `add_code` and `add_postamble` so that newline-only text is batched into
24
+ //! the next `_buf.safe_append='...'` and block expressions (`<%= x do %>`)
25
+ //! are not wrapped in parentheses.
26
+ //!
27
+ //! `File.read` returns a String in `Encoding.default_external`; this module
28
+ //! assumes UTF-8, the default under a UTF-8 locale. The Ruby source Erubi
29
+ //! builds is ASCII-8BIT when it is all ASCII and UTF-8 otherwise, but Prism
30
+ //! ignores the encoding of the String it parses (it reads the bytes, and the
31
+ //! strings in its result take the encoding of the source's magic comment,
32
+ //! UTF-8 without one), so the converted Ruby parses exactly as
33
+ //! `File.binread` bytes would in [`parse_source`].
34
+
35
+ use crate::{parse_source, ParsedFile, RubyException, Skip};
36
+
37
+ /// `Flay#process_erb` on the contents of a file: [`erb_to_ruby`], then
38
+ /// `NotRubyParser.new.process(ruby, file)` ([`parse_source`]).
39
+ ///
40
+ /// An exception from the conversion (`Flay::Erubi.new`) and one from the
41
+ /// parser both make `Flay#process` skip the file. Only for the parser's does
42
+ /// `process_erb` first `warn ruby if option[:verbose]`, the converted Ruby.
43
+ pub fn parse_erb_source(source: &[u8], path: &str, ruby_version: &str) -> ParsedFile {
44
+ match erb_to_ruby(source) {
45
+ Ok(ruby) => parse_source(&ruby, path, ruby_version),
46
+ Err(exception) => ParsedFile { path: path.to_string(), outcome: Err(Skip::Raised(exception)) },
47
+ }
48
+ }
49
+
50
+ /// Reads an ERB file and processes it as `Flay#process_erb` does
51
+ /// ([`parse_erb_source`]).
52
+ pub fn parse_erb_file(path: &str, ruby_version: &str) -> ParsedFile {
53
+ match std::fs::read(path) {
54
+ Ok(source) => parse_erb_source(&source, path, ruby_version),
55
+ Err(error) => ParsedFile { path: path.to_string(), outcome: Err(Skip::Unreadable(crate::read_error_message(&error, path))) },
56
+ }
57
+ }
58
+
59
+ /// `Flay::Erubi.new(erb).src` for the template `erb` read as a UTF-8 String.
60
+ ///
61
+ /// `Erubi::Engine#initialize` scans the template with a regexp, and Ruby's
62
+ /// regexp search raises `ArgumentError, "invalid byte sequence in UTF-8"`
63
+ /// on a String that is not valid UTF-8, before any Ruby is generated. No
64
+ /// other exception is reachable: `Erubi::Engine#handle` raises for an
65
+ /// unknown indicator, but `DEFAULT_REGEXP` only matches known ones.
66
+ pub fn erb_to_ruby(erb: &[u8]) -> Result<Vec<u8>, RubyException> {
67
+ let Ok(erb) = std::str::from_utf8(erb) else {
68
+ return Err(RubyException { class: "ArgumentError", message: "invalid byte sequence in UTF-8".to_string() });
69
+ };
70
+ Ok(FlayErubi::convert(erb).into_bytes())
71
+ }
72
+
73
+ /// `Flay::Erubi`: the state of one conversion.
74
+ struct FlayErubi {
75
+ /// `@src`, which starts with the preamble.
76
+ src: String,
77
+ /// `@newline_pending`: how many `"\n"` texts are waiting to be appended.
78
+ newline_pending: usize,
79
+ }
80
+
81
+ /// `Erubi::Engine`'s default preamble, `"#{bufvar} = #{bufval};"`.
82
+ const PREAMBLE: &str = "_buf = ::String.new;";
83
+
84
+ /// The `:postamble` `Flay::Erubi` sets.
85
+ const POSTAMBLE: &str = "_buf.to_s";
86
+
87
+ impl FlayErubi {
88
+ /// `Erubi::Engine#initialize` with `Flay::Erubi`'s properties: walks the
89
+ /// tags `DEFAULT_REGEXP` finds and adds the text before each, the tag,
90
+ /// and the text after the last one.
91
+ fn convert(input: &str) -> String {
92
+ let mut engine = FlayErubi { src: String::from(PREAMBLE), newline_pending: 0 };
93
+ let mut pos = 0;
94
+ let mut is_bol = true;
95
+ while let Some(tag) = next_tag(input, pos) {
96
+ let mut text = &input[pos..tag.start];
97
+ pos = tag.end;
98
+
99
+ // The spaces and tabs before a tag that starts a line.
100
+ let mut lspace = None;
101
+ if !tag.indicator.is_some_and(|indicator| indicator.starts_with('=')) {
102
+ if text.is_empty() {
103
+ if is_bol {
104
+ lspace = Some("");
105
+ }
106
+ } else if text.ends_with('\n') {
107
+ lspace = Some("");
108
+ } else if let Some(rindex) = text.rfind('\n') {
109
+ let last_line = &text[rindex + 1..];
110
+ if is_spaces_and_tabs(last_line) {
111
+ lspace = Some(last_line);
112
+ text = &text[..rindex + 1];
113
+ }
114
+ } else if is_bol && is_spaces_and_tabs(text) {
115
+ lspace = Some(text);
116
+ text = "";
117
+ }
118
+ }
119
+
120
+ is_bol = tag.rspace.is_some();
121
+ engine.add_text(text);
122
+ engine.add_tag(&tag, lspace);
123
+ }
124
+ engine.add_text(&input[pos..]);
125
+
126
+ if !engine.src.ends_with('\n') {
127
+ engine.src.push('\n');
128
+ }
129
+ engine.add_postamble();
130
+ engine.src
131
+ }
132
+
133
+ /// The `case ch` in `Erubi::Engine#initialize`, with `trim` true (Flay
134
+ /// does not set `:trim`). A code or comment tag alone on its line
135
+ /// (`lspace` and `rspace` both present) becomes code that includes the
136
+ /// surrounding whitespace.
137
+ fn add_tag(&mut self, tag: &Tag<'_>, lspace: Option<&str>) {
138
+ let code = tag.code;
139
+ let rspace = tag.rspace;
140
+ match tag.indicator {
141
+ Some("=") | Some("==") => {
142
+ self.add_expression(tag.indicator, code);
143
+ // `-%>` or `=%>` swallows the newline after the tag.
144
+ if tag.tailch.is_none() {
145
+ if let Some(rspace) = rspace {
146
+ self.add_text(rspace);
147
+ }
148
+ }
149
+ }
150
+ None | Some("-") => match (lspace, rspace) {
151
+ (Some(lspace), Some(rspace)) => self.add_code(&format!("{lspace}{code}{rspace}")),
152
+ _ => {
153
+ self.add_text(lspace.unwrap_or(""));
154
+ self.add_code(code);
155
+ self.add_text(rspace.unwrap_or(""));
156
+ }
157
+ },
158
+ Some("#") => {
159
+ let newlines = "\n".repeat(code.matches('\n').count() + usize::from(rspace.is_some()));
160
+ match (lspace, rspace) {
161
+ (Some(_), Some(_)) => self.add_code(&newlines),
162
+ _ => {
163
+ self.add_text(lspace.unwrap_or(""));
164
+ self.add_code(&newlines);
165
+ self.add_text(rspace.unwrap_or(""));
166
+ }
167
+ }
168
+ }
169
+ // `<%%`: the tag as text, with `literal_prefix` `<%` and
170
+ // `literal_postfix` `%>`.
171
+ Some("%") => self.add_text(&format!(
172
+ "{}<%{}{}%>{}",
173
+ lspace.unwrap_or(""),
174
+ code,
175
+ tag.tailch.unwrap_or(""),
176
+ rspace.unwrap_or("")
177
+ )),
178
+ Some(indicator) => unreachable!("DEFAULT_REGEXP matched indicator {indicator:?}"),
179
+ }
180
+ }
181
+
182
+ /// `Flay::Erubi#add_text`: a text of one newline is counted and appended
183
+ /// with the next text, expression, code or the postamble; other text is
184
+ /// appended as `_buf.safe_append='...';` after the pending newlines,
185
+ /// with `'` and `\` escaped. Empty text adds nothing.
186
+ fn add_text(&mut self, text: &str) {
187
+ if text.is_empty() {
188
+ return;
189
+ }
190
+ if text == "\n" {
191
+ self.newline_pending += 1;
192
+ return;
193
+ }
194
+ self.src.push_str("_buf.safe_append='");
195
+ self.src.push_str(&"\n".repeat(self.newline_pending));
196
+ for character in text.chars() {
197
+ if character == '\'' || character == '\\' {
198
+ self.src.push('\\');
199
+ }
200
+ self.src.push(character);
201
+ }
202
+ self.src.push_str("';");
203
+ self.newline_pending = 0;
204
+ }
205
+
206
+ /// `Flay::Erubi#add_expression`: `<%==` appends with
207
+ /// `_buf.safe_expr_append=`, `<%=` with `_buf.append=`. A block
208
+ /// expression is appended as is; any other code in parentheses.
209
+ fn add_expression(&mut self, indicator: Option<&str>, code: &str) {
210
+ self.flush_newline_if_pending();
211
+ if indicator == Some("==") {
212
+ self.src.push_str("_buf.safe_expr_append=");
213
+ } else {
214
+ self.src.push_str("_buf.append=");
215
+ }
216
+ if block_expression(code) {
217
+ self.src.push(' ');
218
+ self.src.push_str(code);
219
+ } else {
220
+ self.src.push('(');
221
+ self.src.push_str(code);
222
+ self.src.push_str(");");
223
+ }
224
+ }
225
+
226
+ /// `Flay::Erubi#add_code`, then `Erubi::Engine#add_code`: the code,
227
+ /// followed by `;` unless it ends with a newline.
228
+ fn add_code(&mut self, code: &str) {
229
+ self.flush_newline_if_pending();
230
+ self.src.push_str(code);
231
+ if !code.ends_with('\n') {
232
+ self.src.push(';');
233
+ }
234
+ }
235
+
236
+ /// `Flay::Erubi#add_postamble`, then `Erubi::Engine#add_postamble`.
237
+ fn add_postamble(&mut self) {
238
+ self.flush_newline_if_pending();
239
+ self.src.push_str(POSTAMBLE);
240
+ }
241
+
242
+ /// `Flay::Erubi#flush_newline_if_pending`: appends the pending newlines
243
+ /// as `_buf.safe_append='\n...';`.
244
+ fn flush_newline_if_pending(&mut self) {
245
+ if self.newline_pending > 0 {
246
+ self.src.push_str("_buf.safe_append='");
247
+ self.src.push_str(&"\n".repeat(self.newline_pending));
248
+ self.src.push_str("';");
249
+ self.newline_pending = 0;
250
+ }
251
+ }
252
+ }
253
+
254
+ /// One match of `Erubi::Engine::DEFAULT_REGEXP`,
255
+ /// `/<%(={1,2}|-|\#|%)?(.*?)([-=])?%>([ \t]*\r?\n)?/m`, as byte offsets
256
+ /// into the template and its four groups.
257
+ struct Tag<'a> {
258
+ start: usize,
259
+ end: usize,
260
+ indicator: Option<&'a str>,
261
+ code: &'a str,
262
+ tailch: Option<&'a str>,
263
+ rspace: Option<&'a str>,
264
+ }
265
+
266
+ /// The first match of `DEFAULT_REGEXP` at or after `from`, as
267
+ /// `input.scan(regexp)` finds it.
268
+ ///
269
+ /// The regexp starts at the first `<%`. It tries the indicator first
270
+ /// (`==` before `=`) and without it only when no `%>` follows the
271
+ /// indicator; that happens only for `<%%>` with no later `%>`. The lazy
272
+ /// code ends at the first `%>`, less a `-` or `=` (`tailch`) just before
273
+ /// it. When the first `<%` has no `%>` after it, no later one does either.
274
+ fn next_tag(input: &str, from: usize) -> Option<Tag<'_>> {
275
+ let bytes = input.as_bytes();
276
+ let start = from + input[from..].find("<%")?;
277
+ let after_open = start + 2;
278
+ for indicator_length in indicator_lengths(&bytes[after_open..]) {
279
+ let code_start = after_open + indicator_length;
280
+ let Some(close) = input[code_start..].find("%>").map(|offset| code_start + offset) else {
281
+ continue;
282
+ };
283
+ let code_end = if close > code_start && matches!(bytes[close - 1], b'-' | b'=') { close - 1 } else { close };
284
+ let close_end = close + 2;
285
+ let rspace_length = rspace_length(&bytes[close_end..]);
286
+ return Some(Tag {
287
+ start,
288
+ end: close_end + rspace_length,
289
+ indicator: (indicator_length > 0).then(|| &input[after_open..code_start]),
290
+ code: &input[code_start..code_end],
291
+ tailch: (code_end < close).then(|| &input[code_end..close]),
292
+ rspace: (rspace_length > 0).then(|| &input[close_end..close_end + rspace_length]),
293
+ });
294
+ }
295
+ None
296
+ }
297
+
298
+ /// The lengths the optional indicator group `(={1,2}|-|\#|%)?` tries, in
299
+ /// order, for the text after `<%`: the indicator, if any, then none.
300
+ fn indicator_lengths(after_open: &[u8]) -> Vec<usize> {
301
+ match after_open {
302
+ [b'=', b'=', ..] => vec![2, 1, 0],
303
+ [b'=' | b'-' | b'#' | b'%', ..] => vec![1, 0],
304
+ _ => vec![0],
305
+ }
306
+ }
307
+
308
+ /// The length of `([ \t]*\r?\n)?` at the start of `after_close`: spaces and
309
+ /// tabs, an optional carriage return and a newline, or nothing.
310
+ fn rspace_length(after_close: &[u8]) -> usize {
311
+ let blanks = after_close.iter().take_while(|&&byte| byte == b' ' || byte == b'\t').count();
312
+ match &after_close[blanks..] {
313
+ [b'\n', ..] => blanks + 1,
314
+ [b'\r', b'\n', ..] => blanks + 2,
315
+ _ => 0,
316
+ }
317
+ }
318
+
319
+ /// `/\A[ \t]*\z/.match?(text)`.
320
+ fn is_spaces_and_tabs(text: &str) -> bool {
321
+ text.bytes().all(|byte| byte == b' ' || byte == b'\t')
322
+ }
323
+
324
+ /// `Flay::Erubi::BLOCK_EXPR.match?(code)`, with
325
+ /// `BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/`.
326
+ ///
327
+ /// The regexp is not anchored at the start and its trailing `\s*\Z` reaches
328
+ /// the end of the code, so it matches when the code, without trailing
329
+ /// whitespace, ends with `{` or with `do` after whitespace or `)`, optionally
330
+ /// followed by block parameters: whitespace, then `|`, anything but `|`,
331
+ /// and `|`.
332
+ fn block_expression(code: &str) -> bool {
333
+ let code = trim_end_whitespace(code);
334
+ let before_parameters = match code.strip_suffix('|') {
335
+ Some(rest) => match rest.rfind('|') {
336
+ Some(opening) => trim_end_whitespace(&rest[..opening]),
337
+ None => return false,
338
+ },
339
+ None => code,
340
+ };
341
+ if before_parameters.ends_with('{') {
342
+ return true;
343
+ }
344
+ match before_parameters.strip_suffix("do") {
345
+ Some(rest) => rest.ends_with(|character: char| character == ')' || is_whitespace(character)),
346
+ None => false,
347
+ }
348
+ }
349
+
350
+ /// The text without trailing `\s` characters.
351
+ fn trim_end_whitespace(text: &str) -> &str {
352
+ text.trim_end_matches(is_whitespace)
353
+ }
354
+
355
+ /// Ruby's regexp `\s`: `[ \t\r\n\f\v]`, ASCII only.
356
+ fn is_whitespace(character: char) -> bool {
357
+ matches!(character, ' ' | '\t' | '\r' | '\n' | '\x0C' | '\x0B')
358
+ }
359
+
360
+ #[cfg(test)]
361
+ mod tests {
362
+ use super::*;
363
+
364
+ fn src(erb: &str) -> String {
365
+ String::from_utf8(erb_to_ruby(erb.as_bytes()).unwrap()).unwrap()
366
+ }
367
+
368
+ #[test]
369
+ fn text_escapes_quotes_and_backslashes() {
370
+ assert_eq!(src("it's a \\ test"), "_buf = ::String.new;_buf.safe_append='it\\'s a \\\\ test';\n_buf.to_s");
371
+ }
372
+
373
+ #[test]
374
+ fn newlines_wait_for_the_next_text() {
375
+ assert_eq!(
376
+ src("<% a %>\n\n\nb\n"),
377
+ "_buf = ::String.new; a \n_buf.safe_append='\n\nb\n';\n_buf.to_s"
378
+ );
379
+ assert_eq!(src("<%= a %>\n\n"), "_buf = ::String.new;_buf.append=( a );\n_buf.safe_append='\n\n';_buf.to_s");
380
+ }
381
+
382
+ #[test]
383
+ fn expressions() {
384
+ assert_eq!(src("<%== a %>"), "_buf = ::String.new;_buf.safe_expr_append=( a );\n_buf.to_s");
385
+ assert_eq!(
386
+ src("<%= form do |f| %>x<% end %>"),
387
+ "_buf = ::String.new;_buf.append= form do |f| _buf.safe_append='x'; end ;\n_buf.to_s"
388
+ );
389
+ assert_eq!(src("<%= a -%>\nb"), "_buf = ::String.new;_buf.append=( a );_buf.safe_append='b';\n_buf.to_s");
390
+ }
391
+
392
+ #[test]
393
+ fn block_expressions() {
394
+ assert!(block_expression(" form_for x do |f| "));
395
+ assert!(block_expression(" foo(x)do"));
396
+ assert!(block_expression(" foo {\n"));
397
+ assert!(block_expression(" foo { |a,\n b| "));
398
+ assert!(!block_expression("do"));
399
+ assert!(!block_expression(" todo"));
400
+ assert!(!block_expression(" foo { |a| }"));
401
+ assert!(!block_expression(" foo do |a"));
402
+ assert!(!block_expression(" foo\u{a0}do"));
403
+ }
404
+
405
+ #[test]
406
+ fn comments_and_literals() {
407
+ assert_eq!(src(" <%# a\nb %>\nc"), "_buf = ::String.new;\n\n_buf.safe_append='c';\n_buf.to_s");
408
+ assert_eq!(src("a<%#%>b"), "_buf = ::String.new;_buf.safe_append='a';;_buf.safe_append='b';\n_buf.to_s");
409
+ assert_eq!(src("<%% a -%>\n"), "_buf = ::String.new;_buf.safe_append='<% a -%>\n';\n_buf.to_s");
410
+ assert_eq!(src("<%%>"), "_buf = ::String.new;;\n_buf.to_s");
411
+ }
412
+
413
+ #[test]
414
+ fn invalid_utf8_raises() {
415
+ let error = erb_to_ruby(b"a\xFFb").unwrap_err();
416
+ assert_eq!(error, RubyException { class: "ArgumentError", message: "invalid byte sequence in UTF-8".to_string() });
417
+ }
418
+ }