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.
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.
16 use strings::string_buffer::StringBuffer;
17 use std::collections::HashMap;
18 use syntax::codemap::{CodeMap, Span, BytePos};
21 use std::io::{Write, stdout};
24 use utils::round_up_to_power_of_two;
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>,
31 file_spans: Vec<(u32, u32)>,
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(),
40 file_spans: Vec::with_capacity(codemap.files.borrow().len()),
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());
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));
52 result.file_spans.sort();
57 pub fn filespans_for_span(&self, start: BytePos, end: BytePos) -> Vec<(u32, u32)> {
58 assert!(start.0 <= end.0);
60 if self.file_spans.len() == 0 {
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)) {
72 let mut result = Vec::new();
73 let mut start = start.0;
75 let cur_file = &self.file_spans[idx];
78 if idx >= self.file_spans.len() || start >= end.0 {
80 result.push((start, end.0));
85 let end = ::std::cmp::min(cur_file.1 - 1, end.0);
87 result.push((start, end));
89 start = self.file_spans[idx].0;
93 pub fn push_str(&mut self, filename: &str, text: &str) {
94 let buf = self.file_map.get_mut(&*filename).unwrap();
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)
103 pub fn get_mut(&mut self, file_name: &str) -> &mut StringBuffer {
104 self.file_map.get_mut(file_name).unwrap()
107 pub fn cur_offset(&mut self, filename: &str) -> usize {
108 self.file_map[&*filename].cur_offset()
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)
116 // Return an iterator over the entire changed text.
117 pub fn text<'c>(&'c self) -> FileIterator<'c, 'a> {
120 keys: self.file_map.keys().collect(),
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() {
132 pub fn write_all_files(&self,
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);
146 pub fn write_file(&self,
149 -> Result<Option<String>, ::std::io::Error> {
150 let text = &self.file_map[filename];
152 // prints all newlines either as `\n` or as `\r\n`
153 fn write_system_newlines<T>(
156 -> Result<(), ::std::io::Error>
159 match config!(newline_style) {
160 NewlineStyle::Unix => write!(writer, "{}", text),
161 NewlineStyle::Windows => {
162 for (c, _) in text.chars() {
164 '\n' => try!(write!(writer, "\r\n")),
166 c => try!(write!(writer, "{}", c)),
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
179 let tmp_name = filename.to_owned() + ".tmp";
180 let bk_name = filename.to_owned() + ".bk";
182 // Write text to temp file
183 let tmp_file = try!(File::create(&tmp_name));
184 try!(write_system_newlines(tmp_file, text));
187 try!(::std::fs::rename(filename, bk_name));
188 try!(::std::fs::rename(tmp_name, filename));
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));
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));
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()));
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>,
222 impl<'c, 'a> Iterator for FileIterator<'c, 'a> {
223 type Item = (&'c str, &'c StringBuffer);
225 fn next(&mut self) -> Option<(&'c str, &'c StringBuffer)> {
226 if self.cur_key >= self.keys.len() {
230 let key = self.keys[self.cur_key];
232 return Some((&key, &self.change_set.file_map[&*key]))
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));