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 string_buffer::StringBuffer;
17 use std::collections::HashMap;
18 use syntax::codemap::{CodeMap, Span};
21 // This is basically a wrapper around a bunch of Ropes which makes it convenient
22 // to work with libsyntax. It is badly named.
23 pub struct ChangeSet<'a> {
24 file_map: HashMap<String, StringBuffer>,
28 impl<'a> ChangeSet<'a> {
29 // Create a new ChangeSet for a given libsyntax CodeMap.
30 pub fn from_codemap(codemap: &'a CodeMap) -> ChangeSet<'a> {
31 let mut result = ChangeSet {
32 file_map: HashMap::new(),
36 for f in codemap.files.borrow().iter() {
37 // Use the length of the file as a heuristic for how much space we
38 // need. I hope that at some stage someone rounds this up to the next
39 // power of two. TODO check that or do it here.
40 result.file_map.insert(f.name.clone(),
41 StringBuffer::with_capacity(f.src.as_ref().unwrap().len()));
47 pub fn push_str(&mut self, file_name: &str, text: &str) {
48 self.file_map[*file_name].push_str(text)
51 pub fn push_str_span(&mut self, span: Span, text: &str) {
52 let file_name = self.codemap.span_to_filename(span);
53 self.push_str(&file_name, text)
56 pub fn cur_offset(&mut self, file_name: &str) -> usize {
57 self.file_map[*file_name].cur_offset()
60 pub fn cur_offset_span(&mut self, span: Span) -> usize {
61 let file_name = self.codemap.span_to_filename(span);
62 self.cur_offset(&file_name)
65 // Return an iterator over the entire changed text.
66 pub fn text<'c>(&'c self) -> FileIterator<'c, 'a> {
69 keys: self.file_map.keys().collect(),
76 // Iterates over each file in the ChangSet. Yields the filename and the changed
77 // text for that file.
78 pub struct FileIterator<'c, 'a: 'c> {
79 change_set: &'c ChangeSet<'a>,
80 keys: Vec<&'c String>,
84 impl<'c, 'a> Iterator for FileIterator<'c, 'a> {
85 type Item = (&'c str, &'c StringBuffer);
87 fn next(&mut self) -> Option<(&'c str, &'c StringBuffer)> {
88 if self.cur_key >= self.keys.len() {
92 let key = self.keys[self.cur_key];
94 return Some((&key, &self.change_set.file_map[*key]))
98 impl<'a> fmt::Display for ChangeSet<'a> {
99 // Prints the entire changed text.
100 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
101 for (f, r) in self.text() {
102 try!(write!(fmt, "{}:\n", f));
103 try!(write!(fmt, "{}\n\n", r));