Skip to content

Commit

Permalink
Add Spanned type
Browse files Browse the repository at this point in the history
  • Loading branch information
chorman0773 committed Aug 8, 2023
1 parent ca75642 commit 6225d15
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions xlang/xlang_frontend/src/span.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
use core::ops::{Deref, DerefMut};

use xlang::abi::ops::{ChangeOutputType, Residual, Try};

use xlang::abi::try_;

use crate::symbol::Symbol;

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
Expand Down Expand Up @@ -91,3 +97,77 @@ impl<H> Span<H> {
self.is_empty() && self.begin.is_synthetic()
}
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Spanned<T, H> {
val: T,
span: Span<H>,
}

impl<T, H> Deref for Spanned<T, H> {
type Target = T;

fn deref(&self) -> &T {
&self.val
}
}

impl<T, H> DerefMut for Spanned<T, H> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.val
}
}

impl<T, H> Spanned<T, H> {
pub const fn new(val: T, span: Span<H>) -> Self {
Self { val, span }
}

pub fn into_inner(self) -> T {
self.val
}

pub const fn span(&self) -> &Span<H> {
&self.span
}

pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Spanned<U, H> {
let Self { val, span } = self;

Spanned::new(f(val), span)
}

pub fn try_map<R: Try, F: FnOnce(T) -> R>(
self,
f: F,
) -> ChangeOutputType<R, Spanned<R::Output, H>>
where
R::Residual: Residual<Spanned<R::Output, H>>,
{
let Self { val, span } = self;

Try::from_output(Spanned::new(try_!(f(val)), span))
}

pub fn copy_span<U, F: FnOnce(&T) -> U>(&self, f: F) -> Spanned<U, H>
where
H: Copy,
{
let Self { val, span } = self;

Spanned::new(f(val), *span)
}

pub fn try_copy_span<R: Try, F: FnOnce(&T) -> R>(
&self,
f: F,
) -> ChangeOutputType<R, Spanned<R::Output, H>>
where
R::Residual: Residual<Spanned<R::Output, H>>,
H: Copy,
{
let Self { val, span } = self;

Try::from_output(Spanned::new(try_!(f(val)), *span))
}
}

0 comments on commit 6225d15

Please sign in to comment.