]> git.lizzy.rs Git - rust.git/blob - src/string.rs
6a888cf83181c3184beef7c826bcf2c464d87dc6
[rust.git] / src / string.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Format string literals.
12
13 use regex::Regex;
14 use unicode_segmentation::UnicodeSegmentation;
15
16 use config::Config;
17 use shape::Shape;
18 use utils::wrap_str;
19
20 const MIN_STRING: usize = 10;
21
22 /// Describes the layout of a piece of text.
23 pub struct StringFormat<'a> {
24     /// The opening sequence of characters for the piece of text
25     pub opener: &'a str,
26     /// The closing sequence of characters for the piece of text
27     pub closer: &'a str,
28     /// The opening sequence of characters for a line
29     pub line_start: &'a str,
30     /// The closing sequence of characters for a line
31     pub line_end: &'a str,
32     /// The allocated box to fit the text into
33     pub shape: Shape,
34     /// Trim trailing whitespaces
35     pub trim_end: bool,
36     pub config: &'a Config,
37 }
38
39 impl<'a> StringFormat<'a> {
40     pub fn new(shape: Shape, config: &'a Config) -> StringFormat<'a> {
41         StringFormat {
42             opener: "\"",
43             closer: "\"",
44             line_start: " ",
45             line_end: "\\",
46             shape,
47             trim_end: false,
48             config,
49         }
50     }
51
52     /// Returns the maximum number of graphemes that is possible on a line while taking the
53     /// indentation into account.
54     ///
55     /// If we cannot put at least a single character per line, the rewrite won't succeed.
56     fn max_chars_with_indent(&self) -> Option<usize> {
57         Some(
58             self.shape
59                 .width
60                 .checked_sub(self.opener.len() + self.line_end.len() + 1)?
61                 + 1,
62         )
63     }
64
65     /// Like max_chars_with_indent but the indentation is not substracted.
66     /// This allows to fit more graphemes from the string on a line when
67     /// SnippetState::EndWithLineFeed.
68     fn max_chars_without_indent(&self) -> Option<usize> {
69         Some(self.config.max_width().checked_sub(self.line_end.len())?)
70     }
71 }
72
73 pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {
74     let max_chars_with_indent = fmt.max_chars_with_indent()?;
75     let max_chars_without_indent = fmt.max_chars_without_indent()?;
76     let indent_with_newline = fmt.shape.indent.to_string_with_newline(fmt.config);
77     let indent_without_newline = fmt.shape.indent.to_string(fmt.config);
78
79     // Strip line breaks.
80     // With this regex applied, all remaining whitespaces are significant
81     let strip_line_breaks_re = Regex::new(r"([^\\](\\\\)*)\\[\n\r][[:space:]]*").unwrap();
82     let stripped_str = strip_line_breaks_re.replace_all(orig, "$1");
83
84     let graphemes = UnicodeSegmentation::graphemes(&*stripped_str, false).collect::<Vec<&str>>();
85
86     // `cur_start` is the position in `orig` of the start of the current line.
87     let mut cur_start = 0;
88     let mut result = String::with_capacity(
89         stripped_str
90             .len()
91             .checked_next_power_of_two()
92             .unwrap_or(usize::max_value()),
93     );
94     result.push_str(fmt.opener);
95
96     // Snip a line at a time from `stripped_str` until it is used up. Push the snippet
97     // onto result.
98     let mut cur_max_chars = max_chars_with_indent;
99     let is_bareline_ok = fmt.line_start.is_empty() || is_whitespace(fmt.line_start);
100     loop {
101         // All the input starting at cur_start fits on the current line
102         if graphemes.len() - cur_start <= cur_max_chars {
103             for (i, grapheme) in graphemes[cur_start..].iter().enumerate() {
104                 if is_line_feed(grapheme) {
105                     // take care of blank lines
106                     result = trim_right_but_line_feed(fmt.trim_end, result);
107                     result.push_str("\n");
108                     if !is_bareline_ok && cur_start + i + 1 < graphemes.len() {
109                         result.push_str(&indent_without_newline);
110                         result.push_str(fmt.line_start);
111                     }
112                 } else {
113                     result.push_str(grapheme);
114                 }
115             }
116             result = trim_right_but_line_feed(fmt.trim_end, result);
117             break;
118         }
119
120         // The input starting at cur_start needs to be broken
121         match break_string(
122             cur_max_chars,
123             fmt.trim_end,
124             fmt.line_end,
125             &graphemes[cur_start..],
126         ) {
127             SnippetState::LineEnd(line, len) => {
128                 result.push_str(&line);
129                 result.push_str(fmt.line_end);
130                 result.push_str(&indent_with_newline);
131                 result.push_str(fmt.line_start);
132                 cur_max_chars = max_chars_with_indent;
133                 cur_start += len;
134             }
135             SnippetState::EndWithLineFeed(line, len) => {
136                 if line == "\n" && fmt.trim_end {
137                     result = result.trim_right().to_string();
138                 }
139                 result.push_str(&line);
140                 if is_bareline_ok {
141                     // the next line can benefit from the full width
142                     cur_max_chars = max_chars_without_indent;
143                 } else {
144                     result.push_str(&indent_without_newline);
145                     result.push_str(fmt.line_start);
146                     cur_max_chars = max_chars_with_indent;
147                 }
148                 cur_start += len;
149             }
150             SnippetState::EndOfInput(line) => {
151                 result.push_str(&line);
152                 break;
153             }
154         }
155     }
156
157     result.push_str(fmt.closer);
158     wrap_str(result, fmt.config.max_width(), fmt.shape)
159 }
160
161 /// Trims whitespaces to the right except for the line feed character.
162 fn trim_right_but_line_feed(trim_end: bool, result: String) -> String {
163     let whitespace_except_line_feed = |c: char| c.is_whitespace() && c != '\n';
164     if trim_end && result.ends_with(whitespace_except_line_feed) {
165         result
166             .trim_right_matches(whitespace_except_line_feed)
167             .to_string()
168     } else {
169         result
170     }
171 }
172
173 /// Result of breaking a string so it fits in a line and the state it ended in.
174 /// The state informs about what to do with the snippet and how to continue the breaking process.
175 #[derive(Debug, PartialEq)]
176 enum SnippetState {
177     /// The input could not be broken and so rewriting the string is finished.
178     EndOfInput(String),
179     /// The input could be broken and the returned snippet should be ended with a
180     /// `[StringFormat::line_end]`. The next snippet needs to be indented.
181     ///
182     /// The returned string is the line to print out and the number is the length that got read in
183     /// the text being rewritten. That length may be greater than the returned string if trailing
184     /// whitespaces got trimmed.
185     LineEnd(String, usize),
186     /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
187     /// to be rewritten *could* use more width than what is specified by the given shape. For
188     /// example with a multiline string, the next snippet does not need to be indented, allowing
189     /// more characters to be fit within a line.
190     ///
191     /// The returned string is the line to print out and the number is the length that got read in
192     /// the text being rewritten.
193     EndWithLineFeed(String, usize),
194 }
195
196 /// Break the input string at a boundary character around the offset `max_chars`. A boundary
197 /// character is either a punctuation or a whitespace.
198 fn break_string(max_chars: usize, trim_end: bool, line_end: &str, input: &[&str]) -> SnippetState {
199     let break_at = |index /* grapheme at index is included */| {
200         // Take in any whitespaces to the left/right of `input[index]` while
201         // preserving line feeds
202         let not_whitespace_except_line_feed = |g| is_line_feed(g) || !is_whitespace(g);
203         let index_minus_ws = input[0..=index]
204             .iter()
205             .rposition(|grapheme| not_whitespace_except_line_feed(grapheme))
206             .unwrap_or(index);
207         // Take into account newlines occuring in input[0..=index], i.e., the possible next new
208         // line. If there is one, then text after it could be rewritten in a way that the available
209         // space is fully used.
210         for (i, grapheme) in input[0..=index].iter().enumerate() {
211             if is_line_feed(grapheme) {
212                 if i <= index_minus_ws {
213                     let mut line = input[0..i].join("");
214                     if trim_end {
215                         line = line.trim_right().to_string();
216                     }
217                     return SnippetState::EndWithLineFeed(format!("{}\n", line), i + 1);
218                 }
219                 break;
220             }
221         }
222
223         let mut index_plus_ws = index;
224         for (i, grapheme) in input[index + 1..].iter().enumerate() {
225             if !trim_end && is_line_feed(grapheme) {
226                 return SnippetState::EndWithLineFeed(
227                     input[0..=index + 1 + i].join("").to_string(),
228                     index + 2 + i,
229                 );
230             } else if not_whitespace_except_line_feed(grapheme) {
231                 index_plus_ws = index + i;
232                 break;
233             }
234         }
235
236         if trim_end {
237             SnippetState::LineEnd(
238                 input[0..=index_minus_ws].join("").to_string(),
239                 index_plus_ws + 1,
240             )
241         } else {
242             SnippetState::LineEnd(
243                 input[0..=index_plus_ws].join("").to_string(),
244                 index_plus_ws + 1,
245             )
246         }
247     };
248
249     // Find the position in input for breaking the string
250     if line_end.is_empty()
251         && trim_end
252         && !is_whitespace(input[max_chars - 1])
253         && is_whitespace(input[max_chars])
254     {
255         // At a breaking point already
256         // The line won't invalidate the rewriting because:
257         // - no extra space needed for the line_end character
258         // - extra whitespaces to the right can be trimmed
259         return break_at(max_chars - 1);
260     }
261     match input[0..max_chars]
262         .iter()
263         .rposition(|grapheme| is_whitespace(grapheme))
264     {
265         // Found a whitespace and what is on its left side is big enough.
266         Some(index) if index >= MIN_STRING => break_at(index),
267         // No whitespace found, try looking for a punctuation instead
268         _ => match input[0..max_chars]
269             .iter()
270             .rposition(|grapheme| is_punctuation(grapheme))
271         {
272             // Found a punctuation and what is on its left side is big enough.
273             Some(index) if index >= MIN_STRING => break_at(index),
274             // Either no boundary character was found to the left of `input[max_chars]`, or the line
275             // got too small. We try searching for a boundary character to the right.
276             _ => match input[max_chars..]
277                 .iter()
278                 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
279             {
280                 // A boundary was found after the line limit
281                 Some(index) => break_at(max_chars + index),
282                 // No boundary to the right, the input cannot be broken
283                 None => SnippetState::EndOfInput(input.join("").to_string()),
284             },
285         },
286     }
287 }
288
289 fn is_line_feed(grapheme: &str) -> bool {
290     grapheme.as_bytes()[0] == b'\n'
291 }
292
293 fn is_whitespace(grapheme: &str) -> bool {
294     grapheme.chars().all(|c| c.is_whitespace())
295 }
296
297 fn is_punctuation(grapheme: &str) -> bool {
298     match grapheme.as_bytes()[0] {
299         b':' | b',' | b';' | b'.' => true,
300         _ => false,
301     }
302 }
303
304 #[cfg(test)]
305 mod test {
306     use super::{break_string, rewrite_string, SnippetState, StringFormat};
307     use config::Config;
308     use shape::{Indent, Shape};
309     use unicode_segmentation::UnicodeSegmentation;
310
311     #[test]
312     fn issue343() {
313         let config = Default::default();
314         let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
315         rewrite_string("eq_", &fmt);
316     }
317
318     #[test]
319     fn should_break_on_whitespace() {
320         let string = "Placerat felis. Mauris porta ante sagittis purus.";
321         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
322         assert_eq!(
323             break_string(20, false, "", &graphemes[..]),
324             SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
325         );
326         assert_eq!(
327             break_string(20, true, "", &graphemes[..]),
328             SnippetState::LineEnd("Placerat felis.".to_string(), 16)
329         );
330     }
331
332     #[test]
333     fn should_break_on_punctuation() {
334         let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
335         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
336         assert_eq!(
337             break_string(20, false, "", &graphemes[..]),
338             SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
339         );
340     }
341
342     #[test]
343     fn should_break_forward() {
344         let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
345         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
346         assert_eq!(
347             break_string(20, false, "", &graphemes[..]),
348             SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
349         );
350         assert_eq!(
351             break_string(20, true, "", &graphemes[..]),
352             SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
353         );
354     }
355
356     #[test]
357     fn nothing_to_break() {
358         let string = "Venenatis_tellus_vel_tellus";
359         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
360         assert_eq!(
361             break_string(20, false, "", &graphemes[..]),
362             SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
363         );
364     }
365
366     #[test]
367     fn significant_whitespaces() {
368         let string = "Neque in sem.      \n      Pellentesque tellus augue.";
369         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
370         assert_eq!(
371             break_string(15, false, "", &graphemes[..]),
372             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
373         );
374         assert_eq!(
375             break_string(25, false, "", &graphemes[..]),
376             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
377         );
378
379         assert_eq!(
380             break_string(15, true, "", &graphemes[..]),
381             SnippetState::LineEnd("Neque in sem.".to_string(), 19)
382         );
383         assert_eq!(
384             break_string(25, true, "", &graphemes[..]),
385             SnippetState::EndWithLineFeed("Neque in sem.\n".to_string(), 20)
386         );
387     }
388
389     #[test]
390     fn big_whitespace() {
391         let string = "Neque in sem.            Pellentesque tellus augue.";
392         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
393         assert_eq!(
394             break_string(20, false, "", &graphemes[..]),
395             SnippetState::LineEnd("Neque in sem.            ".to_string(), 25)
396         );
397         assert_eq!(
398             break_string(20, true, "", &graphemes[..]),
399             SnippetState::LineEnd("Neque in sem.".to_string(), 25)
400         );
401     }
402
403     #[test]
404     fn newline_in_candidate_line() {
405         let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
406
407         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
408         assert_eq!(
409             break_string(25, false, "", &graphemes[..]),
410             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
411         );
412         assert_eq!(
413             break_string(25, true, "", &graphemes[..]),
414             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
415         );
416
417         let mut config: Config = Default::default();
418         config.set().max_width(27);
419         let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
420         let rewritten_string = rewrite_string(string, &fmt);
421         assert_eq!(
422             rewritten_string,
423             Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
424         );
425     }
426
427     #[test]
428     fn last_line_fit_with_trailing_whitespaces() {
429         let string = "Vivamus id mi.  ";
430         let config: Config = Default::default();
431         let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
432
433         fmt.trim_end = true;
434         let rewritten_string = rewrite_string(string, &fmt);
435         assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
436
437         fmt.trim_end = false; // default value of trim_end
438         let rewritten_string = rewrite_string(string, &fmt);
439         assert_eq!(rewritten_string, Some("\"Vivamus id mi.  \"".to_string()));
440     }
441
442     #[test]
443     fn last_line_fit_with_newline() {
444         let string = "Vivamus id mi.\nVivamus id mi.";
445         let config: Config = Default::default();
446         let fmt = StringFormat {
447             opener: "",
448             closer: "",
449             line_start: "// ",
450             line_end: "",
451             shape: Shape::legacy(100, Indent::from_width(&config, 4)),
452             trim_end: true,
453             config: &config,
454         };
455
456         let rewritten_string = rewrite_string(string, &fmt);
457         assert_eq!(
458             rewritten_string,
459             Some("Vivamus id mi.\n    // Vivamus id mi.".to_string())
460         );
461     }
462
463     #[test]
464     fn overflow_in_non_string_content() {
465         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
466         let config: Config = Default::default();
467         let fmt = StringFormat {
468             opener: "",
469             closer: "",
470             line_start: "// ",
471             line_end: "",
472             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
473             trim_end: true,
474             config: &config,
475         };
476
477         assert_eq!(
478             rewrite_string(comment, &fmt),
479             Some(
480                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus\n        // porttitor"
481                     .to_string()
482             )
483         );
484     }
485
486     #[test]
487     fn overflow_in_non_string_content_with_line_end() {
488         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
489         let config: Config = Default::default();
490         let fmt = StringFormat {
491             opener: "",
492             closer: "",
493             line_start: "// ",
494             line_end: "@",
495             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
496             trim_end: true,
497             config: &config,
498         };
499
500         assert_eq!(
501             rewrite_string(comment, &fmt),
502             Some(
503                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus@\n        // porttitor"
504                     .to_string()
505             )
506         );
507     }
508
509     #[test]
510     fn blank_line_with_non_empty_line_start() {
511         let config: Config = Default::default();
512         let mut fmt = StringFormat {
513             opener: "",
514             closer: "",
515             line_start: "// ",
516             line_end: "",
517             shape: Shape::legacy(30, Indent::from_width(&config, 4)),
518             trim_end: true,
519             config: &config,
520         };
521
522         let comment = "Aenean metus. Vestibulum\n\nac lacus. Vivamus porttitor";
523         assert_eq!(
524             rewrite_string(comment, &fmt),
525             Some(
526                 "Aenean metus. Vestibulum\n    //\n    // ac lacus. Vivamus porttitor".to_string()
527             )
528         );
529
530         fmt.shape = Shape::legacy(15, Indent::from_width(&config, 4));
531         let comment = "Aenean\n\nmetus. Vestibulum ac lacus. Vivamus porttitor";
532         assert_eq!(
533             rewrite_string(comment, &fmt),
534             Some(
535                 r#"Aenean
536     //
537     // metus. Vestibulum
538     // ac lacus. Vivamus
539     // porttitor"#
540                     .to_string()
541             )
542         );
543     }
544
545     #[test]
546     fn retain_blank_lines() {
547         let config: Config = Default::default();
548         let fmt = StringFormat {
549             opener: "",
550             closer: "",
551             line_start: "// ",
552             line_end: "",
553             shape: Shape::legacy(20, Indent::from_width(&config, 4)),
554             trim_end: true,
555             config: &config,
556         };
557
558         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n\n";
559         assert_eq!(
560             rewrite_string(comment, &fmt),
561             Some(
562                 "Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n    //\n".to_string()
563             )
564         );
565
566         let comment = "Aenean\n\nmetus. Vestibulum ac lacus.\n";
567         assert_eq!(
568             rewrite_string(comment, &fmt),
569             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.\n".to_string())
570         );
571
572         let comment = "Aenean\n        \nmetus. Vestibulum ac lacus.";
573         assert_eq!(
574             rewrite_string(comment, &fmt),
575             Some("Aenean\n    //\n    // metus. Vestibulum ac\n    // lacus.".to_string())
576         );
577     }
578
579     #[test]
580     fn boundary_on_edge() {
581         let config: Config = Default::default();
582         let mut fmt = StringFormat {
583             opener: "",
584             closer: "",
585             line_start: "// ",
586             line_end: "",
587             shape: Shape::legacy(13, Indent::from_width(&config, 4)),
588             trim_end: true,
589             config: &config,
590         };
591
592         let comment = "Aenean metus. Vestibulum ac lacus.";
593         assert_eq!(
594             rewrite_string(comment, &fmt),
595             Some("Aenean metus.\n    // Vestibulum ac\n    // lacus.".to_string())
596         );
597
598         fmt.trim_end = false;
599         let comment = "Vestibulum ac lacus.";
600         assert_eq!(
601             rewrite_string(comment, &fmt),
602             Some("Vestibulum \n    // ac lacus.".to_string())
603         );
604
605         fmt.trim_end = true;
606         fmt.line_end = "\\";
607         let comment = "Vestibulum ac lacus.";
608         assert_eq!(
609             rewrite_string(comment, &fmt),
610             Some("Vestibulum\\\n    // ac lacus.".to_string())
611         );
612     }
613 }