1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use std::env;
use std::fs;
use std::convert::AsRef;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::collections::HashMap;

use url::Url;

use errors::Result;
use types::{SourceMap, RawToken, Token};


/// Helper for sourcemap generation
///
/// This helper exists because generating and modifying `SourceMap`
/// objects is generally not very comfortable.  As a general aid this
/// type can help.
pub struct SourceMapBuilder {
    file: Option<String>,
    name_map: HashMap<String, u32>,
    names: Vec<String>,
    tokens: Vec<RawToken>,
    source_map: HashMap<String, u32>,
    sources: Vec<String>,
    source_contents: Vec<Option<String>>,
}

fn resolve_local_reference(base: &Url, reference: &str) -> Option<PathBuf> {
    let url = match base.join(reference) {
        Ok(url) => {
            if url.scheme() != "file" {
                return None;
            }
            url
        }
        Err(_) => {
            return None;
        }
    };

    url.to_file_path().ok()
}

impl SourceMapBuilder {
    /// Creates a new source map builder and sets the file.
    pub fn new(file: Option<&str>) -> SourceMapBuilder {
        SourceMapBuilder {
            file: file.map(|x| x.to_string()),
            name_map: HashMap::new(),
            names: vec![],
            tokens: vec![],
            source_map: HashMap::new(),
            sources: vec![],
            source_contents: vec![],
        }
    }

    /// Sets the file for the sourcemap (optional)
    pub fn set_file(&mut self, value: Option<&str>) {
        self.file = value.map(|x| x.to_string());
    }

    /// Returns the currently set file.
    pub fn get_file(&self) -> Option<&str> {
        self.file.as_ref().map(|x| &x[..])
    }

    /// Registers a new source with the builder and returns the source ID.
    pub fn add_source(&mut self, src: &str) -> u32 {
        let count = self.sources.len() as u32;
        let id = *self.source_map.entry(src.into()).or_insert(count);
        if id == count {
            self.sources.push(src.into());
        }
        id
    }

    /// Changes the source name for an already set source.
    pub fn set_source(&mut self, src_id: u32, src: &str) {
        assert!(src_id != !0, "Cannot set sources for tombstone source id");
        self.sources[src_id as usize] = src.to_string();
    }

    /// Looks up a source name for an ID.
    pub fn get_source(&self, src_id: u32) -> Option<&str> {
        self.sources.get(src_id as usize).map(|x| &x[..])
    }

    /// Sets the source contents for an already existing source.
    pub fn set_source_contents(&mut self, src_id: u32, contents: Option<&str>) {
        assert!(src_id != !0, "Cannot set sources for tombstone source id");
        if self.sources.len() > self.source_contents.len() {
            self.source_contents.resize(self.sources.len(), None);
        }
        self.source_contents[src_id as usize] = contents.map(|x| x.to_string());
    }

    /// Returns the current source contents for a source.
    pub fn get_source_contents(&self, src_id: u32) -> Option<&str> {
        self.source_contents.get(src_id as usize).and_then(|x| x.as_ref().map(|x| &x[..]))
    }

    /// Checks if a given source ID has source contents available.
    pub fn has_source_contents(&self, src_id: u32) -> bool {
        self.get_source_contents(src_id).is_some()
    }

    /// Loads source contents from locally accessible files if referenced
    /// accordingly.  Returns the number of loaded source contents
    pub fn load_local_source_contents(&mut self, base_path: Option<&Path>) -> Result<usize> {
        let mut abs_path = env::current_dir()?;
        if let Some(path) = base_path {
            abs_path.push(path);
        }
        let base_url = Url::from_directory_path(&abs_path).unwrap();

        let mut to_read = vec![];
        for (source, &src_id) in self.source_map.iter() {
            if self.has_source_contents(src_id) {
                continue;
            }
            if let Some(path) = resolve_local_reference(&base_url, &source) {
                to_read.push((src_id, path));
            }
        }

        let rv = to_read.len();
        for (src_id, path) in to_read {
            if let Ok(mut f) = fs::File::open(&path) {
                let mut contents = String::new();
                if f.read_to_string(&mut contents).is_ok() {
                    self.set_source_contents(src_id, Some(&contents));
                }
            }
        }

        Ok(rv)
    }

    /// Registers a name with the builder and returns the name ID.
    pub fn add_name(&mut self, name: &str) -> u32 {
        let count = self.names.len() as u32;
        let id = *self.name_map.entry(name.into()).or_insert(count);
        if id == count {
            self.names.push(name.into());
        }
        id
    }

    /// Adds a new mapping to the builder.
    pub fn add(&mut self,
               dst_line: u32,
               dst_col: u32,
               src_line: u32,
               src_col: u32,
               source: Option<&str>,
               name: Option<&str>)
               -> RawToken {
        let src_id = match source {
            Some(source) => self.add_source(source),
            None => !0,
        };
        let name_id = match name {
            Some(name) => self.add_name(name),
            None => !0,
        };
        let raw = RawToken {
            dst_line: dst_line,
            dst_col: dst_col,
            src_line: src_line,
            src_col: src_col,
            src_id: src_id,
            name_id: name_id,
        };
        self.tokens.push(raw);
        raw
    }

    /// Shortcut for adding a new mapping based of an already existing token,
    /// optionally removing the name.
    pub fn add_token(&mut self, token: &Token, with_name: bool) -> RawToken {
        let name = if with_name { token.get_name() } else { None };
        self.add(token.get_dst_line(),
                 token.get_dst_col(),
                 token.get_src_line(),
                 token.get_src_col(),
                 token.get_source(),
                 name)
    }

    /// Strips common prefixes from the sources in the builder
    pub fn strip_prefixes<S: AsRef<str>>(&mut self, prefixes: &[S]) {
        for source in self.sources.iter_mut() {
            for prefix in prefixes {
                let mut prefix = prefix.as_ref().to_string();
                if !prefix.ends_with('/') {
                    prefix.push('/');
                }
                if source.starts_with(&prefix) {
                    *source = source[prefix.len()..].to_string();
                    break;
                }
            }
        }
    }

    /// Converts the builder into a sourcemap.
    pub fn into_sourcemap(self) -> SourceMap {
        let contents = if self.source_contents.len() > 0 {
            Some(self.source_contents)
        } else {
            None
        };
        SourceMap::new(self.file, self.tokens, self.names, self.sources, contents)
    }
}