use comemo::Track;
use crate::diag::{bail, Hint, HintedStrResult, SourceResult};
use crate::engine::Engine;
use crate::foundations::{
elem, Args, Construct, Content, Func, Packed, Show, StyleChain, Value,
};
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, Show)]
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");
}
}
impl Show for Packed<ContextElem> {
#[typst_macros::time(name = "context", span = self.span())]
fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content> {
let loc = self.location().unwrap();
let context = Context::new(Some(loc), Some(styles));
Ok(self.func.call::<[Value; 0]>(engine, context.track(), [])?.display())
}
}