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