]> git.lizzy.rs Git - rust.git/blob - src/changes.rs
Merge pull request #90 from marcusklaas/empty-imports
[rust.git] / src / changes.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
12 // TODO
13 // print to files
14 // tests
15
16 use strings::string_buffer::StringBuffer;
17 use std::collections::HashMap;
18 use syntax::codemap::{CodeMap, Span, BytePos};
19 use std::fmt;
20 use std::fs::File;
21 use std::io::{Write, stdout};
22 use WriteMode;
23 use NewlineStyle;
24 use utils::round_up_to_power_of_two;
25
26 // This is basically a wrapper around a bunch of Ropes which makes it convenient
27 // to work with libsyntax. It is badly named.
28 pub struct ChangeSet<'a> {
29     file_map: HashMap<String, StringBuffer>,
30     codemap: &'a CodeMap,
31     file_spans: Vec<(u32, u32)>,
32 }
33
34 impl<'a> ChangeSet<'a> {
35     // Create a new ChangeSet for a given libsyntax CodeMap.
36     pub fn from_codemap(codemap: &'a CodeMap) -> ChangeSet<'a> {
37         let mut result = ChangeSet {
38             file_map: HashMap::new(),
39             codemap: codemap,
40             file_spans: Vec::with_capacity(codemap.files.borrow().len()),
41         };
42
43         for f in codemap.files.borrow().iter() {
44             // Use the length of the file as a heuristic for how much space we
45             // need. Round to the next power of two.
46             let buffer_cap = round_up_to_power_of_two(f.src.as_ref().unwrap().len());
47
48             result.file_map.insert(f.name.clone(), StringBuffer::with_capacity(buffer_cap));
49             result.file_spans.push((f.start_pos.0, f.end_pos.0));
50         }
51
52         result.file_spans.sort();
53
54         result
55     }
56
57     pub fn filespans_for_span(&self, start: BytePos, end: BytePos) -> Vec<(u32, u32)> {
58         assert!(start.0 <= end.0);
59
60         if self.file_spans.len() == 0 {
61             return Vec::new();
62         }
63
64         // idx is the index into file_spans which indicates the current file, we
65         // with the file start denotes.
66         let mut idx = match self.file_spans.binary_search(&(start.0, ::std::u32::MAX)) {
67             Ok(i) => i,
68             Err(0) => 0,
69             Err(i) => i - 1,
70         };
71
72         let mut result = Vec::new();
73         let mut start = start.0;
74         loop {
75             let cur_file = &self.file_spans[idx];
76             idx += 1;
77
78             if idx >= self.file_spans.len() || start >= end.0 {
79                 if start < end.0 {
80                     result.push((start, end.0));
81                 }
82                 return result;
83             }
84
85             let end = ::std::cmp::min(cur_file.1 - 1, end.0);
86             if start < end {
87                 result.push((start, end));
88             }
89             start = self.file_spans[idx].0;
90         }
91     }
92
93     pub fn push_str(&mut self, filename: &str, text: &str) {
94         let buf = self.file_map.get_mut(&*filename).unwrap();
95         buf.push_str(text)
96     }
97
98     pub fn push_str_span(&mut self, span: Span, text: &str) {
99         let file_name = self.codemap.span_to_filename(span);
100         self.push_str(&file_name, text)
101     }
102
103     pub fn get_mut(&mut self, file_name: &str) -> &mut StringBuffer {
104         self.file_map.get_mut(file_name).unwrap()
105     }
106
107     pub fn cur_offset(&mut self, filename: &str) -> usize {
108         self.file_map[&*filename].cur_offset()
109     }
110
111     pub fn cur_offset_span(&mut self, span: Span) -> usize {
112         let filename = self.codemap.span_to_filename(span);
113         self.cur_offset(&filename)
114     }
115
116     // Return an iterator over the entire changed text.
117     pub fn text<'c>(&'c self) -> FileIterator<'c, 'a> {
118         FileIterator {
119             change_set: self,
120             keys: self.file_map.keys().collect(),
121             cur_key: 0,
122         }
123     }
124
125     // Append a newline to the end of each file.
126     pub fn append_newlines(&mut self) {
127         for (_, s) in self.file_map.iter_mut() {
128             s.push_str("\n");
129         }
130     }
131
132     pub fn write_all_files(&self,
133                            mode: WriteMode)
134                            -> Result<(HashMap<String, String>), ::std::io::Error> {
135         let mut result = HashMap::new();
136         for filename in self.file_map.keys() {
137             let one_result = try!(self.write_file(filename, mode));
138             if let Some(r) = one_result {
139                 result.insert(filename.clone(), r);
140             }
141         }
142
143         Ok(result)
144     }
145
146     pub fn write_file(&self,
147                       filename: &str,
148                       mode: WriteMode)
149                       -> Result<Option<String>, ::std::io::Error> {
150         let text = &self.file_map[filename];
151
152         // prints all newlines either as `\n` or as `\r\n`
153         fn write_system_newlines<T>(
154             mut writer: T,
155             text: &StringBuffer)
156             -> Result<(), ::std::io::Error>
157             where T: Write,
158         {
159             match config!(newline_style) {
160                 NewlineStyle::Unix => write!(writer, "{}", text),
161                 NewlineStyle::Windows => {
162                     for (c, _) in text.chars() {
163                         match c {
164                             '\n' => try!(write!(writer, "\r\n")),
165                             '\r' => continue,
166                             c => try!(write!(writer, "{}", c)),
167                         }
168                     }
169                     Ok(())
170                 },
171             }
172         }
173
174         match mode {
175             WriteMode::Overwrite => {
176                 // Do a little dance to make writing safer - write to a temp file
177                 // rename the original to a .bk, then rename the temp file to the
178                 // original.
179                 let tmp_name = filename.to_owned() + ".tmp";
180                 let bk_name = filename.to_owned() + ".bk";
181                 {
182                     // Write text to temp file
183                     let tmp_file = try!(File::create(&tmp_name));
184                     try!(write_system_newlines(tmp_file, text));
185                 }
186
187                 try!(::std::fs::rename(filename, bk_name));
188                 try!(::std::fs::rename(tmp_name, filename));
189             }
190             WriteMode::NewFile(extn) => {
191                 let filename = filename.to_owned() + "." + extn;
192                 let file = try!(File::create(&filename));
193                 try!(write_system_newlines(file, text));
194             }
195             WriteMode::Display => {
196                 println!("{}:\n", filename);
197                 let stdout = stdout();
198                 let stdout_lock = stdout.lock();
199                 try!(write_system_newlines(stdout_lock, text));
200             }
201             WriteMode::Return(_) => {
202                 // io::Write is not implemented for String, working around with Vec<u8>
203                 let mut v = Vec::new();
204                 try!(write_system_newlines(&mut v, text));
205                 // won't panic, we are writing correct utf8
206                 return Ok(Some(String::from_utf8(v).unwrap()));
207             }
208         }
209
210         Ok(None)
211     }
212 }
213
214 // Iterates over each file in the ChangSet. Yields the filename and the changed
215 // text for that file.
216 pub struct FileIterator<'c, 'a: 'c> {
217     change_set: &'c ChangeSet<'a>,
218     keys: Vec<&'c String>,
219     cur_key: usize,
220 }
221
222 impl<'c, 'a> Iterator for FileIterator<'c, 'a> {
223     type Item = (&'c str, &'c StringBuffer);
224
225     fn next(&mut self) -> Option<(&'c str, &'c StringBuffer)> {
226         if self.cur_key >= self.keys.len() {
227             return None;
228         }
229
230         let key = self.keys[self.cur_key];
231         self.cur_key += 1;
232         return Some((&key, &self.change_set.file_map[&*key]))
233     }
234 }
235
236 impl<'a> fmt::Display for ChangeSet<'a> {
237     // Prints the entire changed text.
238     fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
239         for (f, r) in self.text() {
240             try!(write!(fmt, "{}:\n", f));
241             try!(write!(fmt, "{}\n\n", r));
242         }
243         Ok(())
244     }
245 }