use std::collections::BTreeMap;
use std::path::PathBuf;
use std::fs::{remove_file, create_dir_all, File};
use std::error::Error;
use syntax_pos::Span;
use ext::base::ExtCtxt;
use diagnostics::plugin::{ErrorMap, ErrorInfo};
use serde_json;
const ERROR_METADATA_PREFIX: &'static str = "tmp/extended-errors";
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorMetadata {
pub description: Option<String>,
pub use_site: Option<ErrorLocation>
}
pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>;
#[derive(PartialEq, Deserialize, Serialize)]
pub struct ErrorLocation {
pub filename: String,
pub line: usize
}
impl ErrorLocation {
pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
ErrorLocation {
filename: loc.filename,
line: loc.line
}
}
}
pub fn get_metadata_dir(prefix: &str) -> PathBuf {
PathBuf::from(ERROR_METADATA_PREFIX).join(prefix)
}
fn get_metadata_path(directory: PathBuf, name: &str) -> PathBuf {
directory.join(format!("{}.json", name))
}
pub fn output_metadata(ecx: &ExtCtxt, prefix: &str, name: &str, err_map: &ErrorMap)
-> Result<(), Box<Error>>
{
let metadata_dir = get_metadata_dir(prefix);
create_dir_all(&metadata_dir)?;
let metadata_path = get_metadata_path(metadata_dir, name);
let mut metadata_file = File::create(&metadata_path)?;
let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| {
let key = k.as_str().to_string();
let value = ErrorMetadata {
description: description.map(|n| n.as_str().to_string()),
use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp))
};
(key, value)
}).collect::<ErrorMetadataMap>();
let result = serde_json::to_writer(&mut metadata_file, &json_map);
if result.is_err() {
remove_file(&metadata_path)?;
}
Ok(result?)
}