use comemo::Track;
use crate::diag::{Hint, HintedStrResult, SourceResult, bail};
use crate::engine::Engine;
use crate::foundations::{
Args, Construct, Content, Func, ShowFn, StyleChain, Value, elem,
};
use crate::introspection::{Locatable, Location};
#[derive(Debug, Default, Clone, Hash)]
pub struct Context<'a> {
pub location: Option<Location>,
pub styles: Option<StyleChain<'a>>,
}
impl<'a> Context<'a> {
pub fn none() -> Self {
Self::default()
}
pub fn new(location: Option<Location>, styles: Option<StyleChain<'a>>) -> Self {
Self { location, styles }
}
}
#[comemo::track]
impl<'a> Context<'a> {
pub fn location(&self) -> HintedStrResult<Location> {
require(self.location)
}
pub fn styles(&self) -> HintedStrResult<StyleChain<'a>> {
require(self.styles)
}
pub fn introspect(&self) -> HintedStrResult<()> {
require(self.location.map(|_| ()).or(self.styles.map(|_| ())))
}
}
fn require<T>(val: Option<T>) -> HintedStrResult<T> {
val.ok_or("can only be used when context is known")
.hint("try wrapping this in a `context` expression")
.hint(
"the `context` expression should wrap everything that depends on this function",
)
}
#[elem(Construct, Locatable)]
pub struct ContextElem {
#[required]
#[internal]
func: Func,
}
impl Construct for ContextElem {
fn construct(_: &mut Engine, args: &mut Args) -> SourceResult<Content> {
bail!(args.span, "cannot be constructed manually");
}
}
pub const CONTEXT_RULE: ShowFn<ContextElem> = |elem, engine, styles| {
let loc = elem.location().unwrap();
let context = Context::new(Some(loc), Some(styles));
Ok(elem.func.call::<[Value; 0]>(engine, context.track(), [])?.display())
};