]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
cargo update
[rust.git] / src / lib.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 #![feature(rustc_private)]
12
13 #[macro_use]
14 extern crate log;
15
16 extern crate serde;
17 #[macro_use]
18 extern crate serde_derive;
19 extern crate serde_json;
20
21 extern crate syntax;
22 extern crate rustc_errors as errors;
23
24 extern crate strings;
25
26 extern crate unicode_segmentation;
27 extern crate regex;
28 extern crate diff;
29 extern crate term;
30
31 use std::collections::HashMap;
32 use std::fmt;
33 use std::io::{self, stdout, Write};
34 use std::ops::{Add, Sub};
35 use std::path::{Path, PathBuf};
36 use std::rc::Rc;
37
38 use errors::{DiagnosticBuilder, Handler};
39 use errors::emitter::{ColorConfig, EmitterWriter};
40 use strings::string_buffer::StringBuffer;
41 use syntax::ast;
42 use syntax::codemap::{CodeMap, FilePathMapping, Span};
43 use syntax::parse::{self, ParseSess};
44
45 use checkstyle::{output_footer, output_header};
46 use config::Config;
47 use filemap::FileMap;
48 use issues::{BadIssueSeeker, Issue};
49 use utils::mk_sp;
50 use visitor::FmtVisitor;
51
52 pub use self::summary::Summary;
53
54 #[macro_use]
55 mod utils;
56 pub mod config;
57 pub mod codemap;
58 pub mod filemap;
59 pub mod file_lines;
60 pub mod visitor;
61 mod checkstyle;
62 mod items;
63 mod missed_spans;
64 mod lists;
65 mod types;
66 mod expr;
67 mod imports;
68 mod issues;
69 mod rewrite;
70 mod string;
71 mod comment;
72 pub mod modules;
73 pub mod rustfmt_diff;
74 mod chains;
75 mod macros;
76 mod patterns;
77 mod summary;
78 mod vertical;
79
80 pub trait Spanned {
81     fn span(&self) -> Span;
82 }
83
84 impl Spanned for ast::Expr {
85     fn span(&self) -> Span {
86         if self.attrs.is_empty() {
87             self.span
88         } else {
89             mk_sp(self.attrs[0].span.lo, self.span.hi)
90         }
91     }
92 }
93
94 impl Spanned for ast::Stmt {
95     fn span(&self) -> Span {
96         match self.node {
97             // Cover attributes
98             ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => {
99                 mk_sp(expr.span().lo, self.span.hi)
100             }
101             _ => self.span,
102         }
103     }
104 }
105
106 impl Spanned for ast::Pat {
107     fn span(&self) -> Span {
108         self.span
109     }
110 }
111
112 impl Spanned for ast::Ty {
113     fn span(&self) -> Span {
114         self.span
115     }
116 }
117
118 impl Spanned for ast::Arm {
119     fn span(&self) -> Span {
120         let hi = self.body.span.hi;
121         if self.attrs.is_empty() {
122             mk_sp(self.pats[0].span.lo, hi)
123         } else {
124             mk_sp(self.attrs[0].span.lo, hi)
125         }
126     }
127 }
128
129 impl Spanned for ast::Arg {
130     fn span(&self) -> Span {
131         if items::is_named_arg(self) {
132             utils::mk_sp(self.pat.span.lo, self.ty.span.hi)
133         } else {
134             self.ty.span
135         }
136     }
137 }
138
139 impl Spanned for ast::StructField {
140     fn span(&self) -> Span {
141         if self.attrs.is_empty() {
142             mk_sp(self.span.lo, self.ty.span.hi)
143         } else {
144             // Include attributes and doc comments, if present
145             mk_sp(self.attrs[0].span.lo, self.ty.span.hi)
146         }
147     }
148 }
149
150 impl Spanned for ast::Field {
151     fn span(&self) -> Span {
152         let lo = if self.attrs.is_empty() {
153             self.span.lo
154         } else {
155             self.attrs[0].span.lo
156         };
157         mk_sp(lo, self.span.hi)
158     }
159 }
160
161 impl Spanned for ast::WherePredicate {
162     fn span(&self) -> Span {
163         match *self {
164             ast::WherePredicate::BoundPredicate(ref p) => p.span,
165             ast::WherePredicate::RegionPredicate(ref p) => p.span,
166             ast::WherePredicate::EqPredicate(ref p) => p.span,
167         }
168     }
169 }
170
171 impl Spanned for ast::FunctionRetTy {
172     fn span(&self) -> Span {
173         match *self {
174             ast::FunctionRetTy::Default(span) => span,
175             ast::FunctionRetTy::Ty(ref ty) => ty.span,
176         }
177     }
178 }
179
180 impl Spanned for ast::TyParam {
181     fn span(&self) -> Span {
182         // Note that ty.span is the span for ty.ident, not the whole item.
183         let lo = if self.attrs.is_empty() {
184             self.span.lo
185         } else {
186             self.attrs[0].span.lo
187         };
188         if let Some(ref def) = self.default {
189             return mk_sp(lo, def.span.hi);
190         }
191         if self.bounds.is_empty() {
192             return mk_sp(lo, self.span.hi);
193         }
194         let hi = self.bounds[self.bounds.len() - 1].span().hi;
195         mk_sp(lo, hi)
196     }
197 }
198
199 impl Spanned for ast::TyParamBound {
200     fn span(&self) -> Span {
201         match *self {
202             ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span,
203             ast::TyParamBound::RegionTyParamBound(ref l) => l.span,
204         }
205     }
206 }
207
208 #[derive(Copy, Clone, Debug)]
209 pub struct Indent {
210     // Width of the block indent, in characters. Must be a multiple of
211     // Config::tab_spaces.
212     pub block_indent: usize,
213     // Alignment in characters.
214     pub alignment: usize,
215 }
216
217 impl Indent {
218     pub fn new(block_indent: usize, alignment: usize) -> Indent {
219         Indent {
220             block_indent: block_indent,
221             alignment: alignment,
222         }
223     }
224
225     pub fn empty() -> Indent {
226         Indent::new(0, 0)
227     }
228
229     pub fn block_only(&self) -> Indent {
230         Indent {
231             block_indent: self.block_indent,
232             alignment: 0,
233         }
234     }
235
236     pub fn block_indent(mut self, config: &Config) -> Indent {
237         self.block_indent += config.tab_spaces();
238         self
239     }
240
241     pub fn block_unindent(mut self, config: &Config) -> Indent {
242         if self.block_indent < config.tab_spaces() {
243             Indent::new(self.block_indent, 0)
244         } else {
245             self.block_indent -= config.tab_spaces();
246             self
247         }
248     }
249
250     pub fn width(&self) -> usize {
251         self.block_indent + self.alignment
252     }
253
254     pub fn to_string(&self, config: &Config) -> String {
255         let (num_tabs, num_spaces) = if config.hard_tabs() {
256             (self.block_indent / config.tab_spaces(), self.alignment)
257         } else {
258             (0, self.width())
259         };
260         let num_chars = num_tabs + num_spaces;
261         let mut indent = String::with_capacity(num_chars);
262         for _ in 0..num_tabs {
263             indent.push('\t')
264         }
265         for _ in 0..num_spaces {
266             indent.push(' ')
267         }
268         indent
269     }
270 }
271
272 impl Add for Indent {
273     type Output = Indent;
274
275     fn add(self, rhs: Indent) -> Indent {
276         Indent {
277             block_indent: self.block_indent + rhs.block_indent,
278             alignment: self.alignment + rhs.alignment,
279         }
280     }
281 }
282
283 impl Sub for Indent {
284     type Output = Indent;
285
286     fn sub(self, rhs: Indent) -> Indent {
287         Indent::new(
288             self.block_indent - rhs.block_indent,
289             self.alignment - rhs.alignment,
290         )
291     }
292 }
293
294 impl Add<usize> for Indent {
295     type Output = Indent;
296
297     fn add(self, rhs: usize) -> Indent {
298         Indent::new(self.block_indent, self.alignment + rhs)
299     }
300 }
301
302 impl Sub<usize> for Indent {
303     type Output = Indent;
304
305     fn sub(self, rhs: usize) -> Indent {
306         Indent::new(self.block_indent, self.alignment - rhs)
307     }
308 }
309
310 #[derive(Copy, Clone, Debug)]
311 pub struct Shape {
312     pub width: usize,
313     // The current indentation of code.
314     pub indent: Indent,
315     // Indentation + any already emitted text on the first line of the current
316     // statement.
317     pub offset: usize,
318 }
319
320 impl Shape {
321     /// `indent` is the indentation of the first line. The next lines
322     /// should begin with at least `indent` spaces (except backwards
323     /// indentation). The first line should not begin with indentation.
324     /// `width` is the maximum number of characters on the last line
325     /// (excluding `indent`). The width of other lines is not limited by
326     /// `width`.
327     /// Note that in reality, we sometimes use width for lines other than the
328     /// last (i.e., we are conservative).
329     // .......*-------*
330     //        |       |
331     //        |     *-*
332     //        *-----|
333     // |<------------>|  max width
334     // |<---->|          indent
335     //        |<--->|    width
336     pub fn legacy(width: usize, indent: Indent) -> Shape {
337         Shape {
338             width: width,
339             indent: indent,
340             offset: indent.alignment,
341         }
342     }
343
344     pub fn indented(indent: Indent, config: &Config) -> Shape {
345         Shape {
346             width: config.max_width().checked_sub(indent.width()).unwrap_or(0),
347             indent: indent,
348             offset: indent.alignment,
349         }
350     }
351
352     pub fn with_max_width(&self, config: &Config) -> Shape {
353         Shape {
354             width: config
355                 .max_width()
356                 .checked_sub(self.indent.width())
357                 .unwrap_or(0),
358             ..*self
359         }
360     }
361
362     pub fn offset(width: usize, indent: Indent, offset: usize) -> Shape {
363         Shape {
364             width: width,
365             indent: indent,
366             offset: offset,
367         }
368     }
369
370     pub fn visual_indent(&self, extra_width: usize) -> Shape {
371         let alignment = self.offset + extra_width;
372         Shape {
373             width: self.width,
374             indent: Indent::new(self.indent.block_indent, alignment),
375             offset: alignment,
376         }
377     }
378
379     pub fn block_indent(&self, extra_width: usize) -> Shape {
380         if self.indent.alignment == 0 {
381             Shape {
382                 width: self.width,
383                 indent: Indent::new(self.indent.block_indent + extra_width, 0),
384                 offset: 0,
385             }
386         } else {
387             Shape {
388                 width: self.width,
389                 indent: self.indent + extra_width,
390                 offset: self.indent.alignment + extra_width,
391             }
392         }
393     }
394
395     pub fn block_left(&self, width: usize) -> Option<Shape> {
396         self.block_indent(width).sub_width(width)
397     }
398
399     pub fn add_offset(&self, extra_width: usize) -> Shape {
400         Shape {
401             offset: self.offset + extra_width,
402             ..*self
403         }
404     }
405
406     pub fn block(&self) -> Shape {
407         Shape {
408             indent: self.indent.block_only(),
409             ..*self
410         }
411     }
412
413     pub fn sub_width(&self, width: usize) -> Option<Shape> {
414         Some(Shape {
415             width: try_opt!(self.width.checked_sub(width)),
416             ..*self
417         })
418     }
419
420     pub fn shrink_left(&self, width: usize) -> Option<Shape> {
421         Some(Shape {
422             width: try_opt!(self.width.checked_sub(width)),
423             indent: self.indent + width,
424             offset: self.offset + width,
425         })
426     }
427
428     pub fn offset_left(&self, width: usize) -> Option<Shape> {
429         self.add_offset(width).sub_width(width)
430     }
431
432     pub fn used_width(&self) -> usize {
433         self.indent.block_indent + self.offset
434     }
435
436     pub fn rhs_overhead(&self, config: &Config) -> usize {
437         config
438             .max_width()
439             .checked_sub(self.used_width() + self.width)
440             .unwrap_or(0)
441     }
442 }
443
444 pub enum ErrorKind {
445     // Line has exceeded character limit (found, maximum)
446     LineOverflow(usize, usize),
447     // Line ends in whitespace
448     TrailingWhitespace,
449     // TO-DO or FIX-ME item without an issue number
450     BadIssue(Issue),
451 }
452
453 impl fmt::Display for ErrorKind {
454     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
455         match *self {
456             ErrorKind::LineOverflow(found, maximum) => write!(
457                 fmt,
458                 "line exceeded maximum length (maximum: {}, found: {})",
459                 maximum,
460                 found
461             ),
462             ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
463             ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
464         }
465     }
466 }
467
468 // Formatting errors that are identified *after* rustfmt has run.
469 pub struct FormattingError {
470     line: u32,
471     kind: ErrorKind,
472 }
473
474 impl FormattingError {
475     fn msg_prefix(&self) -> &str {
476         match self.kind {
477             ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "Rustfmt failed at",
478             ErrorKind::BadIssue(_) => "WARNING:",
479         }
480     }
481
482     fn msg_suffix(&self) -> &str {
483         match self.kind {
484             ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "(sorry)",
485             ErrorKind::BadIssue(_) => "",
486         }
487     }
488 }
489
490 pub struct FormatReport {
491     // Maps stringified file paths to their associated formatting errors.
492     file_error_map: HashMap<String, Vec<FormattingError>>,
493 }
494
495 impl FormatReport {
496     fn new() -> FormatReport {
497         FormatReport {
498             file_error_map: HashMap::new(),
499         }
500     }
501
502     pub fn warning_count(&self) -> usize {
503         self.file_error_map
504             .iter()
505             .map(|(_, errors)| errors.len())
506             .fold(0, |acc, x| acc + x)
507     }
508
509     pub fn has_warnings(&self) -> bool {
510         self.warning_count() > 0
511     }
512 }
513
514 impl fmt::Display for FormatReport {
515     // Prints all the formatting errors.
516     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
517         for (file, errors) in &self.file_error_map {
518             for error in errors {
519                 write!(
520                     fmt,
521                     "{} {}:{}: {} {}\n",
522                     error.msg_prefix(),
523                     file,
524                     error.line,
525                     error.kind,
526                     error.msg_suffix()
527                 )?;
528             }
529         }
530         Ok(())
531     }
532 }
533
534 // Formatting which depends on the AST.
535 fn format_ast<F>(
536     krate: &ast::Crate,
537     mut parse_session: &mut ParseSess,
538     main_file: &Path,
539     config: &Config,
540     codemap: &Rc<CodeMap>,
541     mut after_file: F,
542 ) -> Result<(FileMap, bool), io::Error>
543 where
544     F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>,
545 {
546     let mut result = FileMap::new();
547     // diff mode: check if any files are differing
548     let mut has_diff = false;
549
550     // We always skip children for the "Plain" write mode, since there is
551     // nothing to distinguish the nested module contents.
552     let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
553     for (path, module) in modules::list_files(krate, parse_session.codemap()) {
554         if skip_children && path.as_path() != main_file {
555             continue;
556         }
557         let path_str = path.to_str().unwrap();
558         if config.verbose() {
559             println!("Formatting {}", path_str);
560         }
561         {
562             let mut visitor = FmtVisitor::from_codemap(parse_session, config);
563             let filemap = visitor.codemap.lookup_char_pos(module.inner.lo).file;
564             // Format inner attributes if available.
565             if !krate.attrs.is_empty() && path == main_file {
566                 visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner);
567             } else {
568                 visitor.last_pos = filemap.start_pos;
569             }
570             visitor.format_separate_mod(module, &*filemap);
571
572             has_diff |= after_file(path_str, &mut visitor.buffer)?;
573
574             result.push((path_str.to_owned(), visitor.buffer));
575         }
576         // Reset the error count.
577         if parse_session.span_diagnostic.has_errors() {
578             let silent_emitter = Box::new(EmitterWriter::new(
579                 Box::new(Vec::new()),
580                 Some(codemap.clone()),
581             ));
582             parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
583         }
584     }
585
586     Ok((result, has_diff))
587 }
588
589 // Formatting done on a char by char or line by line basis.
590 // FIXME(#209) warn on bad license
591 // FIXME(#20) other stuff for parity with make tidy
592 fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {
593     // Iterate over the chars in the file map.
594     let mut trims = vec![];
595     let mut last_wspace: Option<usize> = None;
596     let mut line_len = 0;
597     let mut cur_line = 1;
598     let mut newline_count = 0;
599     let mut errors = vec![];
600     let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
601
602     for (c, b) in text.chars() {
603         if c == '\r' {
604             continue;
605         }
606
607         let format_line = config.file_lines().contains_line(name, cur_line as usize);
608
609         if format_line {
610             // Add warnings for bad todos/ fixmes
611             if let Some(issue) = issue_seeker.inspect(c) {
612                 errors.push(FormattingError {
613                     line: cur_line,
614                     kind: ErrorKind::BadIssue(issue),
615                 });
616             }
617         }
618
619         if c == '\n' {
620             if format_line {
621                 // Check for (and record) trailing whitespace.
622                 if let Some(lw) = last_wspace {
623                     trims.push((cur_line, lw, b));
624                     line_len -= 1;
625                 }
626
627                 // Check for any line width errors we couldn't correct.
628                 if config.error_on_line_overflow() && line_len > config.max_width() {
629                     errors.push(FormattingError {
630                         line: cur_line,
631                         kind: ErrorKind::LineOverflow(line_len, config.max_width()),
632                     });
633                 }
634             }
635
636             line_len = 0;
637             cur_line += 1;
638             newline_count += 1;
639             last_wspace = None;
640         } else {
641             newline_count = 0;
642             line_len += 1;
643             if c.is_whitespace() {
644                 if last_wspace.is_none() {
645                     last_wspace = Some(b);
646                 }
647             } else {
648                 last_wspace = None;
649             }
650         }
651     }
652
653     if newline_count > 1 {
654         debug!("track truncate: {} {}", text.len, newline_count);
655         let line = text.len - newline_count + 1;
656         text.truncate(line);
657     }
658
659     for &(l, _, _) in &trims {
660         errors.push(FormattingError {
661             line: l,
662             kind: ErrorKind::TrailingWhitespace,
663         });
664     }
665
666     report.file_error_map.insert(name.to_owned(), errors);
667 }
668
669 fn parse_input(
670     input: Input,
671     parse_session: &ParseSess,
672 ) -> Result<ast::Crate, Option<DiagnosticBuilder>> {
673     let result = match input {
674         Input::File(file) => {
675             let mut parser = parse::new_parser_from_file(parse_session, &file);
676             parser.cfg_mods = false;
677             parser.parse_crate_mod()
678         }
679         Input::Text(text) => {
680             let mut parser =
681                 parse::new_parser_from_source_str(parse_session, "stdin".to_owned(), text);
682             parser.cfg_mods = false;
683             parser.parse_crate_mod()
684         }
685     };
686
687     match result {
688         Ok(c) => {
689             if parse_session.span_diagnostic.has_errors() {
690                 // Bail out if the parser recovered from an error.
691                 Err(None)
692             } else {
693                 Ok(c)
694             }
695         }
696         Err(e) => Err(Some(e)),
697     }
698 }
699
700 pub fn format_input<T: Write>(
701     input: Input,
702     config: &Config,
703     mut out: Option<&mut T>,
704 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
705     let mut summary = Summary::new();
706     if config.disable_all_formatting() {
707         return Ok((summary, FileMap::new(), FormatReport::new()));
708     }
709     let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
710
711     let tty_handler =
712         Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
713     let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
714
715     let main_file = match input {
716         Input::File(ref file) => file.clone(),
717         Input::Text(..) => PathBuf::from("stdin"),
718     };
719
720     let krate = match parse_input(input, &parse_session) {
721         Ok(krate) => krate,
722         Err(diagnostic) => {
723             if let Some(mut diagnostic) = diagnostic {
724                 diagnostic.emit();
725             }
726             summary.add_parsing_error();
727             return Ok((summary, FileMap::new(), FormatReport::new()));
728         }
729     };
730
731     if parse_session.span_diagnostic.has_errors() {
732         summary.add_parsing_error();
733     }
734
735     // Suppress error output after parsing.
736     let silent_emitter = Box::new(EmitterWriter::new(
737         Box::new(Vec::new()),
738         Some(codemap.clone()),
739     ));
740     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
741
742     let mut report = FormatReport::new();
743
744     match format_ast(
745         &krate,
746         &mut parse_session,
747         &main_file,
748         config,
749         &codemap,
750         |file_name, file| {
751             // For some reason, the codemap does not include terminating
752             // newlines so we must add one on for each file. This is sad.
753             filemap::append_newline(file);
754
755             format_lines(file, file_name, config, &mut report);
756
757             if let Some(ref mut out) = out {
758                 return filemap::write_file(file, file_name, out, config);
759             }
760             Ok(false)
761         },
762     ) {
763         Ok((file_map, has_diff)) => {
764             if report.has_warnings() {
765                 summary.add_formatting_error();
766             }
767
768             if has_diff {
769                 summary.add_diff();
770             }
771
772             Ok((summary, file_map, report))
773         }
774         Err(e) => Err((e, summary)),
775     }
776 }
777
778 #[derive(Debug)]
779 pub enum Input {
780     File(PathBuf),
781     Text(String),
782 }
783
784 pub fn run(input: Input, config: &Config) -> Summary {
785     let mut out = &mut stdout();
786     output_header(out, config.write_mode()).ok();
787     match format_input(input, config, Some(out)) {
788         Ok((summary, _, report)) => {
789             output_footer(out, config.write_mode()).ok();
790
791             if report.has_warnings() {
792                 msg!("{}", report);
793             }
794
795             summary
796         }
797         Err((msg, mut summary)) => {
798             msg!("Error writing files: {}", msg);
799             summary.add_operational_error();
800             summary
801         }
802     }
803 }
804
805 #[cfg(test)]
806 mod test {
807     use super::*;
808
809     #[test]
810     fn indent_add_sub() {
811         let indent = Indent::new(4, 8) + Indent::new(8, 12);
812         assert_eq!(12, indent.block_indent);
813         assert_eq!(20, indent.alignment);
814
815         let indent = indent - Indent::new(4, 4);
816         assert_eq!(8, indent.block_indent);
817         assert_eq!(16, indent.alignment);
818     }
819
820     #[test]
821     fn indent_add_sub_alignment() {
822         let indent = Indent::new(4, 8) + 4;
823         assert_eq!(4, indent.block_indent);
824         assert_eq!(12, indent.alignment);
825
826         let indent = indent - 4;
827         assert_eq!(4, indent.block_indent);
828         assert_eq!(8, indent.alignment);
829     }
830
831     #[test]
832     fn indent_to_string_spaces() {
833         let config = Config::default();
834         let indent = Indent::new(4, 8);
835
836         // 12 spaces
837         assert_eq!("            ", indent.to_string(&config));
838     }
839
840     #[test]
841     fn indent_to_string_hard_tabs() {
842         let mut config = Config::default();
843         config.set().hard_tabs(true);
844         let indent = Indent::new(8, 4);
845
846         // 2 tabs + 4 spaces
847         assert_eq!("\t\t    ", indent.to_string(&config));
848     }
849
850     #[test]
851     fn shape_visual_indent() {
852         let config = Config::default();
853         let indent = Indent::new(4, 8);
854         let shape = Shape::legacy(config.max_width(), indent);
855         let shape = shape.visual_indent(20);
856
857         assert_eq!(config.max_width(), shape.width);
858         assert_eq!(4, shape.indent.block_indent);
859         assert_eq!(28, shape.indent.alignment);
860         assert_eq!(28, shape.offset);
861     }
862
863     #[test]
864     fn shape_block_indent_without_alignment() {
865         let config = Config::default();
866         let indent = Indent::new(4, 0);
867         let shape = Shape::legacy(config.max_width(), indent);
868         let shape = shape.block_indent(20);
869
870         assert_eq!(config.max_width(), shape.width);
871         assert_eq!(24, shape.indent.block_indent);
872         assert_eq!(0, shape.indent.alignment);
873         assert_eq!(0, shape.offset);
874     }
875
876     #[test]
877     fn shape_block_indent_with_alignment() {
878         let config = Config::default();
879         let indent = Indent::new(4, 8);
880         let shape = Shape::legacy(config.max_width(), indent);
881         let shape = shape.block_indent(20);
882
883         assert_eq!(config.max_width(), shape.width);
884         assert_eq!(4, shape.indent.block_indent);
885         assert_eq!(28, shape.indent.alignment);
886         assert_eq!(28, shape.offset);
887     }
888 }