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