]> git.lizzy.rs Git - rust.git/blob - src/string.rs
7589dca1bf9540e463893c4afe202f9b6a8f70aa
[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_overflow_allowed = 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             let last_line = graphemes[cur_start..].join("");
104             if fmt.trim_end {
105                 result.push_str(&last_line.trim_right());
106             } else {
107                 result.push_str(&last_line);
108             }
109             break;
110         }
111
112         // The input starting at cur_start needs to be broken
113         match break_string(cur_max_chars, fmt.trim_end, &graphemes[cur_start..]) {
114             SnippetState::LineEnd(line, len) => {
115                 result.push_str(&line);
116                 result.push_str(fmt.line_end);
117                 result.push_str(&indent_with_newline);
118                 result.push_str(fmt.line_start);
119                 cur_max_chars = max_chars_with_indent;
120                 cur_start += len;
121             }
122             SnippetState::EndWithLineFeed(line, len) => {
123                 result.push_str(&line);
124                 if is_overflow_allowed {
125                     // the next line can benefit from the full width
126                     cur_max_chars = max_chars_without_indent;
127                 } else {
128                     result.push_str(&indent_without_newline);
129                     result.push_str(fmt.line_start);
130                     cur_max_chars = max_chars_with_indent;
131                 }
132                 cur_start += len;
133             }
134             SnippetState::EndOfInput(line) => {
135                 result.push_str(&line);
136                 break;
137             }
138         }
139     }
140
141     result.push_str(fmt.closer);
142     wrap_str(result, fmt.config.max_width(), fmt.shape)
143 }
144
145 /// Result of breaking a string so it fits in a line and the state it ended in.
146 /// The state informs about what to do with the snippet and how to continue the breaking process.
147 #[derive(Debug, PartialEq)]
148 enum SnippetState {
149     /// The input could not be broken and so rewriting the string is finished.
150     EndOfInput(String),
151     /// The input could be broken and the returned snippet should be ended with a
152     /// `[StringFormat::line_end]`. The next snippet needs to be indented.
153     ///
154     /// The returned string is the line to print out and the number is the length that got read in
155     /// the text being rewritten. That length may be greater than the returned string if trailing
156     /// whitespaces got trimmed.
157     LineEnd(String, usize),
158     /// The input could be broken but a newline is present that cannot be trimmed. The next snippet
159     /// to be rewritten *could* use more width than what is specified by the given shape. For
160     /// example with a multiline string, the next snippet does not need to be indented, allowing
161     /// more characters to be fit within a line.
162     ///
163     /// The returned string is the line to print out and the number is the length that got read in
164     /// the text being rewritten.
165     EndWithLineFeed(String, usize),
166 }
167
168 /// Break the input string at a boundary character around the offset `max_chars`. A boundary
169 /// character is either a punctuation or a whitespace.
170 fn break_string(max_chars: usize, trim_end: bool, input: &[&str]) -> SnippetState {
171     let break_at = |index /* grapheme at index is included */| {
172         // Take in any whitespaces to the left/right of `input[index]` and
173         // check if there is a line feed, in which case whitespaces needs to be kept.
174         let mut index_minus_ws = index;
175         for (i, grapheme) in input[0..=index].iter().enumerate().rev() {
176             if !is_whitespace(grapheme) {
177                 index_minus_ws = i;
178                 break;
179             }
180         }
181         // Take into account newlines occuring in input[0..=index], i.e., the possible next new
182         // line. If there is one, then text after it could be rewritten in a way that the available
183         // space is fully used.
184         for (i, grapheme) in input[0..=index].iter().enumerate() {
185             if is_line_feed(grapheme) {
186                 if i < index_minus_ws || !trim_end {
187                     return SnippetState::EndWithLineFeed(input[0..=i].join("").to_string(), i + 1);
188                 }
189                 break;
190             }
191         }
192
193         let mut index_plus_ws = index;
194         for (i, grapheme) in input[index + 1..].iter().enumerate() {
195             if !trim_end && is_line_feed(grapheme) {
196                 return SnippetState::EndWithLineFeed(
197                     input[0..=index + 1 + i].join("").to_string(),
198                     index + 2 + i,
199                 );
200             } else if !is_whitespace(grapheme) {
201                 index_plus_ws = index + i;
202                 break;
203             }
204         }
205
206         if trim_end {
207             SnippetState::LineEnd(
208                 input[0..=index_minus_ws].join("").to_string(),
209                 index_plus_ws + 1,
210             )
211         } else {
212             SnippetState::LineEnd(
213                 input[0..=index_plus_ws].join("").to_string(),
214                 index_plus_ws + 1,
215             )
216         }
217     };
218
219     // Find the position in input for breaking the string
220     match input[0..max_chars]
221         .iter()
222         .rposition(|grapheme| is_whitespace(grapheme))
223     {
224         // Found a whitespace and what is on its left side is big enough.
225         Some(index) if index >= MIN_STRING => break_at(index),
226         // No whitespace found, try looking for a punctuation instead
227         _ => match input[0..max_chars]
228             .iter()
229             .rposition(|grapheme| is_punctuation(grapheme))
230         {
231             // Found a punctuation and what is on its left side is big enough.
232             Some(index) if index >= MIN_STRING => break_at(index),
233             // Either no boundary character was found to the left of `input[max_chars]`, or the line
234             // got too small. We try searching for a boundary character to the right.
235             _ => match input[max_chars..]
236                 .iter()
237                 .position(|grapheme| is_whitespace(grapheme) || is_punctuation(grapheme))
238             {
239                 // A boundary was found after the line limit
240                 Some(index) => break_at(max_chars + index),
241                 // No boundary to the right, the input cannot be broken
242                 None => SnippetState::EndOfInput(input.join("").to_string()),
243             },
244         },
245     }
246 }
247
248 fn is_line_feed(grapheme: &str) -> bool {
249     grapheme.as_bytes()[0] == b'\n'
250 }
251
252 fn is_whitespace(grapheme: &str) -> bool {
253     grapheme.chars().all(|c| c.is_whitespace())
254 }
255
256 fn is_punctuation(grapheme: &str) -> bool {
257     match grapheme.as_bytes()[0] {
258         b':' | b',' | b';' | b'.' => true,
259         _ => false,
260     }
261 }
262
263 #[cfg(test)]
264 mod test {
265     use super::{break_string, rewrite_string, SnippetState, StringFormat};
266     use config::Config;
267     use shape::{Indent, Shape};
268     use unicode_segmentation::UnicodeSegmentation;
269
270     #[test]
271     fn issue343() {
272         let config = Default::default();
273         let fmt = StringFormat::new(Shape::legacy(2, Indent::empty()), &config);
274         rewrite_string("eq_", &fmt);
275     }
276
277     #[test]
278     fn should_break_on_whitespace() {
279         let string = "Placerat felis. Mauris porta ante sagittis purus.";
280         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
281         assert_eq!(
282             break_string(20, false, &graphemes[..]),
283             SnippetState::LineEnd("Placerat felis. ".to_string(), 16)
284         );
285         assert_eq!(
286             break_string(20, true, &graphemes[..]),
287             SnippetState::LineEnd("Placerat felis.".to_string(), 16)
288         );
289     }
290
291     #[test]
292     fn should_break_on_punctuation() {
293         let string = "Placerat_felis._Mauris_porta_ante_sagittis_purus.";
294         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
295         assert_eq!(
296             break_string(20, false, &graphemes[..]),
297             SnippetState::LineEnd("Placerat_felis.".to_string(), 15)
298         );
299     }
300
301     #[test]
302     fn should_break_forward() {
303         let string = "Venenatis_tellus_vel_tellus. Aliquam aliquam dolor at justo.";
304         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
305         assert_eq!(
306             break_string(20, false, &graphemes[..]),
307             SnippetState::LineEnd("Venenatis_tellus_vel_tellus. ".to_string(), 29)
308         );
309         assert_eq!(
310             break_string(20, true, &graphemes[..]),
311             SnippetState::LineEnd("Venenatis_tellus_vel_tellus.".to_string(), 29)
312         );
313     }
314
315     #[test]
316     fn nothing_to_break() {
317         let string = "Venenatis_tellus_vel_tellus";
318         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
319         assert_eq!(
320             break_string(20, false, &graphemes[..]),
321             SnippetState::EndOfInput("Venenatis_tellus_vel_tellus".to_string())
322         );
323     }
324
325     #[test]
326     fn significant_whitespaces() {
327         let string = "Neque in sem.      \n      Pellentesque tellus augue.";
328         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
329         assert_eq!(
330             break_string(15, false, &graphemes[..]),
331             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
332         );
333         assert_eq!(
334             break_string(25, false, &graphemes[..]),
335             SnippetState::EndWithLineFeed("Neque in sem.      \n".to_string(), 20)
336         );
337         // if `StringFormat::line_end` is true, then the line feed does not matter anymore
338         assert_eq!(
339             break_string(15, true, &graphemes[..]),
340             SnippetState::LineEnd("Neque in sem.".to_string(), 26)
341         );
342         assert_eq!(
343             break_string(25, true, &graphemes[..]),
344             SnippetState::LineEnd("Neque in sem.".to_string(), 26)
345         );
346     }
347
348     #[test]
349     fn big_whitespace() {
350         let string = "Neque in sem.            Pellentesque tellus augue.";
351         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
352         assert_eq!(
353             break_string(20, false, &graphemes[..]),
354             SnippetState::LineEnd("Neque in sem.            ".to_string(), 25)
355         );
356         assert_eq!(
357             break_string(20, true, &graphemes[..]),
358             SnippetState::LineEnd("Neque in sem.".to_string(), 25)
359         );
360     }
361
362     #[test]
363     fn newline_in_candidate_line() {
364         let string = "Nulla\nconsequat erat at massa. Vivamus id mi.";
365
366         let graphemes = UnicodeSegmentation::graphemes(&*string, false).collect::<Vec<&str>>();
367         assert_eq!(
368             break_string(25, false, &graphemes[..]),
369             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
370         );
371         assert_eq!(
372             break_string(25, true, &graphemes[..]),
373             SnippetState::EndWithLineFeed("Nulla\n".to_string(), 6)
374         );
375
376         let mut config: Config = Default::default();
377         config.set().max_width(27);
378         let fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
379         let rewritten_string = rewrite_string(string, &fmt);
380         assert_eq!(
381             rewritten_string,
382             Some("\"Nulla\nconsequat erat at massa. \\\n Vivamus id mi.\"".to_string())
383         );
384     }
385
386     #[test]
387     fn last_line_fit_with_trailing_whitespaces() {
388         let string = "Vivamus id mi.  ";
389         let config: Config = Default::default();
390         let mut fmt = StringFormat::new(Shape::legacy(25, Indent::empty()), &config);
391
392         fmt.trim_end = true;
393         let rewritten_string = rewrite_string(string, &fmt);
394         assert_eq!(rewritten_string, Some("\"Vivamus id mi.\"".to_string()));
395
396         fmt.trim_end = false; // default value of trim_end
397         let rewritten_string = rewrite_string(string, &fmt);
398         assert_eq!(rewritten_string, Some("\"Vivamus id mi.  \"".to_string()));
399     }
400
401     #[test]
402     fn overflow_in_non_string_content() {
403         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
404         let config: Config = Default::default();
405         let fmt = StringFormat {
406             opener: "",
407             closer: "",
408             line_start: "// ",
409             line_end: "",
410             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
411             trim_end: true,
412             config: &config,
413         };
414
415         assert_eq!(
416             rewrite_string(comment, &fmt),
417             Some(
418                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus\n        // porttitor"
419                     .to_string()
420             )
421         );
422     }
423
424     #[test]
425     fn overflow_in_non_string_content_with_line_end() {
426         let comment = "Aenean metus.\nVestibulum ac lacus. Vivamus porttitor";
427         let config: Config = Default::default();
428         let fmt = StringFormat {
429             opener: "",
430             closer: "",
431             line_start: "// ",
432             line_end: "@",
433             shape: Shape::legacy(30, Indent::from_width(&config, 8)),
434             trim_end: true,
435             config: &config,
436         };
437
438         assert_eq!(
439             rewrite_string(comment, &fmt),
440             Some(
441                 "Aenean metus.\n        // Vestibulum ac lacus. Vivamus@\n        // porttitor"
442                     .to_string()
443             )
444         );
445     }
446 }