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