]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
942fdb06994c7f54447ad4c4b0b78aba82538ef8
[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 syntex_syntax as syntax;
19 extern crate rustc_serialize;
20
21 extern crate strings;
22
23 extern crate unicode_segmentation;
24 extern crate regex;
25 extern crate diff;
26 extern crate term;
27
28 use syntax::ast;
29 use syntax::codemap::{mk_sp, CodeMap, Span};
30 use syntax::errors::{Handler, DiagnosticBuilder};
31 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
32 use syntax::parse::{self, ParseSess};
33
34 use std::io::{stdout, Write};
35 use std::ops::{Add, Sub};
36 use std::path::{Path, PathBuf};
37 use std::rc::Rc;
38 use std::collections::HashMap;
39 use std::fmt;
40
41 use issues::{BadIssueSeeker, Issue};
42 use filemap::FileMap;
43 use visitor::FmtVisitor;
44 use config::Config;
45
46 pub use self::summary::Summary;
47
48 #[macro_use]
49 mod utils;
50 pub mod config;
51 pub mod filemap;
52 mod visitor;
53 mod checkstyle;
54 mod items;
55 mod missed_spans;
56 mod lists;
57 mod types;
58 mod expr;
59 mod imports;
60 mod issues;
61 mod rewrite;
62 mod string;
63 mod comment;
64 mod modules;
65 pub mod rustfmt_diff;
66 mod chains;
67 mod macros;
68 mod patterns;
69 mod summary;
70
71 const MIN_STRING: usize = 10;
72 // When we get scoped annotations, we should have rustfmt::skip.
73 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
74
75 pub trait Spanned {
76     fn span(&self) -> Span;
77 }
78
79 impl Spanned for ast::Expr {
80     fn span(&self) -> Span {
81         self.span
82     }
83 }
84
85 impl Spanned for ast::Pat {
86     fn span(&self) -> Span {
87         self.span
88     }
89 }
90
91 impl Spanned for ast::Ty {
92     fn span(&self) -> Span {
93         self.span
94     }
95 }
96
97 impl Spanned for ast::Arg {
98     fn span(&self) -> Span {
99         if items::is_named_arg(self) {
100             mk_sp(self.pat.span.lo, self.ty.span.hi)
101         } else {
102             self.ty.span
103         }
104     }
105 }
106
107 #[derive(Copy, Clone, Debug)]
108 pub struct Indent {
109     // Width of the block indent, in characters. Must be a multiple of
110     // Config::tab_spaces.
111     pub block_indent: usize,
112     // Alignment in characters.
113     pub alignment: usize,
114 }
115
116 impl Indent {
117     pub fn new(block_indent: usize, alignment: usize) -> Indent {
118         Indent {
119             block_indent: block_indent,
120             alignment: alignment,
121         }
122     }
123
124     pub fn empty() -> Indent {
125         Indent::new(0, 0)
126     }
127
128     pub fn block_indent(mut self, config: &Config) -> Indent {
129         self.block_indent += config.tab_spaces;
130         self
131     }
132
133     pub fn block_unindent(mut self, config: &Config) -> Indent {
134         self.block_indent -= config.tab_spaces;
135         self
136     }
137
138     pub fn width(&self) -> usize {
139         self.block_indent + self.alignment
140     }
141
142     pub fn to_string(&self, config: &Config) -> String {
143         let (num_tabs, num_spaces) = if config.hard_tabs {
144             (self.block_indent / config.tab_spaces, self.alignment)
145         } else {
146             (0, self.block_indent + self.alignment)
147         };
148         let num_chars = num_tabs + num_spaces;
149         let mut indent = String::with_capacity(num_chars);
150         for _ in 0..num_tabs {
151             indent.push('\t')
152         }
153         for _ in 0..num_spaces {
154             indent.push(' ')
155         }
156         indent
157     }
158 }
159
160 impl Add for Indent {
161     type Output = Indent;
162
163     fn add(self, rhs: Indent) -> Indent {
164         Indent {
165             block_indent: self.block_indent + rhs.block_indent,
166             alignment: self.alignment + rhs.alignment,
167         }
168     }
169 }
170
171 impl Sub for Indent {
172     type Output = Indent;
173
174     fn sub(self, rhs: Indent) -> Indent {
175         Indent::new(self.block_indent - rhs.block_indent,
176                     self.alignment - rhs.alignment)
177     }
178 }
179
180 impl Add<usize> for Indent {
181     type Output = Indent;
182
183     fn add(self, rhs: usize) -> Indent {
184         Indent::new(self.block_indent, self.alignment + rhs)
185     }
186 }
187
188 impl Sub<usize> for Indent {
189     type Output = Indent;
190
191     fn sub(self, rhs: usize) -> Indent {
192         Indent::new(self.block_indent, self.alignment - rhs)
193     }
194 }
195
196 pub enum ErrorKind {
197     // Line has exceeded character limit
198     LineOverflow,
199     // Line ends in whitespace
200     TrailingWhitespace,
201     // TO-DO or FIX-ME item without an issue number
202     BadIssue(Issue),
203 }
204
205 impl fmt::Display for ErrorKind {
206     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
207         match *self {
208             ErrorKind::LineOverflow => write!(fmt, "line exceeded maximum length"),
209             ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
210             ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
211         }
212     }
213 }
214
215 // Formatting errors that are identified *after* rustfmt has run.
216 pub struct FormattingError {
217     line: u32,
218     kind: ErrorKind,
219 }
220
221 impl FormattingError {
222     fn msg_prefix(&self) -> &str {
223         match self.kind {
224             ErrorKind::LineOverflow |
225             ErrorKind::TrailingWhitespace => "Rustfmt failed at",
226             ErrorKind::BadIssue(_) => "WARNING:",
227         }
228     }
229
230     fn msg_suffix(&self) -> &str {
231         match self.kind {
232             ErrorKind::LineOverflow |
233             ErrorKind::TrailingWhitespace => "(sorry)",
234             ErrorKind::BadIssue(_) => "",
235         }
236     }
237 }
238
239 pub struct FormatReport {
240     // Maps stringified file paths to their associated formatting errors.
241     file_error_map: HashMap<String, Vec<FormattingError>>,
242 }
243
244 impl FormatReport {
245     fn new() -> FormatReport {
246         FormatReport { file_error_map: HashMap::new() }
247     }
248
249     pub fn warning_count(&self) -> usize {
250         self.file_error_map.iter().map(|(_, ref errors)| errors.len()).fold(0, |acc, x| acc + x)
251     }
252
253     pub fn has_warnings(&self) -> bool {
254         self.warning_count() > 0
255     }
256 }
257
258 impl fmt::Display for FormatReport {
259     // Prints all the formatting errors.
260     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
261         for (file, errors) in &self.file_error_map {
262             for error in errors {
263                 try!(write!(fmt,
264                             "{} {}:{}: {} {}\n",
265                             error.msg_prefix(),
266                             file,
267                             error.line,
268                             error.kind,
269                             error.msg_suffix()));
270             }
271         }
272         Ok(())
273     }
274 }
275
276 // Formatting which depends on the AST.
277 fn format_ast(krate: &ast::Crate,
278               parse_session: &ParseSess,
279               main_file: &Path,
280               config: &Config)
281               -> FileMap {
282     let mut file_map = FileMap::new();
283     // We always skip children for the "Plain" write mode, since there is
284     // nothing to distinguish the nested module contents.
285     let skip_children = config.skip_children || config.write_mode == config::WriteMode::Plain;
286     for (path, module) in modules::list_files(krate, parse_session.codemap()) {
287         if skip_children && path.as_path() != main_file {
288             continue;
289         }
290         let path = path.to_str().unwrap();
291         if config.verbose {
292             println!("Formatting {}", path);
293         }
294         let mut visitor = FmtVisitor::from_codemap(parse_session, config);
295         visitor.format_separate_mod(module);
296         file_map.insert(path.to_owned(), visitor.buffer);
297     }
298     file_map
299 }
300
301 // Formatting done on a char by char or line by line basis.
302 // TODO(#209) warn on bad license
303 // TODO(#20) other stuff for parity with make tidy
304 fn format_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
305     let mut truncate_todo = Vec::new();
306     let mut report = FormatReport::new();
307
308     // Iterate over the chars in the file map.
309     for (f, text) in file_map.iter() {
310         let mut trims = vec![];
311         let mut last_wspace: Option<usize> = None;
312         let mut line_len = 0;
313         let mut cur_line = 1;
314         let mut newline_count = 0;
315         let mut errors = vec![];
316         let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
317
318         for (c, b) in text.chars() {
319             if c == '\r' {
320                 line_len += c.len_utf8();
321                 continue;
322             }
323
324             // Add warnings for bad todos/ fixmes
325             if let Some(issue) = issue_seeker.inspect(c) {
326                 errors.push(FormattingError {
327                     line: cur_line,
328                     kind: ErrorKind::BadIssue(issue),
329                 });
330             }
331
332             if c == '\n' {
333                 // Check for (and record) trailing whitespace.
334                 if let Some(lw) = last_wspace {
335                     trims.push((cur_line, lw, b));
336                     line_len -= b - lw;
337                 }
338                 // Check for any line width errors we couldn't correct.
339                 if line_len > config.max_width {
340                     errors.push(FormattingError {
341                         line: cur_line,
342                         kind: ErrorKind::LineOverflow,
343                     });
344                 }
345                 line_len = 0;
346                 cur_line += 1;
347                 newline_count += 1;
348                 last_wspace = None;
349             } else {
350                 newline_count = 0;
351                 line_len += c.len_utf8();
352                 if c.is_whitespace() {
353                     if last_wspace.is_none() {
354                         last_wspace = Some(b);
355                     }
356                 } else {
357                     last_wspace = None;
358                 }
359             }
360         }
361
362         if newline_count > 1 {
363             debug!("track truncate: {} {} {}", f, text.len, newline_count);
364             truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
365         }
366
367         for &(l, _, _) in &trims {
368             errors.push(FormattingError {
369                 line: l,
370                 kind: ErrorKind::TrailingWhitespace,
371             });
372         }
373
374         report.file_error_map.insert(f.to_owned(), errors);
375     }
376
377     for (f, l) in truncate_todo {
378         file_map.get_mut(&f).unwrap().truncate(l);
379     }
380
381     report
382 }
383
384 fn parse_input(input: Input,
385                parse_session: &ParseSess)
386                -> Result<ast::Crate, Option<DiagnosticBuilder>> {
387     let result = match input {
388         Input::File(file) => parse::parse_crate_from_file(&file, Vec::new(), &parse_session),
389         Input::Text(text) => {
390             parse::parse_crate_from_source_str("stdin".to_owned(), text, Vec::new(), &parse_session)
391         }
392     };
393
394     // Bail out if the parser recovered from an error.
395     if parse_session.span_diagnostic.has_errors() {
396         return Err(None);
397     }
398
399     result.map_err(|e| Some(e))
400 }
401
402 pub fn format_input(input: Input, config: &Config) -> (Summary, FileMap, FormatReport) {
403     let mut summary = Summary::new();
404     let codemap = Rc::new(CodeMap::new());
405
406     let tty_handler = Handler::with_tty_emitter(ColorConfig::Auto,
407                                                 None,
408                                                 true,
409                                                 false,
410                                                 codemap.clone());
411     let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
412
413     let main_file = match input {
414         Input::File(ref file) => file.clone(),
415         Input::Text(..) => PathBuf::from("stdin"),
416     };
417
418     let krate = match parse_input(input, &parse_session) {
419         Ok(krate) => krate,
420         Err(diagnostic) => {
421             if let Some(mut diagnostic) = diagnostic {
422                 diagnostic.emit();
423             }
424             summary.add_parsing_error();
425             return (summary, FileMap::new(), FormatReport::new());
426         }
427     };
428
429     if parse_session.span_diagnostic.has_errors() {
430         summary.add_parsing_error();
431     }
432
433     // Suppress error output after parsing.
434     let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None, codemap.clone()));
435     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
436
437     let mut file_map = format_ast(&krate, &parse_session, &main_file, config);
438
439     // For some reason, the codemap does not include terminating
440     // newlines so we must add one on for each file. This is sad.
441     filemap::append_newlines(&mut file_map);
442
443     let report = format_lines(&mut file_map, config);
444     if report.has_warnings() {
445         summary.add_formatting_error();
446     }
447     (summary, file_map, report)
448 }
449
450 pub enum Input {
451     File(PathBuf),
452     Text(String),
453 }
454
455 pub fn run(input: Input, config: &Config) -> Summary {
456     let (mut summary, file_map, report) = format_input(input, config);
457     if report.has_warnings() {
458         msg!("{}", report);
459     }
460
461     let mut out = stdout();
462     let write_result = filemap::write_all_files(&file_map, &mut out, config);
463
464     if let Err(msg) = write_result {
465         msg!("Error writing files: {}", msg);
466         summary.add_operational_error();
467     }
468
469     summary
470 }