| 1 |
//! An example that shows how to implement a simple custom file database. |
| 2 |
//! The database uses 32-bit file-ids, which could be useful for optimizing |
| 3 |
//! memory usage. |
| 4 |
//! |
| 5 |
//! To run this example, execute the following command from the top level of |
| 6 |
//! this repository: |
| 7 |
//! |
| 8 |
//! ```sh |
| 9 |
//! cargo run --example custom_files |
| 10 |
//! ``` |
| 11 |
|
| 12 |
use codespan_reporting::diagnostic::{Diagnostic, Label}; |
| 13 |
use codespan_reporting::term; |
| 14 |
use codespan_reporting::term::termcolor::{ColorChoice, StandardStream}; |
| 15 |
use core::ops::Range; |
| 16 |
|
| 17 |
fn main() -> anyhow::Result<()> { |
| 18 |
let mut files = files::Files::new(); |
| 19 |
|
| 20 |
let file_id0 = files.add("0.greeting", "hello world!").unwrap(); |
| 21 |
let file_id1 = files.add("1.greeting", "bye world").unwrap(); |
| 22 |
|
| 23 |
let messages = vec![ |
| 24 |
Message::UnwantedGreetings { |
| 25 |
greetings: vec![(file_id0, 0..5), (file_id1, 0..3)], |
| 26 |
}, |
| 27 |
Message::OverTheTopExclamations { |
| 28 |
exclamations: vec![(file_id0, 11..12)], |
| 29 |
}, |
| 30 |
]; |
| 31 |
|
| 32 |
let writer = StandardStream::stderr(ColorChoice::Always); |
| 33 |
let config = term::Config::default(); |
| 34 |
for message in &messages { |
| 35 |
let writer = &mut writer.lock(); |
| 36 |
term::emit(writer, &config, &files, &message.to_diagnostic())?; |
| 37 |
} |
| 38 |
|
| 39 |
Ok(()) |
| 40 |
} |
| 41 |
|
| 42 |
/// A module containing the file implementation |
| 43 |
mod files { |
| 44 |
use codespan_reporting::files; |
| 45 |
use core::ops::Range; |
| 46 |
|
| 47 |
/// A file that is backed by an `Arc<String>`. |
| 48 |
#[derive(Debug, Clone)] |
| 49 |
struct File { |
| 50 |
/// The name of the file. |
| 51 |
name: String, |
| 52 |
/// The source code of the file. |
| 53 |
source: String, |
| 54 |
/// The starting byte indices in the source code. |
| 55 |
line_starts: Vec<usize>, |
| 56 |
} |
| 57 |
|
| 58 |
impl File { |
| 59 |
fn line_start(&self, line_index: usize) -> Result<usize, files::Error> { |
| 60 |
use core::cmp::Ordering; |
| 61 |
|
| 62 |
match line_index.cmp(&self.line_starts.len()) { |
| 63 |
Ordering::Less => Ok(*self |
| 64 |
.line_starts |
| 65 |
.get(line_index) |
| 66 |
.expect("failed despite previous check")), |
| 67 |
Ordering::Equal => Ok(self.source.len()), |
| 68 |
Ordering::Greater => Err(files::Error::LineTooLarge { |
| 69 |
given: line_index, |
| 70 |
max: self.line_starts.len() - 1, |
| 71 |
}), |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
/// An opaque file identifier. |
| 77 |
#[derive(Copy, Clone, PartialEq, Eq)] |
| 78 |
pub struct FileId(u32); |
| 79 |
|
| 80 |
#[derive(Debug, Clone)] |
| 81 |
pub struct Files { |
| 82 |
files: Vec<File>, |
| 83 |
} |
| 84 |
|
| 85 |
impl Files { |
| 86 |
/// Create a new files database. |
| 87 |
pub fn new() -> Files { |
| 88 |
Files { files: Vec::new() } |
| 89 |
} |
| 90 |
|
| 91 |
/// Add a file to the database, returning the handle that can be used to |
| 92 |
/// refer to it again. |
| 93 |
pub fn add( |
| 94 |
&mut self, |
| 95 |
name: impl Into<String>, |
| 96 |
source: impl Into<String>, |
| 97 |
) -> Option<FileId> { |
| 98 |
use core::convert::TryFrom; |
| 99 |
|
| 100 |
let file_id = FileId(u32::try_from(self.files.len()).ok()?); |
| 101 |
let name = name.into(); |
| 102 |
let source = source.into(); |
| 103 |
let line_starts = files::line_starts(&source).collect(); |
| 104 |
|
| 105 |
self.files.push(File { |
| 106 |
name, |
| 107 |
line_starts, |
| 108 |
source, |
| 109 |
}); |
| 110 |
|
| 111 |
Some(file_id) |
| 112 |
} |
| 113 |
|
| 114 |
/// Get the file corresponding to the given id. |
| 115 |
fn get(&self, file_id: FileId) -> Result<&File, files::Error> { |
| 116 |
self.files |
| 117 |
.get(file_id.0 as usize) |
| 118 |
.ok_or(files::Error::FileMissing) |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
impl<'files> files::Files<'files> for Files { |
| 123 |
type FileId = FileId; |
| 124 |
type Name = &'files str; |
| 125 |
type Source = &'files str; |
| 126 |
|
| 127 |
fn name(&self, file_id: FileId) -> Result<&str, files::Error> { |
| 128 |
Ok(self.get(file_id)?.name.as_ref()) |
| 129 |
} |
| 130 |
|
| 131 |
fn source(&self, file_id: FileId) -> Result<&str, files::Error> { |
| 132 |
Ok(&self.get(file_id)?.source) |
| 133 |
} |
| 134 |
|
| 135 |
fn line_index(&self, file_id: FileId, byte_index: usize) -> Result<usize, files::Error> { |
| 136 |
self.get(file_id)? |
| 137 |
.line_starts |
| 138 |
.binary_search(&byte_index) |
| 139 |
.or_else(|next_line| Ok(next_line - 1)) |
| 140 |
} |
| 141 |
|
| 142 |
fn line_range( |
| 143 |
&self, |
| 144 |
file_id: FileId, |
| 145 |
line_index: usize, |
| 146 |
) -> Result<Range<usize>, files::Error> { |
| 147 |
let file = self.get(file_id)?; |
| 148 |
let line_start = file.line_start(line_index)?; |
| 149 |
let next_line_start = file.line_start(line_index + 1)?; |
| 150 |
|
| 151 |
Ok(line_start..next_line_start) |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
/// A Diagnostic message. |
| 157 |
enum Message { |
| 158 |
UnwantedGreetings { |
| 159 |
greetings: Vec<(files::FileId, Range<usize>)>, |
| 160 |
}, |
| 161 |
OverTheTopExclamations { |
| 162 |
exclamations: Vec<(files::FileId, Range<usize>)>, |
| 163 |
}, |
| 164 |
} |
| 165 |
|
| 166 |
impl Message { |
| 167 |
fn to_diagnostic(&self) -> Diagnostic<files::FileId> { |
| 168 |
match self { |
| 169 |
Message::UnwantedGreetings { greetings } => Diagnostic::error() |
| 170 |
.with_message("greetings are not allowed") |
| 171 |
.with_labels( |
| 172 |
greetings |
| 173 |
.iter() |
| 174 |
.map(|(file_id, range)| { |
| 175 |
Label::primary(*file_id, range.clone()).with_message("a greeting") |
| 176 |
}) |
| 177 |
.collect(), |
| 178 |
) |
| 179 |
.with_notes(vec![ |
| 180 |
"found greetings!".to_owned(), |
| 181 |
"pleas no greetings :(".to_owned(), |
| 182 |
]), |
| 183 |
Message::OverTheTopExclamations { exclamations } => Diagnostic::error() |
| 184 |
.with_message("over-the-top exclamations") |
| 185 |
.with_labels( |
| 186 |
exclamations |
| 187 |
.iter() |
| 188 |
.map(|(file_id, range)| { |
| 189 |
Label::primary(*file_id, range.clone()).with_message("an exclamation") |
| 190 |
}) |
| 191 |
.collect(), |
| 192 |
) |
| 193 |
.with_notes(vec!["ridiculous!".to_owned()]), |
| 194 |
} |
| 195 |
} |
| 196 |
} |