oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/intro.rs
16.4 KiB, 15 runs
created by r1870400018:63240, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | // U8 owns this file. Introspection functions and the methods of counter, state and location, plus schemas |
| 2 | // for metadata, counter/state updates, context and layout. Each read a context body makes is recorded on |
| 3 | // `engine.reads` for the fixpoint. |
| 4 | // |
| 5 | // A `context` body's errors are delayed, as Typst delays them: the diagnostic is kept and the body shows |
| 6 | // as nothing, so a first pass that cannot yet see a later label does not stop the document. The fixpoint |
| 7 | // clears a pass's diagnostics before the next, so only an error the final pass still makes survives. |
| 8 | |
| 9 | use crate::diag::DiagnosticKind; |
| 10 | use crate::eval::args::Args; |
| 11 | use crate::eval::content::{ |
| 12 | self, |
| 13 | Content, |
| 14 | ElemKind, |
| 15 | FieldDefault, |
| 16 | FieldSpec, |
| 17 | FieldType, |
| 18 | }; |
| 19 | use crate::eval::func::{ |
| 20 | Func, |
| 21 | NativeFunc, |
| 22 | }; |
| 23 | use crate::eval::intro::{ |
| 24 | self as introspect, |
| 25 | Counter, |
| 26 | CounterKey, |
| 27 | CounterUpdate, |
| 28 | State, |
| 29 | }; |
| 30 | use crate::eval::scope::Scope; |
| 31 | use crate::eval::select::{ |
| 32 | self, |
| 33 | Selector, |
| 34 | }; |
| 35 | use crate::eval::styles::StyleChain; |
| 36 | use crate::eval::value::{ |
| 37 | Dict, |
| 38 | Length, |
| 39 | Type, |
| 40 | Value, |
| 41 | }; |
| 42 | use crate::eval::{ |
| 43 | Context, |
| 44 | Engine, |
| 45 | }; |
| 46 | use crate::flow::{ |
| 47 | self, |
| 48 | Region, |
| 49 | }; |
| 50 | use crate::ir::Sp; |
| 51 | use crate::ledger::Position; |
| 52 | use crate::syntax::Span; |
| 53 | |
| 54 | use oxedyne_fe2o3_core::prelude::*; |
| 55 | |
| 56 | use std::sync::Arc; |
| 57 | |
| 58 | native_fns! { |
| 59 | pub enum IntroFn { |
| 60 | Counter => "counter", |
| 61 | State => "state", |
| 62 | Query => "query", |
| 63 | Here => "here", |
| 64 | Locate => "locate", |
| 65 | Measure => "measure", |
| 66 | CounterGet => "get", |
| 67 | CounterAt => "at", |
| 68 | CounterFinal => "final", |
| 69 | CounterDisplay => "display", |
| 70 | CounterStep => "step", |
| 71 | CounterUpdate => "update", |
| 72 | StateGet => "get", |
| 73 | StateAt => "at", |
| 74 | StateFinal => "final", |
| 75 | StateUpdate => "update", |
| 76 | LocationPage => "page", |
| 77 | LocationPosition => "position", |
| 78 | LocationPageNumbering => "page-numbering", |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // Schemas |
| 83 | |
| 84 | const METADATA: &[FieldSpec] = &[ |
| 85 | FieldSpec::required("value", FieldType::Any), |
| 86 | ]; |
| 87 | |
| 88 | const COUNTER_UPDATE: &[FieldSpec] = &[ |
| 89 | FieldSpec::required("key", FieldType::Any), |
| 90 | FieldSpec::named("update", FieldType::Any, FieldDefault::None).synthesised(), // set, step or function |
| 91 | ]; |
| 92 | |
| 93 | const STATE_UPDATE: &[FieldSpec] = &[ |
| 94 | FieldSpec::required("key", FieldType::Of(Type::Str)), |
| 95 | FieldSpec::named("update", FieldType::Any, FieldDefault::None).synthesised(), // a value or a function |
| 96 | ]; |
| 97 | |
| 98 | const FUNC_ONLY: &[FieldSpec] = &[ |
| 99 | FieldSpec::required("func", FieldType::Of(Type::Func)), |
| 100 | ]; |
| 101 | |
| 102 | pub fn fields(kind: ElemKind) -> &'static [FieldSpec] { |
| 103 | match kind { |
| 104 | ElemKind::Metadata => METADATA, |
| 105 | ElemKind::CounterUpdate => COUNTER_UPDATE, |
| 106 | ElemKind::StateUpdate => STATE_UPDATE, |
| 107 | ElemKind::Context => FUNC_ONLY, |
| 108 | ElemKind::Layout => FUNC_ONLY, |
| 109 | _ => &[], |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub fn define(scope: &mut Scope) { |
| 114 | scope.define("counter", Value::Type(Type::Counter)); |
| 115 | scope.define("state", Value::Type(Type::State)); |
| 116 | for f in [IntroFn::Query, IntroFn::Here, IntroFn::Locate, IntroFn::Measure] { |
| 117 | scope.define(f.name(), Value::Func(Func::Native(NativeFunc::Intro(f)))); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// The method of a counter, state or location by name. The names are shared, so `call` settles which |
| 122 | /// type's method runs from the receiver. |
| 123 | pub fn method(name: &str) -> Option<IntroFn> { |
| 124 | match name { |
| 125 | "get" => Some(IntroFn::CounterGet), |
| 126 | "at" => Some(IntroFn::CounterAt), |
| 127 | "final" => Some(IntroFn::CounterFinal), |
| 128 | "display" => Some(IntroFn::CounterDisplay), |
| 129 | "step" => Some(IntroFn::CounterStep), |
| 130 | "update" => Some(IntroFn::CounterUpdate), |
| 131 | "page" => Some(IntroFn::LocationPage), |
| 132 | "position" => Some(IntroFn::LocationPosition), |
| 133 | "page-numbering" => Some(IntroFn::LocationPageNumbering), |
| 134 | _ => None, |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /// The receiver a method was called on. |
| 139 | enum Receiver { |
| 140 | Counter(Arc<Counter>), |
| 141 | State(Arc<State>), |
| 142 | Location(crate::eval::locate::Location), |
| 143 | } |
| 144 | |
| 145 | pub fn call(f: IntroFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> { |
| 146 | let span = args.span; |
| 147 | let out = match f { |
| 148 | IntroFn::Counter => { |
| 149 | let (at, v) = res!(take(engine, &mut args, "key")); |
| 150 | let key = res!(counter_key(engine, at, v)); |
| 151 | Value::Counter(Arc::new(Counter::new(key))) |
| 152 | } |
| 153 | IntroFn::State => { |
| 154 | let key = match res!(take(engine, &mut args, "key")) { |
| 155 | (at, v) => match v.str_cast() { |
| 156 | Some(s) => s.to_string(), |
| 157 | None => return Err(engine.error(DiagnosticKind::Type, at, fmt!( |
| 158 | "expected string, found {}", v.ty().long_name()))), |
| 159 | }, |
| 160 | }; |
| 161 | let init = res!(args.eat::<Value>()).unwrap_or(Value::None); |
| 162 | Value::State(Arc::new(State { key, init })) |
| 163 | } |
| 164 | IntroFn::Query => { |
| 165 | let (at, v) = res!(take(engine, &mut args, "target")); |
| 166 | let sel = res!(select::cast(engine, at, v)); |
| 167 | res!(introspect::check_locatable(engine, at, &sel)); |
| 168 | if engine.context.location.is_none() { |
| 169 | return Err(introspect::no_context(engine, span)); |
| 170 | } |
| 171 | let found = res!(introspect::query(engine, &sel)); |
| 172 | Value::array(found.into_iter().map(Value::Content).collect()) |
| 173 | } |
| 174 | IntroFn::Here => Value::Location(res!(introspect::here(engine, span))), |
| 175 | IntroFn::Locate => { |
| 176 | let (at, v) = res!(take(engine, &mut args, "selector")); |
| 177 | let sel = res!(select::cast(engine, at, v)); |
| 178 | res!(introspect::check_locatable(engine, at, &sel)); |
| 179 | Value::Location(res!(introspect::resolve_unique(engine, span, &sel))) |
| 180 | } |
| 181 | IntroFn::Measure => res!(measure(engine, span, &mut args)), |
| 182 | _ => { |
| 183 | let receiver = match res!(args.eat::<Value>()) { |
| 184 | Some(Value::Counter(c)) => Receiver::Counter(c), |
| 185 | Some(Value::State(s)) => Receiver::State(s), |
| 186 | Some(Value::Location(l)) => Receiver::Location(l), |
| 187 | Some(other) => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 188 | "type {} has no method `{}`", other.ty().name(), f.name()))), |
| 189 | None => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: self")), |
| 190 | }; |
| 191 | match receiver { |
| 192 | Receiver::Counter(c) => res!(counter_method(engine, span, f, &c, &mut args)), |
| 193 | Receiver::State(s) => res!(state_method(engine, span, f, &s, &mut args)), |
| 194 | Receiver::Location(l) => res!(location_method(engine, span, f, l)), |
| 195 | } |
| 196 | } |
| 197 | }; |
| 198 | res!(finish(engine, args)); |
| 199 | Ok(out) |
| 200 | } |
| 201 | |
| 202 | /// The next positional argument and the span to report it at, or "missing argument" at the call. |
| 203 | fn take(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<(Span, Value)> { |
| 204 | match args.items.iter().position(|a| a.name.is_none()) { |
| 205 | Some(i) => { |
| 206 | let a = args.items.remove(i); |
| 207 | let span = if a.span.is_detached() { args.span } else { a.span }; |
| 208 | Ok((span, a.value)) |
| 209 | } |
| 210 | None => Err(engine.error(DiagnosticKind::Type, args.span, fmt!("missing argument: {}", what))), |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | fn expect(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<Value> { |
| 215 | take(engine, args, what).map(|(_, v)| v) |
| 216 | } |
| 217 | |
| 218 | fn finish(engine: &mut Engine, args: Args) -> Outcome<()> { |
| 219 | match args.items.first() { |
| 220 | None => Ok(()), |
| 221 | Some(a) => { |
| 222 | let span = if a.span.is_detached() { args.span } else { a.span }; |
| 223 | let msg = match &a.name { |
| 224 | Some(n) => fmt!("unexpected argument: {}", n), |
| 225 | None => "unexpected argument".to_string(), |
| 226 | }; |
| 227 | Err(engine.error(DiagnosticKind::Type, span, msg)) |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// Typst's `CounterKey` cast: a string, a label, a location, an element function (`page` is the page |
| 233 | /// counter) or a selector, the last two over locatable elements only. |
| 234 | fn counter_key(engine: &mut Engine, span: Span, v: Value) -> Outcome<CounterKey> { |
| 235 | match v.symbol_as_str() { |
| 236 | Value::Str(s) => Ok(CounterKey::Str(s.to_string())), |
| 237 | Value::Label(l) => Ok(CounterKey::Selector(Selector::Label(l))), |
| 238 | Value::Location(l) => Ok(CounterKey::Selector(Selector::Location(l))), |
| 239 | Value::Func(f) => match f.element() { |
| 240 | Some(ElemKind::Page) => Ok(CounterKey::Page), |
| 241 | Some(k) => { |
| 242 | let sel = Selector::Elem(k, None); |
| 243 | res!(introspect::check_locatable(engine, span, &sel)); |
| 244 | Ok(CounterKey::Selector(sel)) |
| 245 | } |
| 246 | None => Err(engine.error(DiagnosticKind::Type, span, "only element functions can be used as selectors")), |
| 247 | }, |
| 248 | Value::Selector(s) => { |
| 249 | res!(introspect::check_locatable(engine, span, &s)); |
| 250 | Ok(CounterKey::Selector((*s).clone())) |
| 251 | } |
| 252 | other => Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 253 | "expected string, label, function, location, or selector, found {}", other.ty().long_name()))), |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | /// A selector a method resolves to one location: `counter.at`, `state.at`. |
| 258 | fn locatable_arg(engine: &mut Engine, args: &mut Args) -> Outcome<Selector> { |
| 259 | let (at, v) = res!(take(engine, args, "selector")); |
| 260 | let sel = res!(select::cast(engine, at, v)); |
| 261 | res!(introspect::check_locatable(engine, at, &sel)); |
| 262 | Ok(sel) |
| 263 | } |
| 264 | |
| 265 | /// Fails outside a context that has a location, as Typst's `Context::introspect` does. |
| 266 | fn introspect_here(engine: &mut Engine, span: Span) -> Outcome<crate::eval::locate::Location> { |
| 267 | introspect::here(engine, span) |
| 268 | } |
| 269 | |
| 270 | fn counter_method(engine: &mut Engine, span: Span, f: IntroFn, c: &Counter, args: &mut Args) -> Outcome<Value> { |
| 271 | Ok(match f { |
| 272 | IntroFn::CounterGet => { |
| 273 | let loc = res!(introspect_here(engine, span)); |
| 274 | introspect::state_value(&res!(introspect::counter_at(engine, c, loc))) |
| 275 | } |
| 276 | IntroFn::CounterAt => { |
| 277 | let sel = res!(locatable_arg(engine, args)); |
| 278 | let loc = res!(introspect::resolve_unique(engine, span, &sel)); |
| 279 | introspect::state_value(&res!(introspect::counter_at(engine, c, loc))) |
| 280 | } |
| 281 | IntroFn::CounterFinal => { |
| 282 | res!(introspect_here(engine, span)); |
| 283 | introspect::state_value(&res!(introspect::counter_final(engine, c))) |
| 284 | } |
| 285 | IntroFn::CounterDisplay => { |
| 286 | let numbering = match res!(args.eat::<Value>()).map(Value::symbol_as_str) { |
| 287 | None | Some(Value::Auto) => None, |
| 288 | Some(v @ Value::Str(_)) | Some(v @ Value::Func(_)) => Some(v), |
| 289 | Some(other) => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 290 | "expected string, function, or auto, found {}", other.ty().long_name()))), |
| 291 | }; |
| 292 | let both = match res!(args.named::<Value>("both")) { |
| 293 | None => false, |
| 294 | Some(Value::Bool(b)) => b, |
| 295 | Some(other) => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 296 | "expected boolean, found {}", other.ty().long_name()))), |
| 297 | }; |
| 298 | // `at:` displays the counter somewhere else, one element the selector names. |
| 299 | let loc = match res!(args.named::<Value>("at")) { |
| 300 | None | Some(Value::Auto) => res!(introspect_here(engine, span)), |
| 301 | Some(v) => { |
| 302 | let sel = res!(select::cast(engine, span, v)); |
| 303 | res!(introspect::check_locatable(engine, span, &sel)); |
| 304 | res!(introspect::resolve_unique(engine, span, &sel)) |
| 305 | } |
| 306 | }; |
| 307 | let styles = engine.context.styles.clone(); |
| 308 | res!(introspect::counter_display(engine, c, numbering, both, false, loc, styles.as_ref())) |
| 309 | } |
| 310 | IntroFn::CounterStep => { |
| 311 | let level = match res!(args.named::<Value>("level")) { |
| 312 | None => 1, |
| 313 | Some(Value::Int(l)) if l >= 1 => l as usize, |
| 314 | Some(Value::Int(_)) => return Err(engine.error(DiagnosticKind::Type, span, "number must be positive")), |
| 315 | Some(other) => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 316 | "expected integer, found {}", other.ty().long_name()))), |
| 317 | }; |
| 318 | Value::Content(res!(counter_update(engine, span, c, CounterUpdate::Step(level)))) |
| 319 | } |
| 320 | IntroFn::CounterUpdate => { |
| 321 | let v = res!(expect(engine, args, "update")); |
| 322 | let update = match v { |
| 323 | Value::Func(f) => CounterUpdate::Func(f), |
| 324 | other => match introspect::counter_state(&other) { |
| 325 | Ok(s) => CounterUpdate::Set(s), |
| 326 | Err(_) => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 327 | "expected integer, array, or function, found {}", other.ty().long_name()))), |
| 328 | }, |
| 329 | }; |
| 330 | Value::Content(res!(counter_update(engine, span, c, update))) |
| 331 | } |
| 332 | other => return Err(engine.error(DiagnosticKind::Type, span, fmt!("type counter has no method `{}`", other.name()))), |
| 333 | }) |
| 334 | } |
| 335 | |
| 336 | fn counter_update(engine: &mut Engine, span: Span, c: &Counter, update: CounterUpdate) -> Outcome<Content> { |
| 337 | content::build(engine, ElemKind::CounterUpdate, vec![ |
| 338 | ("key", c.key.to_value()), |
| 339 | ("update", update.to_value()), |
| 340 | ], span) |
| 341 | } |
| 342 | |
| 343 | fn state_method(engine: &mut Engine, span: Span, f: IntroFn, s: &State, args: &mut Args) -> Outcome<Value> { |
| 344 | Ok(match f { |
| 345 | IntroFn::CounterGet | IntroFn::StateGet => { |
| 346 | let loc = res!(introspect_here(engine, span)); |
| 347 | res!(introspect::state_at(engine, s, loc)) |
| 348 | } |
| 349 | IntroFn::CounterAt | IntroFn::StateAt => { |
| 350 | let sel = res!(locatable_arg(engine, args)); |
| 351 | let loc = res!(introspect::resolve_unique(engine, span, &sel)); |
| 352 | res!(introspect::state_at(engine, s, loc)) |
| 353 | } |
| 354 | IntroFn::CounterFinal | IntroFn::StateFinal => { |
| 355 | res!(introspect_here(engine, span)); |
| 356 | res!(introspect::state_final(engine, s)) |
| 357 | } |
| 358 | IntroFn::CounterUpdate | IntroFn::StateUpdate => { |
| 359 | let v = res!(expect(engine, args, "update")); |
| 360 | Value::Content(res!(content::build(engine, ElemKind::StateUpdate, vec![ |
| 361 | ("key", Value::str(s.key.clone())), |
| 362 | ("update", v), |
| 363 | ], span))) |
| 364 | } |
| 365 | other => return Err(engine.error(DiagnosticKind::Type, span, fmt!("type state has no method `{}`", other.name()))), |
| 366 | }) |
| 367 | } |
| 368 | |
| 369 | fn location_method(engine: &mut Engine, span: Span, f: IntroFn, loc: crate::eval::locate::Location) -> Outcome<Value> { |
| 370 | // An unplaced location reads as the top of page one, as Typst's introspector answers. The page alone |
| 371 | // is asked for on its own, so it settles as soon as the page does. |
| 372 | Ok(match f { |
| 373 | IntroFn::LocationPage => Value::Int(res!(introspect::page(engine, loc)).unwrap_or(1) as i64), |
| 374 | IntroFn::LocationPosition => introspect::position_dict(res!(introspect::position(engine, loc)) |
| 375 | .unwrap_or(Position::new(1, Sp::ZERO, Sp::ZERO))), |
| 376 | IntroFn::LocationPageNumbering => res!(introspect::page_numbering(engine, loc)), |
| 377 | other => return Err(engine.error(DiagnosticKind::Type, span, fmt!("type location has no method `{}`", other.name()))), |
| 378 | }) |
| 379 | } |
| 380 | |
| 381 | /// `measure(content, width: auto, height: auto)`: the size the content takes, laid out under the |
| 382 | /// context's styles in a region as large as given, `auto` being unbounded. The layout is discarded, and |
| 383 | /// it runs [detached](introspect::detached), so measuring leaves no trace on the document's locations. |
| 384 | fn measure(engine: &mut Engine, span: Span, args: &mut Args) -> Outcome<Value> { |
| 385 | let body = match res!(expect(engine, args, "content")) { |
| 386 | Value::Content(c) => c, |
| 387 | other => res!(content::display(engine, other, span)), |
| 388 | }; |
| 389 | let width = res!(args.named::<Value>("width")); |
| 390 | let height = res!(args.named::<Value>("height")); |
| 391 | let styles = res!(introspect::context_styles(engine, span)); |
| 392 | let w = res!(extent(engine, span, width, &styles)); |
| 393 | let h = res!(extent(engine, span, height, &styles)); |
| 394 | let region = Region { width: w, height: h, base: (w, h), expand_x: false, expand_y: false }; |
| 395 | let dims = res!(introspect::detached(engine, |e| flow::measure(e, &body, &styles, region))); |
| 396 | let mut d = Dict::new(); |
| 397 | d.insert("width", Value::Length(Length::pt(dims.width.to_pt()))); |
| 398 | d.insert("height", Value::Length(Length::pt((dims.height + dims.depth).to_pt()))); |
| 399 | Ok(Value::dict(d)) |
| 400 | } |
| 401 | |
| 402 | fn extent(engine: &mut Engine, span: Span, v: Option<Value>, styles: &StyleChain) -> Outcome<Sp> { |
| 403 | match v { |
| 404 | None | Some(Value::Auto) => Ok(introspect::UNBOUNDED), |
| 405 | Some(Value::Length(l)) => Ok(Sp::from_pt(styles.resolve_length(l))), |
| 406 | Some(other) => Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 407 | "expected length or auto, found {}", other.ty().long_name()))), |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | pub fn construct(_engine: &mut Engine, _kind: ElemKind, _args: &mut Args) -> Outcome<Option<Content>> { |
| 412 | Ok(None) |
| 413 | } |
| 414 | |
| 415 | /// Metadata and the update elements show as nothing, only their tags marking where they sit; a |
| 416 | /// `context` element shows as its body's result; `layout` is flow's, which knows the region. |
| 417 | pub fn show(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> { |
| 418 | let kind = match elem.kind() { |
| 419 | Some(k) => k, |
| 420 | None => return Ok(None), |
| 421 | }; |
| 422 | match kind { |
| 423 | ElemKind::Metadata | ElemKind::CounterUpdate | ElemKind::StateUpdate => Ok(Some(Content::empty())), |
| 424 | ElemKind::Context => show_context(engine, elem, styles).map(Some), |
| 425 | _ => Ok(None), |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | fn show_context(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> { |
| 430 | let span = elem.span(); |
| 431 | let func = match elem.field("func") { |
| 432 | Some(Value::Func(f)) => f.clone(), |
| 433 | _ => return Err(engine.error(DiagnosticKind::Type, span, "context element has no function")), |
| 434 | }; |
| 435 | let saved = std::mem::replace(&mut engine.context, Context { |
| 436 | location: elem.location(), |
| 437 | styles: Some(styles.clone()), |
| 438 | }); |
| 439 | let mark = engine.diags.len(); |
| 440 | let result = engine.call_func(&func, Args::new(span)); |
| 441 | engine.context = saved; |
| 442 | // An error is delayed: its diagnostic stands, and the body shows as nothing this pass. |
| 443 | match result.and_then(|v| content::display(engine, v, span)) { |
| 444 | Ok(c) => Ok(c), |
| 445 | Err(e) => { |
| 446 | engine.adopt(mark, span, e); |
| 447 | Ok(Content::empty()) |
| 448 | } |
| 449 | } |
| 450 | } |