use core::fmt;
use core::num;
use crate as rune;
use crate::alloc;
use crate::alloc::path::Path;
use crate::alloc::prelude::*;
use crate::ast::Span;
use crate::source::Source;
#[cfg(feature = "codespan-reporting")]
use codespan_reporting::files;
#[macro_export]
macro_rules! sources {
($($name:ident => {$($tt:tt)*}),* $(,)?) => {{
let mut sources = $crate::Sources::new();
$(sources.insert($crate::Source::new(stringify!($name), stringify!($($tt)*))?)?;)*
sources
}};
}
#[derive(Debug, Default)]
pub struct Sources {
sources: Vec<Source>,
}
impl Sources {
pub fn new() -> Self {
Self {
sources: Vec::new(),
}
}
pub fn insert(&mut self, source: Source) -> alloc::Result<SourceId> {
let id =
SourceId::try_from(self.sources.len()).expect("could not build a source identifier");
self.sources.try_push(source)?;
Ok(id)
}
pub fn get(&self, id: SourceId) -> Option<&Source> {
self.sources.get(id.into_index())
}
pub(crate) fn name(&self, id: SourceId) -> Option<&str> {
let source = self.sources.get(id.into_index())?;
Some(source.name())
}
pub(crate) fn source(&self, id: SourceId, span: Span) -> Option<&str> {
let source = self.sources.get(id.into_index())?;
source.get(span.range())
}
pub(crate) fn path(&self, id: SourceId) -> Option<&Path> {
let source = self.sources.get(id.into_index())?;
source.path()
}
pub(crate) fn source_ids(&self) -> impl Iterator<Item = SourceId> {
(0..self.sources.len()).map(|index| SourceId::new(index as u32))
}
#[cfg(feature = "cli")]
pub(crate) fn iter(&self) -> impl Iterator<Item = &Source> {
self.sources.iter()
}
}
#[cfg(feature = "codespan-reporting")]
impl<'a> files::Files<'a> for Sources {
type FileId = SourceId;
type Name = &'a str;
type Source = &'a str;
fn name(&'a self, file_id: SourceId) -> Result<Self::Name, files::Error> {
let source = self.get(file_id).ok_or(files::Error::FileMissing)?;
Ok(source.name())
}
fn source(&'a self, file_id: SourceId) -> Result<Self::Source, files::Error> {
let source = self.get(file_id).ok_or(files::Error::FileMissing)?;
Ok(source.as_str())
}
#[cfg(feature = "emit")]
fn line_index(&self, file_id: SourceId, byte_index: usize) -> Result<usize, files::Error> {
let source = self.get(file_id).ok_or(files::Error::FileMissing)?;
Ok(source.line_index(byte_index))
}
#[cfg(feature = "emit")]
fn line_range(
&self,
file_id: SourceId,
line_index: usize,
) -> Result<std::ops::Range<usize>, files::Error> {
let source = self.get(file_id).ok_or(files::Error::FileMissing)?;
let range = source
.line_range(line_index)
.ok_or_else(|| files::Error::LineTooLarge {
given: line_index,
max: source.line_count(),
})?;
Ok(range)
}
}
#[derive(TryClone, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[try_clone(copy)]
#[repr(transparent)]
pub struct SourceId {
index: u32,
}
impl SourceId {
pub const EMPTY: Self = Self::empty();
pub const fn new(index: u32) -> Self {
Self { index }
}
pub const fn empty() -> Self {
Self { index: u32::MAX }
}
pub fn into_index(self) -> usize {
usize::try_from(self.index).expect("source id out of bounds")
}
}
impl fmt::Debug for SourceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.index.fmt(f)
}
}
impl fmt::Display for SourceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.index.fmt(f)
}
}
impl Default for SourceId {
fn default() -> Self {
Self::empty()
}
}
impl TryFrom<usize> for SourceId {
type Error = num::TryFromIntError;
fn try_from(value: usize) -> Result<Self, Self::Error> {
Ok(Self {
index: u32::try_from(value)?,
})
}
}
impl serde::Serialize for SourceId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.index.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for SourceId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(Self {
index: u32::deserialize(deserializer)?,
})
}
}