Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/eval.rs

87.0 KiB, 85 runs

created by r1870400018:63204, 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// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-eval, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4// U2 owns this file: the tree-walking evaluator. Its public surface is `eval_module`, `eval_string` and
5// `Engine::call_func`; the walker's own state (a VM with the scope chain and flow control) is private.
6//
7// The walker reads the concrete syntax tree directly, by kind and child order as typst-syntax 0.14/0.15
8// lays them out, and follows typst-eval's semantics and wording. Three behaviours a reader could not
9// guess from the types:
10//
11// * `set` and `show` style the *rest* of their markup or code block. The rest is gathered iteratively
12// and wrapped from the innermost rule outward, so a file with hundreds of rules does not recurse.
13// * `show: f` with no selector is applied at once to the rest of the block, as Typst does; it never
14// reaches the style chain.
15// * A closure captures by value the free names it mentions, at definition. Over-capturing a name that
16// a parameter later shadows is harmless, so the capture pass is a plain identifier scan.
17
18use crate::diag::{
19 Diagnostic,
20 DiagnosticKind,
21};
22use crate::eval::args::{
23 Arg,
24 Args,
25};
26use crate::eval::content::{
27 self,
28 Content,
29 ElemKind,
30};
31use crate::eval::func::{
32 Closure,
33 Func,
34 NativeFunc,
35 Param,
36};
37use crate::eval::import;
38use crate::eval::intro;
39use crate::eval::lib;
40use crate::eval::lib::foundations;
41use crate::eval::methods;
42use crate::eval::native_kind;
43use crate::eval::ops;
44use crate::eval::scope::{
45 Binding,
46 Scope,
47};
48use crate::eval::select::{
49 self,
50 Selector,
51};
52use crate::eval::styles::{
53 self,
54 Recipe,
55 Style,
56 Styles,
57 Transformation,
58};
59use crate::eval::value::{
60 Angle,
61 Dict,
62 Fraction,
63 Label,
64 Length,
65 Module,
66 Ratio,
67 Value,
68};
69use crate::eval::Engine;
70use crate::syntax::ast::{
71 self,
72 AstNode,
73 BareImportError,
74};
75use crate::syntax::{
76 parser,
77 FileId,
78 Span,
79 SyntaxKind,
80 SyntaxNode,
81};
82
83use oxedyne_fe2o3_core::prelude::*;
84use oxedyne_fe2o3_text::unicode::segment;
85
86use std::collections::{
87 HashMap,
88 HashSet,
89};
90use std::sync::Arc;
91
92mod math_call;
93
94const MAX_WHILE_ITERATIONS: usize = 10_000; // Typst's per-loop limit for `while`
95
96/// Which mode `eval(..)` parses its string in.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub enum EvalMode {
99 Markup,
100 Code,
101 Math,
102}
103
104thread_local! {
105 static LIBRARY: Arc<Scope> = Arc::new(lib::library());
106}
107
108/// The standard library scope, built once per thread and shared by every module and closure.
109pub fn library() -> Arc<Scope> {
110 LIBRARY.with(|l| l.clone())
111}
112
113/// The standard library a compile given `inputs` evaluates against: the shared one when there are none,
114/// else a copy whose `sys.inputs` holds them, as Typst's library is built with the inputs of its world.
115pub fn library_with_inputs(inputs: &[(String, String)]) -> Arc<Scope> {
116 let base = library();
117 if inputs.is_empty() {
118 return base;
119 }
120 let mut scope = (*base).clone();
121 scope.define("sys", Value::Module(Arc::new(lib::foundations::sys_module(inputs))));
122 Arc::new(scope)
123}
124
125/// Evaluates a loaded source: its top-level bindings become the module's scope, its markup (with every
126/// `set`/`show` applied to the rest of its scope) the module's content.
127pub fn eval_module(engine: &mut Engine, id: FileId) -> Outcome<Module> {
128 let (root, path) = match engine.world.source(id) {
129 Some(s) => (s.root.clone(), s.path.clone()),
130 None => return Err(err!("No source with id {} is loaded.", id.0; Missing, Input)),
131 };
132 if report_syntax_errors(engine, &root, None) {
133 return Err(err!("{} does not parse.", path.display(); Input, Invalid));
134 }
135 let lib = engine.world.library.clone();
136 let (content, frame) = {
137 let mut vm = Vm::new(engine, &lib, lib.clone(), id, false, Span::detached());
138 let content = res!(vm.eval_markup(root.children()));
139 res!(vm.forbid_flow());
140 (content, vm.frames.pop().unwrap_or_default())
141 };
142 let name = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
143 let mut module = Module::new(name, Scope { map: frame, parent: None });
144 module.content = content;
145 Ok(module)
146}
147
148/// `eval(text, mode:, scope:)`: evaluates a string against the standard library plus `scope`.
149pub fn eval_string(
150 engine: &mut Engine,
151 text: &str,
152 mode: EvalMode,
153 scope: Scope,
154 span: Span,
155)
156 -> Outcome<Value>
157{
158 let root = match mode {
159 EvalMode::Markup => parser::parse(text, FileId::DETACHED),
160 EvalMode::Code => parser::parse_code(text, FileId::DETACHED),
161 EvalMode::Math => parser::parse_math(text, FileId::DETACHED),
162 };
163 if report_syntax_errors(engine, &root, Some(span)) {
164 return Err(err!("The string passed to eval does not parse."; Input, Invalid));
165 }
166 let lib = engine.world.library.clone();
167 let base = Scope { map: scope.map, parent: Some(lib.clone()) };
168 // The string's own nodes have no file; a path in it resolves from the file that called `eval`.
169 let mut vm = Vm::new(engine, &base, lib.clone(), span.file, false, span);
170 let out = match mode {
171 EvalMode::Markup => Value::Content(res!(vm.eval_markup(root.children()))),
172 EvalMode::Code => res!(vm.eval_code(root.children())),
173 EvalMode::Math => {
174 let body = res!(vm.eval_math_seq(root.children()));
175 Value::Content(res!(vm.elem(ElemKind::Equation, vec![
176 ("block", Value::Bool(false)),
177 ("body", Value::Content(body)),
178 ], span)))
179 }
180 };
181 res!(vm.forbid_flow());
182 Ok(out)
183}
184
185// Every syntax error becomes a diagnostic; `at` replaces a detached position (a string given to `eval`).
186fn report_syntax_errors(engine: &mut Engine, root: &SyntaxNode, at: Option<Span>) -> bool {
187 let errors = root.errors();
188 for (span, e) in &errors {
189 let span = match at {
190 Some(s) if span.is_detached() => s,
191 _ => *span,
192 };
193 let mut d = Diagnostic::error(DiagnosticKind::Syntax, span, e.message.clone());
194 for h in &e.hints {
195 d = d.with_hint(h.clone());
196 }
197 engine.diags.push(d);
198 }
199 !errors.is_empty()
200}
201
202impl Engine {
203 /// Calls any function value: native, element constructor, closure or `.with`. The one call path
204 /// realisation (show-rule closures), the library (`array.map`) and flow (`layout`) all use.
205 pub fn call_func(&mut self, func: &Func, args: Args) -> Outcome<Value> {
206 let span = args.span;
207 let mark = self.diags.len();
208 let out = match func {
209 Func::Native(n) => n.call(self, args),
210 Func::Element(k) => {
211 let mut args = args;
212 content::construct(self, *k, &mut args).map(Value::Content)
213 }
214 Func::Closure(c) => {
215 let out = call_closure(self, c, func, args);
216 if out.is_err() {
217 let name = c.name().unwrap_or("closure").to_string();
218 for d in self.diags[mark..].iter_mut() {
219 if d.is_error() {
220 d.trace.push((span, fmt!("while calling `{}`", name)));
221 }
222 }
223 }
224 out
225 }
226 Func::With(w) => {
227 let mut all = w.1.clone();
228 all.span = span;
229 all.items.extend(args.items);
230 self.call_func(&w.0, all)
231 }
232 #[cfg(feature = "plugin")]
233 Func::Plugin(p) => lib::foundations::call_plugin(self, p, args),
234 };
235 match out {
236 Ok(v) => Ok(v),
237 Err(e) => Err(self.adopt(mark, span, e)),
238 }
239 }
240
241 /// An error raised without a diagnostic (a native function's `err!`) gets one at `span`; an error
242 /// that already recorded its own is passed on untouched.
243 pub fn adopt(&mut self, mark: usize, span: Span, e: Error<ErrTag>) -> Error<ErrTag> {
244 let recorded = self.diags.get(mark..).map(|ds| ds.iter().any(|d| d.is_error())).unwrap_or(false);
245 if !recorded {
246 self.diags.push(Diagnostic::error(native_kind(&e), span, e.plain()));
247 }
248 e
249 }
250}
251
252fn call_closure(engine: &mut Engine, c: &Arc<Closure>, func: &Func, args: Args) -> Outcome<Value> {
253 res!(engine.enter_call(args.span));
254 let lib = engine.world.library.clone();
255 let out = {
256 let mut vm = Vm::new(engine, c.captured(), lib, c.span().file, true, Span::detached());
257 if let Some(name) = c.name() {
258 vm.define(name, Value::Func(func.clone()), c.span());
259 }
260 match vm.bind_params(c.params(), args) {
261 Ok(()) => vm.eval_closure_body(c.body()),
262 Err(e) => Err(e),
263 }
264 };
265 engine.exit_call();
266 out
267}
268
269// The evaluator
270
271#[derive(Clone, Debug)]
272enum Flow {
273 Break(Span),
274 Continue(Span),
275 Return(Span, Option<Value>, bool), // the value, and whether an `if` or a loop lies between
276}
277
278// A style that applies to the rest of a block once the rest is known.
279enum Pending {
280 Styles(Styles),
281 Recipe(Recipe),
282}
283
284#[derive(Clone, Copy, PartialEq, Eq)]
285enum Bind {
286 Define,
287 Assign,
288}
289
290enum Step {
291 Key(String, Span),
292 At(Value, Span, Span), // the key, where it stands and where the access does
293 First(Span), // `.first()`, an accessor as `.at()` is
294 Last(Span),
295}
296
297type Frame = HashMap<String, Binding>;
298
299struct Vm<'a> {
300 engine: &'a mut Engine,
301 base: &'a Scope, // the library, a closure's captures, or `eval`'s scope over the library
302 lib: Arc<Scope>, // the parent of every capture scope
303 frames: Vec<Frame>, // block scopes, innermost last
304 flow: Option<Flow>,
305 file: FileId,
306 in_func: bool, // running a closure body, so `base` holds captures
307 fallback: Span, // where a detached span reports (the `eval` call)
308}
309
310fn is_expr(k: SyntaxKind) -> bool {
311 use SyntaxKind as K;
312 matches!(k,
313 K::Text | K::Space | K::Linebreak | K::Parbreak | K::Escape | K::Shorthand | K::SmartQuote
314 | K::Strong | K::Emph | K::Raw | K::Link | K::Label | K::Ref | K::Heading | K::ListItem
315 | K::EnumItem | K::TermItem | K::Equation | K::Math | K::MathText | K::MathIdent
316 | K::MathShorthand | K::MathAlignPoint | K::MathDelimited | K::MathAttach | K::MathPrimes
317 | K::MathFrac | K::MathRoot | K::MathCall | K::MathFieldAccess | K::Ident | K::None | K::Auto | K::Bool | K::Int | K::Float
318 | K::Numeric | K::Str | K::CodeBlock | K::ContentBlock | K::Parenthesized | K::Array | K::Dict
319 | K::Unary | K::Binary | K::FieldAccess | K::FuncCall | K::Closure | K::LetBinding | K::SetRule
320 | K::ShowRule | K::Contextual | K::Conditional | K::WhileLoop | K::ForLoop | K::ModuleImport
321 | K::ModuleInclude | K::LoopBreak | K::LoopContinue | K::FuncReturn | K::DestructAssignment)
322}
323
324// A code expression: trivia, punctuation and keywords are not.
325fn is_code_expr(k: SyntaxKind) -> bool {
326 is_expr(k) && !matches!(k, SyntaxKind::Space | SyntaxKind::Parbreak)
327}
328
329// What a `let`, `for` or destructuring assignment binds to: an expression, `_`, or a pattern.
330fn is_pattern(k: SyntaxKind) -> bool {
331 is_code_expr(k) || matches!(k, SyntaxKind::Destructuring | SyntaxKind::Underscore)
332}
333
334fn pattern_after(n: &SyntaxNode, k: SyntaxKind) -> Option<&SyntaxNode> {
335 n.children().iter().skip_while(|c| c.kind() != k).skip(1).find(|c| is_pattern(c.kind()))
336}
337
338fn code_exprs(n: &SyntaxNode) -> Vec<&SyntaxNode> {
339 n.children().iter().filter(|c| is_code_expr(c.kind())).collect()
340}
341
342// The expression following the first child of kind `k`.
343fn expr_after(n: &SyntaxNode, k: SyntaxKind) -> Option<&SyntaxNode> {
344 n.children().iter().skip_while(|c| c.kind() != k).skip(1).find(|c| is_code_expr(c.kind()))
345}
346
347fn last_expr(n: &SyntaxNode) -> Option<&SyntaxNode> {
348 n.children().iter().rev().find(|c| is_code_expr(c.kind()))
349}
350
351fn first_expr(n: &SyntaxNode) -> Option<&SyntaxNode> {
352 n.children().iter().find(|c| is_code_expr(c.kind()))
353}
354
355fn ident_text(n: &SyntaxNode) -> Option<&str> {
356 n.children().iter().rev().find(|c| c.kind() == SyntaxKind::Ident).map(|c| c.text())
357}
358
359// Is the callee a name that math mode resolved, so a non-function callee displays with its arguments?
360fn in_math(n: &SyntaxNode) -> bool {
361 match n.kind() {
362 SyntaxKind::MathIdent => true,
363 SyntaxKind::FieldAccess => first_expr(n).map(in_math).unwrap_or(false),
364 _ => false,
365 }
366}
367
368// The names a closure body mentions as variables. The field of a field access and the key of a named
369// argument are not variables, so `it.body` does not capture a `body` of the enclosing function: a closure's
370// fingerprint holds what it captured, and the whole document in a captured `body` would move the location
371// of every context that mentions the word, whatever was typed anywhere in the document.
372fn collect_idents(n: &SyntaxNode, out: &mut HashSet<String>) {
373 match n.kind() {
374 SyntaxKind::Ident | SyntaxKind::MathIdent => { out.insert(n.text().to_string()); }
375 SyntaxKind::FieldAccess => if let Some(t) = first_expr(n) {
376 collect_idents(t, out);
377 },
378 SyntaxKind::Named => {
379 let mut key = true;
380 for c in n.children() {
381 if key && c.kind() == SyntaxKind::Ident {
382 key = false;
383 continue;
384 }
385 collect_idents(c, out);
386 }
387 },
388 _ => for c in n.children() {
389 collect_idents(c, out);
390 },
391 }
392}
393
394fn is_invariant(n: &SyntaxNode) -> bool {
395 match n.kind() {
396 SyntaxKind::Ident | SyntaxKind::MathIdent => false,
397 SyntaxKind::FieldAccess => first_expr(n).map(is_invariant).unwrap_or(true),
398 SyntaxKind::FuncCall => n.children().iter().all(is_invariant),
399 _ => n.children().iter().all(is_invariant),
400 }
401}
402
403fn can_diverge(n: &SyntaxNode) -> bool {
404 matches!(n.kind(), SyntaxKind::Break | SyntaxKind::Return) || n.children().iter().any(can_diverge)
405}
406
407fn unescape_markup(esc: &str) -> String {
408 match esc.strip_prefix("\\u{").and_then(|s| s.strip_suffix('}')) {
409 Some(hex) => u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)
410 .map(|c| c.to_string()).unwrap_or_else(|| esc.to_string()),
411 None => esc.chars().nth(1).map(|c| c.to_string()).unwrap_or_default(),
412 }
413}
414
415fn markup_shorthand(s: &str) -> &str {
416 match s {
417 "~" => "\u{a0}",
418 "-?" => "\u{ad}",
419 "--" => "\u{2013}",
420 "---" => "\u{2014}",
421 "..." => "\u{2026}",
422 "-" => "\u{2212}",
423 other => other,
424 }
425}
426
427fn math_shorthand(s: &str) -> &str {
428 match s {
429 "..." => "\u{2026}",
430 "-" => "\u{2212}",
431 "*" => "\u{2217}",
432 "~" => "\u{223c}",
433 "!=" => "\u{2260}",
434 ":=" => "\u{2254}",
435 "::=" => "\u{2a74}",
436 "=:" => "\u{2255}",
437 "<<" => "\u{226a}",
438 "<<<" => "\u{22d8}",
439 ">>" => "\u{226b}",
440 ">>>" => "\u{22d9}",
441 "<=" => "\u{2264}",
442 ">=" => "\u{2265}",
443 "->" => "\u{2192}",
444 "-->" => "\u{27f6}",
445 "|->" => "\u{21a6}",
446 ">->" => "\u{21a3}",
447 "->>" => "\u{21a0}",
448 "<-" => "\u{2190}",
449 "<--" => "\u{27f5}",
450 "<-<" => "\u{21a2}",
451 "<<-" => "\u{219e}",
452 "<->" => "\u{2194}",
453 "<-->" => "\u{27f7}",
454 "~>" => "\u{21dd}",
455 "~~>" => "\u{27ff}",
456 "<~" => "\u{21dc}",
457 "<~~" => "\u{2b33}",
458 "=>" => "\u{21d2}",
459 "|=>" => "\u{2907}",
460 "==>" => "\u{27f9}",
461 "<==" => "\u{27f8}",
462 "<=>" => "\u{21d4}",
463 "<==>" => "\u{27fa}",
464 "[|" => "\u{27e6}",
465 "|]" => "\u{27e7}",
466 "||" => "\u{2016}",
467 other => other,
468 }
469}
470
471/// A name a function value carries as a scope member: `list.item`, `assert.eq`, `str.from-unicode`.
472pub fn func_field(f: &Func, name: &str) -> Option<Func> {
473 match f {
474 Func::Element(k) => match k.scoped(name) {
475 Some(e) => Some(Func::Element(e)),
476 None => lib::visual::scoped(*k, name).map(|v| Func::Native(NativeFunc::Visual(v))),
477 },
478 Func::Native(n) => match foundations::func_scope(f, name) {
479 Some(Value::Func(g)) => Some(g),
480 _ => foundations::constructed_type(*n)
481 .and_then(|t| methods::type_method(t, name)).map(Func::Native),
482 },
483 Func::With(w) => func_field(&w.0, name),
484 Func::Closure(_) => None,
485 #[cfg(feature = "plugin")]
486 Func::Plugin(_) => None,
487 }
488}
489
490// Walks a place to the value it names. The error carries a span, message and optional hint.
491fn slot<'b>(
492 frames: &'b mut [Frame],
493 base: &Scope,
494 in_func: bool,
495 root: &str,
496 root_span: Span,
497 steps: &[Step],
498 create_last: bool,
499)
500 -> std::result::Result<&'b mut Value, (Span, String, Option<String>)>
501{
502 let mut cur = match frames.iter_mut().rev().find_map(|f| f.get_mut(root)) {
503 Some(b) => &mut b.value,
504 None => {
505 let msg = if in_func && base.map.contains_key(root) {
506 "variables from outside the function are read-only and cannot be modified".to_string()
507 } else if base.get(root).is_some() {
508 fmt!("cannot mutate a constant: {}", root)
509 } else {
510 fmt!("unknown variable: {}", root)
511 };
512 return Err((root_span, msg, None));
513 }
514 };
515 let n = steps.len();
516 for (i, step) in steps.iter().enumerate() {
517 match step {
518 Step::Key(k, sp) => {
519 let ty = cur.ty();
520 match cur {
521 Value::Dict(d) => {
522 let d = Arc::make_mut(d);
523 if create_last && i + 1 == n && !d.contains(k) {
524 d.insert(k, Value::None);
525 }
526 cur = match d.get_mut(k) {
527 Some(v) => v,
528 None => return Err((*sp, fmt!("dictionary does not contain key \"{}\"", k), None)),
529 };
530 }
531 Value::Symbol(_) | Value::Content(_) | Value::Module(_) | Value::Func(_) => return Err((*sp,
532 fmt!("cannot mutate fields on {}", ty.long_name()), None)),
533 Value::Length(_) | Value::Relative(_) | Value::Alignment(_) | Value::Stroke(_)
534 | Value::Version(_) => return Err((*sp,
535 fmt!("fields on {} are not yet mutable", ty.long_name()),
536 Some(fmt!("try creating a new {} with the updated field value instead", ty.long_name())))),
537 _ => return Err((*sp, fmt!("{} does not have accessible fields", ty.long_name()), None)),
538 }
539 }
540 Step::First(sp) | Step::Last(sp) => {
541 let ty = cur.ty();
542 match cur {
543 Value::Array(a) => {
544 let a = Arc::make_mut(a);
545 let end = if matches!(step, Step::First(_)) { a.first_mut() } else { a.last_mut() };
546 cur = match end {
547 Some(v) => v,
548 None => return Err((*sp, "array is empty".to_string(), None)),
549 };
550 }
551 _ => return Err((*sp, fmt!("cannot mutate a temporary value of type {}", ty.long_name()), None)),
552 }
553 }
554 Step::At(key, key_sp, sp) => {
555 let ty = cur.ty();
556 match (cur, key) {
557 (Value::Array(a), Value::Int(i)) => {
558 let a = Arc::make_mut(a);
559 let len = a.len();
560 let idx = if *i < 0 { len as i64 + i } else { *i };
561 if idx < 0 || idx >= len as i64 {
562 return Err((*sp, fmt!("array index out of bounds (index: {}, len: {})", i, len), None));
563 }
564 cur = match a.get_mut(idx as usize) {
565 Some(v) => v,
566 None => return Err((*sp, "array index out of bounds".to_string(), None)),
567 };
568 }
569 (Value::Dict(d), key) => {
570 let k = match key.str_cast() {
571 Some(k) => k,
572 None => return Err((*key_sp,
573 fmt!("expected string, found {}", key.ty().long_name()), None)),
574 };
575 let d = Arc::make_mut(d);
576 cur = match d.get_mut(&k) {
577 Some(v) => v,
578 None => return Err((*sp, fmt!("dictionary does not contain key \"{}\"", k),
579 Some("use `insert` to add or update values".to_string()))),
580 };
581 }
582 (Value::Array(_), other) => return Err((*key_sp,
583 fmt!("expected integer, found {}", other.ty().long_name()), None)),
584 _ => return Err((*sp, fmt!("cannot mutate a temporary value of type {}", ty.long_name()), None)),
585 }
586 }
587 }
588 }
589 Ok(cur)
590}
591
592impl<'a> Vm<'a> {
593 fn new(
594 engine: &'a mut Engine,
595 base: &'a Scope,
596 lib: Arc<Scope>,
597 file: FileId,
598 in_func: bool,
599 fallback: Span,
600 )
601 -> Self
602 {
603 Self { engine, base, lib, frames: vec![Frame::new()], flow: None, file, in_func, fallback }
604 }
605
606 fn fix(&self, span: Span) -> Span {
607 if span.is_detached() { self.fallback } else { span }
608 }
609
610 fn error<S: Into<String>>(&mut self, kind: DiagnosticKind, span: Span, msg: S) -> Error<ErrTag> {
611 let span = self.fix(span);
612 self.engine.error(kind, span, msg)
613 }
614
615 fn error_hint<S: Into<String>, H: Into<String>>(
616 &mut self,
617 kind: DiagnosticKind,
618 span: Span,
619 msg: S,
620 hint: H,
621 )
622 -> Error<ErrTag>
623 {
624 let span = self.fix(span);
625 self.engine.error_hint(kind, span, msg, hint)
626 }
627
628 fn warn<S: Into<String>>(&mut self, kind: DiagnosticKind, span: Span, msg: S) {
629 let span = self.fix(span);
630 self.engine.warn(kind, span, msg);
631 }
632
633 // A library error (an operator, a cast) reported at the expression that caused it.
634 fn fail(&mut self, span: Span, e: Error<ErrTag>) -> Error<ErrTag> {
635 let msg = e.plain();
636 self.error(native_kind(&e), span, msg)
637 }
638
639 fn define(&mut self, name: &str, value: Value, span: Span) {
640 if let Some(f) = self.frames.last_mut() {
641 f.insert(name.to_string(), Binding { value, span });
642 }
643 }
644
645 fn lookup(&self, name: &str) -> Option<&Value> {
646 for f in self.frames.iter().rev() {
647 if let Some(b) = f.get(name) {
648 return Some(&b.value);
649 }
650 }
651 self.base.get(name)
652 }
653
654 // A name bound above the library: a local, a capture, or `eval`'s scope.
655 fn lookup_local(&self, name: &str) -> Option<&Value> {
656 for f in self.frames.iter().rev() {
657 if let Some(b) = f.get(name) {
658 return Some(&b.value);
659 }
660 }
661 let mut s = self.base;
662 while let Some(parent) = &s.parent {
663 if let Some(b) = s.map.get(name) {
664 return Some(&b.value);
665 }
666 s = parent;
667 }
668 None
669 }
670
671 // Maths resolves free names in the `math` module rather than the global library.
672 fn lookup_math(&self, name: &str) -> Option<Value> {
673 if let Some(v) = self.lookup_local(name) {
674 return Some(v.clone());
675 }
676 match self.lib.get("math") {
677 Some(Value::Module(m)) => m.scope.get(name).cloned(),
678 _ => None,
679 }
680 }
681
682 fn capture(&self, node: &SyntaxNode) -> Scope {
683 let mut names = HashSet::new();
684 collect_idents(node, &mut names);
685 let mut map = HashMap::new();
686 for n in names {
687 if let Some(v) = self.lookup_local(&n) {
688 map.insert(n, Binding { value: v.clone(), span: Span::detached() });
689 }
690 }
691 Scope { map, parent: Some(self.lib.clone()) }
692 }
693
694 fn forbid_flow(&mut self) -> Outcome<()> {
695 match self.flow.take() {
696 None => Ok(()),
697 Some(Flow::Break(s)) => Err(self.error(DiagnosticKind::Syntax, s, "cannot break outside of loop")),
698 Some(Flow::Continue(s)) => Err(self.error(DiagnosticKind::Syntax, s, "cannot continue outside of loop")),
699 Some(Flow::Return(s, _, _)) => Err(self.error(DiagnosticKind::Syntax, s, "cannot return outside of function")),
700 }
701 }
702
703 fn elem(&mut self, kind: ElemKind, fields: Vec<(&str, Value)>, span: Span) -> Outcome<Content> {
704 content::build(self.engine, kind, fields, span)
705 }
706
707 fn display(&mut self, v: Value, span: Span) -> Outcome<Content> {
708 content::display(self.engine, v, span)
709 }
710
711 fn expect_bool(&mut self, node: &SyntaxNode) -> Outcome<bool> {
712 match res!(self.eval(node)) {
713 Value::Bool(b) => Ok(b),
714 other => Err(self.error(DiagnosticKind::Type, node.span(), fmt!("expected boolean, found {}", other.ty().long_name()))),
715 }
716 }
717
718 // Blocks
719
720 fn eval_markup(&mut self, nodes: &[SyntaxNode]) -> Outcome<Content> {
721 let outer = self.flow.take();
722 let mut stack: Vec<(Vec<Content>, Pending)> = Vec::new();
723 let mut seq: Vec<Content> = Vec::new();
724 for node in nodes {
725 match node.kind() {
726 SyntaxKind::SetRule => {
727 let styles = res!(self.eval_set(node));
728 if self.flow.is_some() {
729 break;
730 }
731 stack.push((std::mem::take(&mut seq), Pending::Styles(styles)));
732 }
733 SyntaxKind::ShowRule => {
734 let recipe = res!(self.eval_show(node));
735 if self.flow.is_some() {
736 break;
737 }
738 stack.push((std::mem::take(&mut seq), Pending::Recipe(recipe)));
739 }
740 k if is_expr(k) => match res!(self.eval(node)) {
741 Value::Label(label) => self.attach_label(&mut seq, label, node.span()),
742 v => {
743 let c = res!(self.display(v, node.span()));
744 seq.push(c);
745 }
746 },
747 _ => (),
748 }
749 if self.flow.is_some() {
750 break;
751 }
752 }
753 let mut content = Content::sequence(seq);
754 while let Some((mut prev, pending)) = stack.pop() {
755 let tail = res!(self.apply_pending(content, pending));
756 prev.push(tail);
757 content = Content::sequence(prev);
758 }
759 if outer.is_some() {
760 self.flow = outer;
761 }
762 Ok(content)
763 }
764
765 fn attach_label(&mut self, seq: &mut [Content], label: Label, span: Span) {
766 match seq.iter_mut().rev().find(|c| !ops::unlabellable(c)) {
767 Some(c) => {
768 if c.label().is_some() {
769 self.warn(DiagnosticKind::Lint, c.span(), "content labelled multiple times");
770 }
771 *c = std::mem::take(c).labelled(label);
772 }
773 None => self.warn(DiagnosticKind::Lint, span, fmt!("label `<{}>` is not attached to anything", label.as_str())),
774 }
775 }
776
777 fn eval_code(&mut self, nodes: &[SyntaxNode]) -> Outcome<Value> {
778 let outer = self.flow.take();
779 let mut stack: Vec<(Value, Span, Pending)> = Vec::new();
780 let mut output = Value::None;
781 for node in nodes {
782 let span = node.span();
783 match node.kind() {
784 SyntaxKind::SetRule => {
785 let styles = res!(self.eval_set(node));
786 if self.flow.is_some() {
787 break;
788 }
789 stack.push((std::mem::take(&mut output), span, Pending::Styles(styles)));
790 }
791 SyntaxKind::ShowRule => {
792 let recipe = res!(self.eval_show(node));
793 if self.flow.is_some() {
794 break;
795 }
796 stack.push((std::mem::take(&mut output), span, Pending::Recipe(recipe)));
797 }
798 k if is_code_expr(k) => {
799 let v = res!(self.eval(node));
800 output = match ops::join(output, v) {
801 Ok(v) => v,
802 Err(e) => return Err(self.fail(span, e)),
803 };
804 }
805 _ => (),
806 }
807 if self.flow.is_some() {
808 self.warn_discarded(&output);
809 break;
810 }
811 }
812 while let Some((prev, span, pending)) = stack.pop() {
813 let tail = res!(self.display(output, span));
814 let styled = res!(self.apply_pending(tail, pending));
815 output = match ops::join(prev, Value::Content(styled)) {
816 Ok(v) => v,
817 Err(e) => return Err(self.fail(span, e)),
818 };
819 }
820 if outer.is_some() {
821 self.flow = outer;
822 }
823 Ok(output)
824 }
825
826 fn apply_pending(&mut self, content: Content, pending: Pending) -> Outcome<Content> {
827 match pending {
828 Pending::Styles(s) => Ok(content.styled(s)),
829 Pending::Recipe(r) => styles::styled_with_recipe(self.engine, content, r),
830 }
831 }
832
833 fn scoped<T>(&mut self, f: impl FnOnce(&mut Self) -> Outcome<T>) -> Outcome<T> {
834 self.frames.push(Frame::new());
835 let out = f(self);
836 self.frames.pop();
837 out
838 }
839
840 // Expressions
841
842 fn eval(&mut self, node: &SyntaxNode) -> Outcome<Value> {
843 use SyntaxKind as K;
844 let span = node.span();
845 match node.kind() {
846 // Markup
847 K::Text => Ok(Value::Content(Content::text(node.text()).with_span(span))),
848 K::Space => Ok(Value::Content(Content::marker(ElemKind::Space, span))),
849 K::Linebreak => Ok(Value::Content(Content::marker(ElemKind::Linebreak, span))),
850 K::Parbreak => Ok(Value::Content(Content::marker(ElemKind::Parbreak, span))),
851 K::Escape => Ok(Value::Content(Content::symbol(&unescape_markup(node.text())).with_span(span))),
852 K::Shorthand => Ok(Value::Content(Content::symbol(markup_shorthand(node.text())).with_span(span))),
853 K::SmartQuote => self.elem(ElemKind::SmartQuote, vec![
854 ("double", Value::Bool(node.text() == "\"")),
855 ], span).map(Value::Content),
856 K::Strong => self.eval_body_elem(node, ElemKind::Strong),
857 K::Emph => self.eval_body_elem(node, ElemKind::Emph),
858 K::Raw => self.eval_raw(node),
859 K::Link => self.eval_link(node),
860 K::Label => {
861 let t = node.text();
862 let name = t.strip_prefix('<').and_then(|s| s.strip_suffix('>')).unwrap_or(t);
863 Ok(Value::Label(Label::new(name)))
864 }
865 K::Ref => self.eval_ref(node),
866 K::Heading => self.eval_heading(node),
867 K::ListItem => self.eval_body_elem(node, ElemKind::ListItem),
868 K::EnumItem => self.eval_enum_item(node),
869 K::TermItem => self.eval_term_item(node),
870 K::Equation => self.eval_equation(node),
871 K::Markup => self.eval_markup(node.children()).map(Value::Content),
872 // Maths
873 K::Math => self.eval_math_seq(node.children()).map(Value::Content),
874 // One character is a symbol, a number is text, as Typst's `MathText` evaluates.
875 K::MathText => Ok(Value::Content(match node.text().chars().next() {
876 Some(c) if c.is_numeric() => Content::text(node.text()),
877 _ => Content::symbol(node.text()),
878 }.with_span(span))),
879 K::MathIdent => self.eval_math_ident(node),
880 K::MathShorthand => Ok(Value::Content(Content::symbol(math_shorthand(node.text())).with_span(span))),
881 K::MathAlignPoint => Ok(Value::Content(Content::marker(ElemKind::MathAlignPoint, span))),
882 K::MathDelimited => self.eval_math_delimited(node),
883 K::MathAttach => self.eval_math_attach(node),
884 K::MathPrimes => {
885 // One leaf holds every prime of a run, so its length is the count.
886 let n = ast::MathPrimes::from_untyped(node).map(|p| p.count()).unwrap_or(1);
887 self.elem(ElemKind::MathPrimes, vec![("count", Value::Int(n as i64))], span).map(Value::Content)
888 }
889 K::MathFrac => self.eval_math_frac(node),
890 K::MathRoot => self.eval_math_root(node),
891 K::MathCall => self.eval_math_call(node),
892 K::MathFieldAccess => self.eval_math_field_access(node),
893 // Literals
894 K::Ident => match self.lookup(node.text()) {
895 Some(v) => Ok(v.clone()),
896 None => Err(self.error(DiagnosticKind::UnknownVariable, span, fmt!("unknown variable: {}", node.text()))),
897 },
898 K::None => Ok(Value::None),
899 K::Auto => Ok(Value::Auto),
900 K::Bool => Ok(Value::Bool(node.text() == "true")),
901 K::Int => self.eval_int(node),
902 K::Float => match node.text().parse::<f64>() {
903 Ok(f) => Ok(Value::Float(f)),
904 Err(_) => Err(self.error(DiagnosticKind::Syntax, span, fmt!("invalid floating point number: {}", node.text()))),
905 },
906 K::Numeric => self.eval_numeric(node),
907 K::Str => Ok(Value::str(ast::unescape_str(node.text()))),
908 // Code
909 K::Code => self.eval_code(node.children()),
910 K::CodeBlock => match node.child(K::Code) {
911 Some(code) => {
912 let code = code.clone();
913 self.scoped(|vm| vm.eval_code(code.children()))
914 }
915 None => {
916 let kids: Vec<SyntaxNode> = node.children().to_vec();
917 self.scoped(|vm| vm.eval_code(&kids))
918 }
919 },
920 K::ContentBlock => {
921 let kids: Vec<SyntaxNode> = match node.child(K::Markup) {
922 Some(m) => m.children().to_vec(),
923 None => Vec::new(),
924 };
925 self.scoped(|vm| vm.eval_markup(&kids)).map(Value::Content)
926 }
927 K::Parenthesized => match first_expr(node) {
928 Some(e) => self.eval(e),
929 None => Ok(Value::None),
930 },
931 K::Array => self.eval_array(node),
932 K::Dict => self.eval_dict(node),
933 K::Unary => self.eval_unary(node),
934 K::Binary => self.eval_binary(node),
935 K::FieldAccess => {
936 let target = match first_expr(node) {
937 Some(t) => t,
938 None => return Err(self.error(DiagnosticKind::Syntax, span, "field access without a target")),
939 };
940 let tv = res!(self.eval(target));
941 let name = ident_text(node).unwrap_or("");
942 // An error in the access is Typst's at the field's name, not at the whole expression.
943 let at = node.children().iter().rev().find(|c| c.kind() == SyntaxKind::Ident)
944 .map(|c| c.span()).unwrap_or(span);
945 self.field(tv, name, at)
946 }
947 K::FuncCall => self.eval_call(node),
948 K::Closure => self.eval_closure(node, None),
949 K::LetBinding => self.eval_let(node),
950 K::SetRule => self.eval_set(node).map(Value::Styles),
951 K::ShowRule => {
952 // A show rule outside a block's statement list: its styles, for `show: set ..` nesting.
953 let r = res!(self.eval_show(node));
954 Ok(Value::Styles(Styles::from_style(Style::Recipe(Arc::new(r)))))
955 }
956 K::Contextual => self.eval_context(node),
957 K::Conditional => self.eval_if(node),
958 K::WhileLoop => self.eval_while(node),
959 K::ForLoop => self.eval_for(node),
960 K::ModuleImport => self.eval_import(node),
961 K::ModuleInclude => self.eval_include(node),
962 K::LoopBreak => {
963 if self.flow.is_none() {
964 self.flow = Some(Flow::Break(span));
965 }
966 Ok(Value::None)
967 }
968 K::LoopContinue => {
969 if self.flow.is_none() {
970 self.flow = Some(Flow::Continue(span));
971 }
972 Ok(Value::None)
973 }
974 K::FuncReturn => {
975 let v = match first_expr(node) {
976 Some(e) => Some(res!(self.eval(e))),
977 None => None,
978 };
979 if self.flow.is_none() {
980 self.flow = Some(Flow::Return(span, v, false));
981 }
982 Ok(Value::None)
983 }
984 K::DestructAssignment => {
985 let pat = node.children().iter().find(|c| is_pattern(c.kind())).cloned();
986 let val = last_expr(node).cloned();
987 match (pat, val) {
988 (Some(p), Some(v)) => {
989 let value = res!(self.eval(&v));
990 res!(self.destructure(&p, value, Bind::Assign));
991 Ok(Value::None)
992 }
993 _ => Err(self.error(DiagnosticKind::Syntax, span, "incomplete destructuring assignment")),
994 }
995 }
996 K::Error => Err(self.error(DiagnosticKind::Syntax, span, node.error_info()
997 .map(|e| e.message.clone()).unwrap_or_else(|| "syntax error".to_string()))),
998 other => Err(self.error(DiagnosticKind::Syntax, span, fmt!("expected expression, found {}", other.name()))),
999 }
1000 }
1001
1002 fn eval_int(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1003 let t = node.text();
1004 let (digits, radix) = if let Some(h) = t.strip_prefix("0x") {
1005 (h, 16)
1006 } else if let Some(o) = t.strip_prefix("0o") {
1007 (o, 8)
1008 } else if let Some(b) = t.strip_prefix("0b") {
1009 (b, 2)
1010 } else {
1011 (t, 10)
1012 };
1013 match i64::from_str_radix(digits, radix) {
1014 Ok(i) => Ok(Value::Int(i)),
1015 Err(_) if radix == 10 => match t.parse::<f64>() {
1016 Ok(f) => Ok(Value::Float(f)),
1017 Err(_) => Err(self.error(DiagnosticKind::Syntax, node.span(), fmt!("invalid integer: {}", t))),
1018 },
1019 Err(_) => Err(self.error(DiagnosticKind::Syntax, node.span(), "integer number is too large")),
1020 }
1021 }
1022
1023 fn eval_numeric(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1024 let t = node.text();
1025 let split = t.char_indices().rev()
1026 .take_while(|(_, c)| c.is_ascii_alphabetic() || *c == '%')
1027 .last().map(|(i, _)| i).unwrap_or(t.len());
1028 let (n, unit) = t.split_at(split);
1029 let v = match n.parse::<f64>() {
1030 Ok(v) => v,
1031 Err(_) => return Err(self.error(DiagnosticKind::Syntax, node.span(), fmt!("invalid number: {}", t))),
1032 };
1033 Ok(match unit {
1034 "pt" => Value::Length(Length::pt(v)),
1035 "mm" => Value::Length(Length::pt(v * 72.0 / 25.4)),
1036 "cm" => Value::Length(Length::pt(v * 72.0 / 2.54)),
1037 "in" => Value::Length(Length::pt(v * 72.0)),
1038 "em" => Value::Length(Length::em(v)),
1039 "deg" => Value::Angle(Angle(v.to_radians())),
1040 "rad" => Value::Angle(Angle(v)),
1041 "fr" => Value::Fraction(Fraction(v)),
1042 "%" => Value::Ratio(Ratio(v / 100.0)),
1043 other => return Err(self.error(DiagnosticKind::Syntax, node.span(), fmt!("invalid unit: {}", other))),
1044 })
1045 }
1046
1047 fn eval_body_elem(&mut self, node: &SyntaxNode, kind: ElemKind) -> Outcome<Value> {
1048 let body = match node.child(SyntaxKind::Markup) {
1049 Some(m) => res!(self.eval_markup(m.children())),
1050 None => Content::empty(),
1051 };
1052 self.elem(kind, vec![("body", Value::Content(body))], node.span()).map(Value::Content)
1053 }
1054
1055 fn eval_raw(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1056 let lines: Vec<&str> = node.children().iter()
1057 .filter(|c| c.kind() == SyntaxKind::Text).map(|c| c.text()).collect();
1058 let delim = node.child(SyntaxKind::RawDelim).map(|d| d.text().len()).unwrap_or(1);
1059 let block = delim >= 3 && node.children().iter()
1060 .any(|c| c.kind() == SyntaxKind::RawTrimmed && c.text().contains(['\n', '\r']));
1061 let mut fields = vec![
1062 ("text", Value::str(lines.join("\n"))),
1063 ("block", Value::Bool(block)),
1064 ];
1065 if let Some(lang) = node.child(SyntaxKind::RawLang) {
1066 fields.push(("lang", Value::str(lang.text())));
1067 }
1068 self.elem(ElemKind::Raw, fields, node.span()).map(Value::Content)
1069 }
1070
1071 fn eval_link(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1072 let url = node.text();
1073 let shown = url.strip_prefix("mailto:").or_else(|| url.strip_prefix("tel:")).unwrap_or(url);
1074 let body = Content::text(shown).with_span(node.span());
1075 self.elem(ElemKind::Link, vec![
1076 ("dest", Value::str(url)),
1077 ("body", Value::Content(body)),
1078 ], node.span()).map(Value::Content)
1079 }
1080
1081 fn eval_ref(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1082 let marker = node.child(SyntaxKind::RefMarker).map(|m| m.text()).unwrap_or("");
1083 let target = marker.strip_prefix('@').unwrap_or(marker);
1084 let mut fields = vec![("target", Value::Label(Label::new(target)))];
1085 if let Some(block) = node.child(SyntaxKind::ContentBlock) {
1086 let block = block.clone();
1087 fields.push(("supplement", res!(self.eval(&block))));
1088 }
1089 self.elem(ElemKind::Ref, fields, node.span()).map(Value::Content)
1090 }
1091
1092 fn eval_heading(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1093 let depth = node.child(SyntaxKind::HeadingMarker).map(|m| m.text().len()).unwrap_or(1).max(1);
1094 let body = match node.child(SyntaxKind::Markup) {
1095 Some(m) => res!(self.eval_markup(m.children())),
1096 None => Content::empty(),
1097 };
1098 self.elem(ElemKind::Heading, vec![
1099 ("depth", Value::Int(depth as i64)),
1100 ("body", Value::Content(body)),
1101 ], node.span()).map(Value::Content)
1102 }
1103
1104 fn eval_enum_item(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1105 let number = node.child(SyntaxKind::EnumMarker)
1106 .and_then(|m| m.text().trim_end_matches('.').parse::<i64>().ok());
1107 let body = match node.child(SyntaxKind::Markup) {
1108 Some(m) => res!(self.eval_markup(m.children())),
1109 None => Content::empty(),
1110 };
1111 let mut fields = Vec::new();
1112 if let Some(n) = number {
1113 fields.push(("number", Value::Int(n)));
1114 }
1115 fields.push(("body", Value::Content(body)));
1116 self.elem(ElemKind::EnumItem, fields, node.span()).map(Value::Content)
1117 }
1118
1119 fn eval_term_item(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1120 let parts: Vec<SyntaxNode> = node.children().iter()
1121 .filter(|c| c.kind() == SyntaxKind::Markup).cloned().collect();
1122 let term = match parts.first() {
1123 Some(m) => res!(self.eval_markup(m.children())),
1124 None => Content::empty(),
1125 };
1126 let desc = match parts.get(1) {
1127 Some(m) => res!(self.eval_markup(m.children())),
1128 None => Content::empty(),
1129 };
1130 self.elem(ElemKind::TermItem, vec![
1131 ("term", Value::Content(term)),
1132 ("description", Value::Content(desc)),
1133 ], node.span()).map(Value::Content)
1134 }
1135
1136 // Maths
1137
1138 fn eval_equation(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1139 let kids = node.children();
1140 let spaced = |n: Option<&SyntaxNode>| n.map(|c| c.kind() == SyntaxKind::Space).unwrap_or(false);
1141 let block = kids.len() >= 2 && spaced(kids.get(1)) && spaced(kids.get(kids.len() - 2));
1142 let body = match node.child(SyntaxKind::Math) {
1143 Some(m) => res!(self.eval_math_seq(m.children())),
1144 None => Content::empty(),
1145 };
1146 self.elem(ElemKind::Equation, vec![
1147 ("block", Value::Bool(block)),
1148 ("body", Value::Content(body)),
1149 ], node.span()).map(Value::Content)
1150 }
1151
1152 fn eval_math_seq(&mut self, nodes: &[SyntaxNode]) -> Outcome<Content> {
1153 let mut seq = Vec::new();
1154 for n in nodes {
1155 if n.kind() == SyntaxKind::Hash || !is_expr(n.kind()) {
1156 continue;
1157 }
1158 let v = res!(self.eval(n));
1159 seq.push(res!(self.display(v, n.span())));
1160 }
1161 Ok(Content::sequence(seq))
1162 }
1163
1164 fn eval_math_ident(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1165 let name = node.text();
1166 match self.lookup_math(name) {
1167 Some(v) => Ok(v),
1168 None if name.chars().count() > 1 && name.chars().all(char::is_alphabetic) => {
1169 let spaced: Vec<String> = name.chars().map(|c| c.to_string()).collect();
1170 Err(self.error_hint(DiagnosticKind::UnknownVariable, node.span(), fmt!("unknown variable: {}", name), fmt!(
1171 "if you meant to display multiple letters as is, try adding spaces between each letter: `{}`",
1172 spaced.join(" "))))
1173 }
1174 None => Err(self.error(DiagnosticKind::UnknownVariable, node.span(), fmt!("unknown variable: {}", name))),
1175 }
1176 }
1177
1178 // A script or fraction operand drops the parentheses that only group it: `x^(a+b)`.
1179 fn eval_math_operand(&mut self, node: &SyntaxNode) -> Outcome<Content> {
1180 if node.kind() == SyntaxKind::MathDelimited {
1181 let kids = node.children();
1182 let open = kids.first().map(|c| c.text());
1183 let close = kids.last().map(|c| c.text());
1184 if open == Some("(") && close == Some(")") {
1185 return match node.child(SyntaxKind::Math) {
1186 Some(m) => self.eval_math_seq(m.children()),
1187 None => Ok(Content::empty()),
1188 };
1189 }
1190 }
1191 let v = res!(self.eval(node));
1192 self.display(v, node.span())
1193 }
1194
1195 fn eval_math_delimited(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1196 let kids = node.children();
1197 let mut body = Content::empty();
1198 if let Some(open) = kids.first() {
1199 if open.kind() != SyntaxKind::Math {
1200 let v = res!(self.eval(open));
1201 body = ops::content_add(body, res!(self.display(v, open.span())));
1202 }
1203 }
1204 if let Some(m) = node.child(SyntaxKind::Math) {
1205 let inner = res!(self.eval_math_seq(m.children()));
1206 body = ops::content_add(body, inner);
1207 }
1208 if kids.len() > 1 {
1209 if let Some(close) = kids.last() {
1210 if close.kind() != SyntaxKind::Math {
1211 let v = res!(self.eval(close));
1212 body = ops::content_add(body, res!(self.display(v, close.span())));
1213 }
1214 }
1215 }
1216 self.elem(ElemKind::MathLr, vec![("body", Value::Content(body))], node.span()).map(Value::Content)
1217 }
1218
1219 fn eval_math_attach(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1220 let kids = node.children();
1221 let base = match kids.first() {
1222 Some(b) => {
1223 let v = res!(self.eval(b));
1224 res!(self.display(v, b.span()))
1225 }
1226 None => Content::empty(),
1227 };
1228 let mut fields = vec![("base", Value::Content(base))];
1229 let mut i = 1;
1230 while i < kids.len() {
1231 match kids[i].kind() {
1232 SyntaxKind::Hat | SyntaxKind::Underscore => {
1233 let name = if kids[i].kind() == SyntaxKind::Hat { "t" } else { "b" };
1234 if let Some(operand) = kids[i + 1..].iter().find(|c| is_expr(c.kind()) && c.kind() != SyntaxKind::Space) {
1235 let c = res!(self.eval_math_operand(operand));
1236 fields.push((name, Value::Content(c)));
1237 }
1238 i += 2;
1239 }
1240 SyntaxKind::MathPrimes => {
1241 let p = kids[i].clone();
1242 fields.push(("tr", res!(self.eval(&p))));
1243 i += 1;
1244 }
1245 _ => i += 1,
1246 }
1247 }
1248 self.elem(ElemKind::MathAttach, fields, node.span()).map(Value::Content)
1249 }
1250
1251 fn eval_math_frac(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1252 let parts: Vec<SyntaxNode> = node.children().iter()
1253 .filter(|c| is_expr(c.kind()) && c.kind() != SyntaxKind::Space).cloned().collect();
1254 let (num, denom) = match (parts.first(), parts.last()) {
1255 (Some(n), Some(d)) if parts.len() >= 2 => (n.clone(), d.clone()),
1256 _ => return Err(self.error(DiagnosticKind::Syntax, node.span(), "incomplete fraction")),
1257 };
1258 let num = res!(self.eval_math_operand(&num));
1259 let denom = res!(self.eval_math_operand(&denom));
1260 self.elem(ElemKind::MathFrac, vec![
1261 ("num", Value::Content(num)),
1262 ("denom", Value::Content(denom)),
1263 ], node.span()).map(Value::Content)
1264 }
1265
1266 fn eval_math_root(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1267 let index = match node.child(SyntaxKind::Root).map(|r| r.text()) {
1268 Some("\u{221b}") => Some("3"),
1269 Some("\u{221c}") => Some("4"),
1270 _ => None,
1271 };
1272 let radicand = match node.children().iter().rev().find(|c| is_expr(c.kind()) && c.kind() != SyntaxKind::Space) {
1273 Some(r) => {
1274 let r = r.clone();
1275 res!(self.eval_math_operand(&r))
1276 }
1277 None => Content::empty(),
1278 };
1279 let mut fields = Vec::new();
1280 if let Some(i) = index {
1281 fields.push(("index", Value::Content(Content::text(i))));
1282 }
1283 fields.push(("radicand", Value::Content(radicand)));
1284 self.elem(ElemKind::MathRoot, fields, node.span()).map(Value::Content)
1285 }
1286
1287 // Collections and operators
1288
1289 fn eval_array(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1290 let mut out = Vec::new();
1291 for c in node.children() {
1292 match c.kind() {
1293 SyntaxKind::Spread => {
1294 let e = match last_expr(c) {
1295 Some(e) => e.clone(),
1296 None => continue,
1297 };
1298 match res!(self.eval(&e)) {
1299 Value::None => (),
1300 Value::Array(a) => out.extend(a.iter().cloned()),
1301 Value::Dict(_) => return Err(self.error_hint(DiagnosticKind::Type, c.span(),
1302 "cannot spread dictionary into array",
1303 fmt!("add a colon to create a dictionary instead: `(: {},)`", c.full_text().trim()))),
1304 other => return Err(self.error(DiagnosticKind::Type, c.span(),
1305 fmt!("cannot spread {} into array", other.ty().long_name()))),
1306 }
1307 }
1308 k if is_code_expr(k) => out.push(res!(self.eval(c))),
1309 _ => (),
1310 }
1311 }
1312 Ok(Value::array(out))
1313 }
1314
1315 fn eval_dict(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1316 let mut d = Dict::new();
1317 for c in node.children() {
1318 match c.kind() {
1319 SyntaxKind::Named => {
1320 let name = c.children().iter().find(|x| x.kind() == SyntaxKind::Ident)
1321 .map(|x| x.text().to_string()).unwrap_or_default();
1322 let e = match last_expr(c) {
1323 Some(e) => e.clone(),
1324 None => continue,
1325 };
1326 let v = res!(self.eval(&e));
1327 d.insert(&name, v);
1328 }
1329 SyntaxKind::Keyed => {
1330 let (k, e) = match (first_expr(c), last_expr(c)) {
1331 (Some(k), Some(e)) => (k.clone(), e.clone()),
1332 _ => continue,
1333 };
1334 let kv = res!(self.eval(&k));
1335 let key = match kv.str_cast() {
1336 Some(s) => s,
1337 None => return Err(self.error(DiagnosticKind::Type, k.span(),
1338 fmt!("expected string, found {}", kv.ty().long_name()))),
1339 };
1340 let v = res!(self.eval(&e));
1341 d.insert(&key, v);
1342 }
1343 SyntaxKind::Spread => {
1344 let e = match last_expr(c) {
1345 Some(e) => e.clone(),
1346 None => continue,
1347 };
1348 match res!(self.eval(&e)) {
1349 Value::None => (),
1350 Value::Dict(x) => for (k, v) in x.iter() {
1351 d.insert(k, v.clone());
1352 },
1353 other => return Err(self.error(DiagnosticKind::Type, c.span(),
1354 fmt!("cannot spread {} into dictionary", other.ty().long_name()))),
1355 }
1356 }
1357 _ => (),
1358 }
1359 }
1360 Ok(Value::dict(d))
1361 }
1362
1363 fn eval_unary(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1364 let op = node.children().iter().find(|c| !c.kind().is_trivia()).map(|c| c.kind());
1365 let operand = match last_expr(node) {
1366 Some(e) => e,
1367 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "missing operand")),
1368 };
1369 let v = res!(self.eval(operand));
1370 let out = match op {
1371 Some(SyntaxKind::Plus) => ops::pos(v),
1372 Some(SyntaxKind::Minus) => ops::neg(v),
1373 _ => ops::not(v),
1374 };
1375 match out {
1376 Ok(v) => Ok(v),
1377 Err(e) => Err(self.fail(node.span(), e)),
1378 }
1379 }
1380
1381 fn eval_binary(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1382 use SyntaxKind as K;
1383 let sig: Vec<&SyntaxNode> = node.significant().collect();
1384 let (lhs, rhs) = match (sig.first(), sig.last()) {
1385 (Some(l), Some(r)) if sig.len() >= 3 => (*l, *r),
1386 _ => return Err(self.error(DiagnosticKind::Syntax, node.span(), "incomplete binary expression")),
1387 };
1388 let op = match (sig.get(1).map(|n| n.kind()), sig.get(2).map(|n| n.kind())) {
1389 (Some(K::Not), Some(K::In)) => None,
1390 (Some(k), _) => Some(k),
1391 _ => None,
1392 };
1393 let span = node.span();
1394 match op {
1395 Some(K::Eq) => return self.assign_op(lhs, rhs, None),
1396 Some(K::PlusEq) => return self.assign_op(lhs, rhs, Some(ops::add)),
1397 Some(K::HyphEq) => return self.assign_op(lhs, rhs, Some(ops::sub)),
1398 Some(K::StarEq) => return self.assign_op(lhs, rhs, Some(ops::mul)),
1399 Some(K::SlashEq) => return self.assign_op(lhs, rhs, Some(ops::div)),
1400 Some(K::And) => {
1401 let a = res!(self.eval(lhs));
1402 if matches!(a, Value::Bool(false)) {
1403 return Ok(a);
1404 }
1405 let b = res!(self.eval(rhs));
1406 return match ops::and(a, b) {
1407 Ok(v) => Ok(v),
1408 Err(e) => Err(self.fail(span, e)),
1409 };
1410 }
1411 Some(K::Or) => {
1412 let a = res!(self.eval(lhs));
1413 if matches!(a, Value::Bool(true)) {
1414 return Ok(a);
1415 }
1416 let b = res!(self.eval(rhs));
1417 return match ops::or(a, b) {
1418 Ok(v) => Ok(v),
1419 Err(e) => Err(self.fail(span, e)),
1420 };
1421 }
1422 _ => (),
1423 }
1424 let a = res!(self.eval(lhs));
1425 let b = res!(self.eval(rhs));
1426 let out = match op {
1427 Some(K::Plus) => ops::add(a, b),
1428 Some(K::Minus) => ops::sub(a, b),
1429 Some(K::Star) => ops::mul(a, b),
1430 Some(K::Slash) => ops::div(a, b),
1431 Some(K::EqEq) => Ok(Value::Bool(ops::equal(&a, &b))),
1432 Some(K::ExclEq) => Ok(Value::Bool(!ops::equal(&a, &b))),
1433 Some(K::Lt) => ops::compare(&a, &b).map(|o| Value::Bool(o.is_lt())),
1434 Some(K::LtEq) => ops::compare(&a, &b).map(|o| Value::Bool(o.is_le())),
1435 Some(K::Gt) => ops::compare(&a, &b).map(|o| Value::Bool(o.is_gt())),
1436 Some(K::GtEq) => ops::compare(&a, &b).map(|o| Value::Bool(o.is_ge())),
1437 Some(K::In) => ops::contains(&a, &b).map(Value::Bool),
1438 None => ops::contains(&a, &b).map(|c| Value::Bool(!c)),
1439 Some(other) => return Err(self.error(DiagnosticKind::Syntax, span, fmt!("unknown operator {}", other.name()))),
1440 };
1441 match out {
1442 Ok(v) => Ok(v),
1443 Err(e) => Err(self.fail(span, e)),
1444 }
1445 }
1446
1447 // Places and assignment
1448
1449 fn place(&mut self, node: &SyntaxNode) -> Outcome<(String, Span, Vec<Step>)> {
1450 match node.kind() {
1451 SyntaxKind::Ident => Ok((node.text().to_string(), node.span(), Vec::new())),
1452 SyntaxKind::Parenthesized => match first_expr(node) {
1453 Some(e) => {
1454 let e = e.clone();
1455 self.place(&e)
1456 }
1457 None => Err(self.error(DiagnosticKind::Syntax, node.span(), "cannot mutate a temporary value")),
1458 },
1459 SyntaxKind::FieldAccess => {
1460 let target = match first_expr(node) {
1461 Some(t) => t.clone(),
1462 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "cannot mutate a temporary value")),
1463 };
1464 let name = ident_text(node).unwrap_or("").to_string();
1465 let (root, rs, mut steps) = res!(self.place(&target));
1466 steps.push(Step::Key(name, node.span()));
1467 Ok((root, rs, steps))
1468 }
1469 SyntaxKind::FuncCall => {
1470 let callee = first_expr(node).cloned();
1471 if let Some(c) = callee {
1472 // `first` and `last` are accessors beside `at`: `ctx.groups.last().push(n)` changes the array in place.
1473 let edge = if c.kind() == SyntaxKind::FieldAccess { ident_text(&c) } else { None };
1474 if matches!(edge, Some("first") | Some("last")) {
1475 let args = res!(self.eval_args(node.child(SyntaxKind::Args), node.span()));
1476 if !args.items.is_empty() {
1477 return Err(self.error(DiagnosticKind::Type, node.span(), "unexpected argument"));
1478 }
1479 let target = match first_expr(&c) {
1480 Some(t) => t.clone(),
1481 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "cannot mutate a temporary value")),
1482 };
1483 let (root, rs, mut steps) = res!(self.place(&target));
1484 steps.push(if edge == Some("first") { Step::First(node.span()) } else { Step::Last(node.span()) });
1485 return Ok((root, rs, steps));
1486 }
1487 if c.kind() == SyntaxKind::FieldAccess && ident_text(&c) == Some("at") {
1488 let mut args = res!(self.eval_args(node.child(SyntaxKind::Args), node.span()));
1489 let (key, key_sp) = match args.items.iter().position(|a| a.name.is_none()) {
1490 Some(i) => {
1491 let a = args.items.remove(i);
1492 (a.value, a.value_span)
1493 }
1494 None => return Err(self.error(DiagnosticKind::Type, node.span(), "missing argument: index")),
1495 };
1496 let target = match first_expr(&c) {
1497 Some(t) => t.clone(),
1498 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "cannot mutate a temporary value")),
1499 };
1500 let (root, rs, mut steps) = res!(self.place(&target));
1501 steps.push(Step::At(key, key_sp, node.span()));
1502 return Ok((root, rs, steps));
1503 }
1504 }
1505 res!(self.eval(node));
1506 Err(self.error(DiagnosticKind::Syntax, node.span(), "cannot mutate a temporary value"))
1507 }
1508 _ => {
1509 res!(self.eval(node));
1510 Err(self.error(DiagnosticKind::Syntax, node.span(), "cannot mutate a temporary value"))
1511 }
1512 }
1513 }
1514
1515 fn place_error(&mut self, e: (Span, String, Option<String>)) -> Error<ErrTag> {
1516 match e.2 {
1517 Some(h) => self.error_hint(DiagnosticKind::Type, e.0, e.1, h),
1518 None => self.error(DiagnosticKind::Type, e.0, e.1),
1519 }
1520 }
1521
1522 // Reads the value at a place.
1523 fn read_place(&mut self, root: &str, rs: Span, steps: &[Step]) -> Outcome<Value> {
1524 let got = match slot(&mut self.frames, self.base, self.in_func, root, rs, steps, false) {
1525 Ok(v) => Ok(v.clone()),
1526 Err(e) => Err(e),
1527 };
1528 match got {
1529 Ok(v) => Ok(v),
1530 Err(e) => Err(self.place_error(e)),
1531 }
1532 }
1533
1534 fn write_place(&mut self, root: &str, rs: Span, steps: &[Step], v: Value, create: bool) -> Outcome<()> {
1535 let got = match slot(&mut self.frames, self.base, self.in_func, root, rs, steps, create) {
1536 Ok(s) => {
1537 *s = v;
1538 Ok(())
1539 }
1540 Err(e) => Err(e),
1541 };
1542 match got {
1543 Ok(()) => Ok(()),
1544 Err(e) => Err(self.place_error(e)),
1545 }
1546 }
1547
1548 fn assign_op(
1549 &mut self,
1550 lhs: &SyntaxNode,
1551 rhs: &SyntaxNode,
1552 op: Option<fn(Value, Value) -> Outcome<Value>>,
1553 )
1554 -> Outcome<Value>
1555 {
1556 let r = res!(self.eval(rhs));
1557 let (root, rs, steps) = res!(self.place(lhs));
1558 match op {
1559 None => {
1560 // `d.key = v` may create the key; every other place must exist.
1561 let create = matches!(steps.last(), Some(Step::Key(..)));
1562 res!(self.write_place(&root, rs, &steps, r, create));
1563 }
1564 Some(f) => {
1565 let old = res!(self.read_place(&root, rs, &steps));
1566 let span = lhs.span().join(rhs.span());
1567 let new = match f(old, r) {
1568 Ok(v) => v,
1569 Err(e) => return Err(self.fail(span, e)),
1570 };
1571 res!(self.write_place(&root, rs, &steps, new, false));
1572 }
1573 }
1574 Ok(Value::None)
1575 }
1576
1577 // Bindings and patterns
1578
1579 fn eval_let(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1580 let pattern = match pattern_after(node, SyntaxKind::Let) {
1581 Some(p) => p.clone(),
1582 None => return Ok(Value::None),
1583 };
1584 if pattern.kind() == SyntaxKind::Closure {
1585 if let Some(name) = pattern.children().iter().find(|c| c.kind() == SyntaxKind::Ident) {
1586 let name = name.text().to_string();
1587 let f = res!(self.eval_closure(&pattern, Some(name.clone())));
1588 self.define(&name, f, pattern.span());
1589 return Ok(Value::None);
1590 }
1591 }
1592 let init = match expr_after(node, SyntaxKind::Eq) {
1593 Some(e) => {
1594 let e = e.clone();
1595 res!(self.eval(&e))
1596 }
1597 None => Value::None,
1598 };
1599 if self.flow.is_some() {
1600 return Ok(Value::None);
1601 }
1602 res!(self.destructure(&pattern, init, Bind::Define));
1603 Ok(Value::None)
1604 }
1605
1606 fn destructure(&mut self, pat: &SyntaxNode, v: Value, mode: Bind) -> Outcome<()> {
1607 match pat.kind() {
1608 SyntaxKind::Underscore => Ok(()),
1609 // The inner pattern may itself be a destructuring, which is no expression: `((a, b))`.
1610 SyntaxKind::Parenthesized => match pat.children().iter().find(|c| is_pattern(c.kind())) {
1611 Some(inner) => {
1612 let inner = inner.clone();
1613 self.destructure(&inner, v, mode)
1614 }
1615 None => Ok(()),
1616 },
1617 SyntaxKind::Destructuring => match v {
1618 Value::Array(a) => self.destructure_array(pat, &a, mode),
1619 Value::Dict(d) => self.destructure_dict(pat, &d, mode),
1620 other => Err(self.error(DiagnosticKind::Type, pat.span(), fmt!("cannot destructure {}", other.ty().long_name()))),
1621 },
1622 SyntaxKind::Ident if mode == Bind::Define => {
1623 self.define(pat.text(), v, pat.span());
1624 Ok(())
1625 }
1626 _ if mode == Bind::Assign => {
1627 let (root, rs, steps) = res!(self.place(pat));
1628 let create = matches!(steps.last(), Some(Step::Key(..)));
1629 self.write_place(&root, rs, &steps, v, create)
1630 }
1631 _ => Err(self.error(DiagnosticKind::Syntax, pat.span(), "cannot assign to this expression")),
1632 }
1633 }
1634
1635 fn pattern_items(pat: &SyntaxNode) -> Vec<SyntaxNode> {
1636 pat.children().iter().filter(|c| {
1637 matches!(c.kind(), SyntaxKind::Named | SyntaxKind::Spread) || is_pattern(c.kind())
1638 }).cloned().collect()
1639 }
1640
1641 fn wrong_count(&mut self, pat: &SyntaxNode, items: &[SyntaxNode], len: usize) -> Error<ErrTag> {
1642 let count = items.iter().filter(|i| !matches!(i.kind(), SyntaxKind::Spread | SyntaxKind::Named)).count();
1643 let spread = items.iter().any(|i| i.kind() == SyntaxKind::Spread);
1644 let quantifier = if len > count { "too many" } else { "not enough" };
1645 let expected = match (spread, count) {
1646 (true, 1) => "at least 1 element".to_string(),
1647 (true, c) => fmt!("at least {} elements", c),
1648 (false, 0) => "an empty array".to_string(),
1649 (false, 1) => "a single element".to_string(),
1650 (false, c) => fmt!("{} elements", c),
1651 };
1652 self.error_hint(DiagnosticKind::Type, pat.span(), fmt!("{} elements to destructure", quantifier), fmt!(
1653 "the provided array has a length of {}, but the pattern expects {}", len, expected))
1654 }
1655
1656 fn destructure_array(&mut self, pat: &SyntaxNode, a: &[Value], mode: Bind) -> Outcome<()> {
1657 let items = Self::pattern_items(pat);
1658 let len = a.len();
1659 let mut i = 0;
1660 for item in &items {
1661 match item.kind() {
1662 SyntaxKind::Spread => {
1663 let size = (1 + len).checked_sub(items.len());
1664 let sink = size.and_then(|s| a.get(i..i + s));
1665 let (size, sink) = match (size, sink) {
1666 (Some(s), Some(k)) => (s, k.to_vec()),
1667 _ => return Err(self.wrong_count(pat, &items, len)),
1668 };
1669 if let Some(target) = item.children().iter().rev().find(|c| is_pattern(c.kind())) {
1670 let target = target.clone();
1671 res!(self.destructure(&target, Value::array(sink), mode));
1672 }
1673 i += size;
1674 }
1675 SyntaxKind::Named => {
1676 return Err(self.error(DiagnosticKind::Type, item.span(), "cannot destructure named pattern from an array"));
1677 }
1678 _ => {
1679 let v = match a.get(i) {
1680 Some(v) => v.clone(),
1681 None => return Err(self.wrong_count(pat, &items, len)),
1682 };
1683 res!(self.destructure(item, v, mode));
1684 i += 1;
1685 }
1686 }
1687 }
1688 if i < len {
1689 return Err(self.wrong_count(pat, &items, len));
1690 }
1691 Ok(())
1692 }
1693
1694 fn destructure_dict(&mut self, pat: &SyntaxNode, d: &Dict, mode: Bind) -> Outcome<()> {
1695 let items = Self::pattern_items(pat);
1696 let mut used: HashSet<String> = HashSet::new();
1697 let mut sink: Option<Option<SyntaxNode>> = None;
1698 for item in &items {
1699 match item.kind() {
1700 SyntaxKind::Ident => {
1701 let name = item.text();
1702 let v = match d.get(name) {
1703 Some(v) => v.clone(),
1704 None => return Err(self.error(DiagnosticKind::Type, item.span(),
1705 fmt!("dictionary does not contain key \"{}\"", name))),
1706 };
1707 res!(self.destructure(item, v, mode));
1708 used.insert(name.to_string());
1709 }
1710 SyntaxKind::Named => {
1711 let key = match item.children().iter().find(|c| c.kind() == SyntaxKind::Ident) {
1712 Some(k) => k.clone(),
1713 None => continue,
1714 };
1715 let v = match d.get(key.text()) {
1716 Some(v) => v.clone(),
1717 None => return Err(self.error(DiagnosticKind::Type, key.span(),
1718 fmt!("dictionary does not contain key \"{}\"", key.text()))),
1719 };
1720 let sub = item.children().iter().rev().find(|c| is_pattern(c.kind())).cloned();
1721 if let Some(sub) = sub {
1722 res!(self.destructure(&sub, v, mode));
1723 }
1724 used.insert(key.text().to_string());
1725 }
1726 SyntaxKind::Spread => sink = Some(item.children().iter().rev()
1727 .find(|c| is_pattern(c.kind())).cloned()),
1728 _ => return Err(self.error(DiagnosticKind::Type, item.span(), "cannot destructure unnamed pattern from dictionary")),
1729 }
1730 }
1731 if let Some(Some(target)) = sink {
1732 let mut rest = Dict::new();
1733 for (k, v) in d.iter() {
1734 if !used.contains(k) {
1735 rest.insert(k, v.clone());
1736 }
1737 }
1738 res!(self.destructure(&target, Value::dict(rest), mode));
1739 }
1740 Ok(())
1741 }
1742
1743 // Functions
1744
1745 fn eval_closure(&mut self, node: &SyntaxNode, name: Option<String>) -> Outcome<Value> {
1746 let mut params = Vec::new();
1747 if let Some(ps) = node.child(SyntaxKind::Params) {
1748 let ps = ps.clone();
1749 for p in ps.children() {
1750 match p.kind() {
1751 SyntaxKind::Ident | SyntaxKind::Underscore | SyntaxKind::Destructuring
1752 | SyntaxKind::Parenthesized => params.push(Param::Pos(p.clone())),
1753 SyntaxKind::Named => {
1754 let pname = p.children().iter().find(|c| c.kind() == SyntaxKind::Ident)
1755 .map(|c| c.text().to_string()).unwrap_or_default();
1756 let default = match last_expr(p) {
1757 Some(e) => res!(self.eval(e)),
1758 None => Value::None,
1759 };
1760 params.push(Param::Named { name: pname, default });
1761 }
1762 SyntaxKind::Spread => params.push(Param::Sink(
1763 p.children().iter().find(|c| c.kind() == SyntaxKind::Ident).map(|c| c.text().to_string()))),
1764 _ => (),
1765 }
1766 }
1767 }
1768 let body = match node.children().iter().skip_while(|c| !matches!(c.kind(), SyntaxKind::Arrow | SyntaxKind::Eq))
1769 .skip(1).find(|c| is_code_expr(c.kind()))
1770 {
1771 Some(b) => b.clone(),
1772 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "closure has no body")),
1773 };
1774 let captured = self.capture(node);
1775 Ok(Value::Func(Func::Closure(Arc::new(Closure::new(name, params, body, captured, node.span())))))
1776 }
1777
1778 fn bind_params(&mut self, params: &[Param], mut args: Args) -> Outcome<()> {
1779 let span = args.span;
1780 let num_pos = params.iter().filter(|p| matches!(p, Param::Pos(_))).count();
1781 let sink_size = args.pos_count().checked_sub(num_pos);
1782 let mut sink: Option<(Option<String>, Vec<Arg>)> = None;
1783 for p in params {
1784 match p {
1785 Param::Pos(pat) => {
1786 let v = match args.items.iter().position(|a| a.name.is_none()) {
1787 Some(i) => args.items.remove(i).value,
1788 None => {
1789 let what = if pat.kind() == SyntaxKind::Ident { pat.text() } else { "pattern parameter" };
1790 return Err(self.error(DiagnosticKind::Type, span, fmt!("missing argument: {}", what)));
1791 }
1792 };
1793 res!(self.destructure(pat, v, Bind::Define));
1794 }
1795 Param::Named { name, default } => {
1796 let v = match res!(args.named::<Value>(name)) {
1797 Some(v) => v,
1798 None => default.clone(),
1799 };
1800 self.define(name, v, span);
1801 }
1802 Param::Sink(n) => {
1803 let mut taken = Vec::new();
1804 if let Some(k) = sink_size {
1805 for _ in 0..k {
1806 match args.items.iter().position(|a| a.name.is_none()) {
1807 Some(i) => taken.push(args.items.remove(i)),
1808 None => break,
1809 }
1810 }
1811 }
1812 sink = Some((n.clone(), taken));
1813 }
1814 }
1815 }
1816 if let Some((name, pos)) = sink {
1817 let mut rest = args.take();
1818 rest.items.extend(pos);
1819 if let Some(n) = name {
1820 self.define(&n, Value::Args(Arc::new(rest)), span);
1821 }
1822 }
1823 match args.items.first() {
1824 None => Ok(()),
1825 Some(Arg { name: Some(n), .. }) => {
1826 let msg = fmt!("unexpected argument: {}", n);
1827 Err(self.error(DiagnosticKind::Type, span, msg))
1828 }
1829 Some(_) => Err(self.error(DiagnosticKind::Type, span, "unexpected argument")),
1830 }
1831 }
1832
1833 fn eval_closure_body(&mut self, body: &SyntaxNode) -> Outcome<Value> {
1834 let out = res!(self.eval(body));
1835 match self.flow.take() {
1836 None => Ok(out),
1837 Some(Flow::Return(_, Some(v), _)) => Ok(v),
1838 Some(Flow::Return(_, None, _)) => Ok(out),
1839 Some(Flow::Break(s)) => Err(self.error(DiagnosticKind::Syntax, s, "cannot break outside of loop")),
1840 Some(Flow::Continue(s)) => Err(self.error(DiagnosticKind::Syntax, s, "cannot continue outside of loop")),
1841 }
1842 }
1843
1844 fn eval_args(&mut self, node: Option<&SyntaxNode>, span: Span) -> Outcome<Args> {
1845 // A call in a string given to `eval` has no span of its own; it takes the call site's, whose file
1846 // a path in the call resolves against, as in Typst.
1847 let mut args = Args::new(self.fix(span));
1848 let node = match node {
1849 Some(n) => n.clone(),
1850 None => return Ok(args),
1851 };
1852 for c in node.children() {
1853 match c.kind() {
1854 SyntaxKind::Named => {
1855 let name = c.children().iter().find(|x| x.kind() == SyntaxKind::Ident)
1856 .map(|x| x.text().to_string()).unwrap_or_default();
1857 let (v, at) = match last_expr(c) {
1858 Some(e) => (res!(self.eval(e)), e.span()),
1859 None => (Value::None, c.span()),
1860 };
1861 args.push_named_at(self.fix(c.span()), self.fix(at), name, v);
1862 }
1863 SyntaxKind::Spread => {
1864 let v = match last_expr(c) {
1865 Some(e) => res!(self.eval(e)),
1866 None => Value::None,
1867 };
1868 match v {
1869 Value::None => (),
1870 Value::Array(a) => for x in a.iter() {
1871 args.push(self.fix(c.span()), x.clone());
1872 },
1873 Value::Dict(d) => for (k, x) in d.iter() {
1874 args.push_named(self.fix(c.span()), k, x.clone());
1875 },
1876 Value::Args(a) => args.items.extend(a.items.iter().cloned()),
1877 other => return Err(self.error(DiagnosticKind::Type, c.span(),
1878 fmt!("cannot spread {}", other.ty().long_name()))),
1879 }
1880 }
1881 k if is_code_expr(k) => {
1882 let v = res!(self.eval(c));
1883 args.push(self.fix(c.span()), v);
1884 }
1885 _ => (),
1886 }
1887 }
1888 Ok(args)
1889 }
1890
1891 fn eval_call(&mut self, node: &SyntaxNode) -> Outcome<Value> {
1892 let span = node.span();
1893 let callee = match first_expr(node) {
1894 Some(c) => c.clone(),
1895 None => return Err(self.error(DiagnosticKind::Syntax, span, "call without a callee")),
1896 };
1897 let args_node = node.child(SyntaxKind::Args).cloned();
1898 if callee.kind() == SyntaxKind::FieldAccess {
1899 let target = match first_expr(&callee) {
1900 Some(t) => t.clone(),
1901 None => return Err(self.error(DiagnosticKind::Syntax, span, "field access without a target")),
1902 };
1903 let field = ident_text(&callee).unwrap_or("").to_string();
1904 if methods::is_mutating(&field) && matches!(target.kind(),
1905 SyntaxKind::Ident | SyntaxKind::FieldAccess | SyntaxKind::FuncCall | SyntaxKind::Parenthesized)
1906 {
1907 let args = res!(self.eval_args(args_node.as_ref(), span));
1908 let (root, rs, steps) = res!(self.place(&target));
1909 let got = match slot(&mut self.frames, self.base, self.in_func, &root, rs, &steps, false) {
1910 Ok(place) => Ok(methods::call_method_mut(self.engine, place, &field, args, span)),
1911 Err(e) => Err(e),
1912 };
1913 return match got {
1914 Ok(r) => r,
1915 Err(e) => Err(self.place_error(e)),
1916 };
1917 }
1918 let tv = res!(self.eval(&target));
1919 let mut args = res!(self.eval_args(args_node.as_ref(), span));
1920 if methods::is_mutating(&field) && matches!(tv, Value::Array(_) | Value::Dict(_)) {
1921 return Err(self.error(DiagnosticKind::Syntax, span, "cannot mutate a temporary value"));
1922 }
1923 if let Some(f) = methods::type_method(tv.ty(), &field).or_else(|| methods::element_method(&tv, &field)) {
1924 args.prepend(target.span(), tv);
1925 return self.engine.call_func(&Func::Native(f), args);
1926 }
1927 return match tv {
1928 Value::Symbol(_) | Value::Func(_) | Value::Type(_) | Value::Module(_) => {
1929 let fv = res!(self.field(tv, &field, callee.span()));
1930 self.call_value(fv, args, &callee, args_node.as_ref(), span)
1931 }
1932 Value::Dict(ref d) if matches!(d.get(&field), Some(Value::Func(_))) => Err(self.error_hint(DiagnosticKind::Type, span,
1933 "cannot directly call dictionary keys as functions", fmt!(
1934 "to call the stored function, wrap the field access in parentheses: `({})(..)`",
1935 callee.full_text().trim()))),
1936 // A function in the type's own scope is called with the value as its first argument, as Typst
1937 // calls it: `c.mix(red)` is `color.mix(c, red)`.
1938 other => match foundations::type_scope(other.ty(), &field) {
1939 Some(Value::Func(f)) => {
1940 args.prepend(target.span(), other);
1941 self.engine.call_func(&f, args)
1942 },
1943 _ => Err(self.error(DiagnosticKind::Type, callee.span(),
1944 fmt!("type {} has no method `{}`", other.ty().long_name(), field))),
1945 },
1946 };
1947 }
1948 let cv = res!(self.eval(&callee));
1949 let args = res!(self.eval_args(args_node.as_ref(), span));
1950 self.call_value(cv, args, &callee, args_node.as_ref(), span)
1951 }
1952
1953 fn call_value(
1954 &mut self,
1955 callee: Value,
1956 mut args: Args,
1957 callee_node: &SyntaxNode,
1958 args_node: Option<&SyntaxNode>,
1959 span: Span,
1960 )
1961 -> Outcome<Value>
1962 {
1963 // A symbol is callable where it is an accent or an opening delimiter, `sym.acute($x$)` and
1964 // `math.floor($x$)`; any other reads as text in maths and is not callable in code.
1965 let callee = match callee {
1966 Value::Symbol(_) => match foundations::as_func(&callee) {
1967 Some(f) => Value::Func(f),
1968 None if in_math(callee_node) => callee,
1969 None => return Err(self.error(DiagnosticKind::Type, callee_node.span(),
1970 foundations::func_refusal(&callee))),
1971 },
1972 other => other,
1973 };
1974 match callee {
1975 Value::Func(f) => self.engine.call_func(&f, args),
1976 Value::Type(t) => match foundations::constructor(t) {
1977 Some(f) => self.engine.call_func(&Func::Native(f), args),
1978 None => Err(self.error(DiagnosticKind::Type, callee_node.span(), fmt!("type {} is not callable", t.name()))),
1979 },
1980 other if in_math(callee_node) => {
1981 // `$f(x)$` with a non-function `f`: the callee, then its arguments in parentheses.
1982 let head = res!(self.display(other, callee_node.span()));
1983 let mut body = Content::text("(");
1984 let pos = res!(args.all::<Value>());
1985 let n = pos.len();
1986 for (i, v) in pos.into_iter().enumerate() {
1987 if i > 0 {
1988 body = ops::content_add(body, Content::text(","));
1989 }
1990 let c = res!(self.display(v, span));
1991 body = ops::content_add(body, c);
1992 }
1993 let trailing = args_node.map(|a| {
1994 a.children().iter().rev().find(|c| !c.kind().is_trivia() && c.kind() != SyntaxKind::RightParen)
1995 .map(|c| c.kind() == SyntaxKind::Comma).unwrap_or(false)
1996 }).unwrap_or(false);
1997 if trailing && n > 0 {
1998 body = ops::content_add(body, Content::text(","));
1999 }
2000 body = ops::content_add(body, Content::text(")"));
2001 let lr = res!(self.elem(ElemKind::MathLr, vec![("body", Value::Content(body))], span));
2002 Ok(Value::Content(Content::sequence(vec![head, lr])))
2003 }
2004 other => Err(self.error(DiagnosticKind::Type, callee_node.span(),
2005 fmt!("expected function, found {}", other.ty().long_name()))),
2006 }
2007 }
2008
2009 /// `value.name`: a symbol modifier, a dictionary key, a content field, a module, function or type
2010 /// member, or one of the few fields plain values carry.
2011 fn field(&mut self, v: Value, name: &str, span: Span) -> Outcome<Value> {
2012 let ty = v.ty();
2013 let found = match &v {
2014 Value::Symbol(s) => match ops::symbol_modified(s, name) {
2015 Some(m) => Some(Value::Symbol(m)),
2016 None => return Err(self.error(DiagnosticKind::Type, span, "unknown symbol modifier")),
2017 },
2018 Value::Version(_) => match foundations::field(&v, name) {
2019 Some(x) => Some(x),
2020 None => return Err(self.error(DiagnosticKind::Type, span, "unknown version component")),
2021 },
2022 Value::Dict(d) => match d.get(name) {
2023 Some(v) => Some(v.clone()),
2024 None => return Err(self.error(DiagnosticKind::Type, span, fmt!("dictionary does not contain key \"{}\"", name))),
2025 },
2026 Value::Content(c) => match methods::content_field(c, name) {
2027 Some(v) => Some(v),
2028 None => return Err(self.error(DiagnosticKind::Type, span, fmt!(
2029 "{} does not have field \"{}\"", methods::content_name(c), name))),
2030 },
2031 Value::Type(t) => match foundations::type_scope(*t, name) {
2032 Some(x) => Some(x),
2033 None => return Err(self.error(DiagnosticKind::Type, span, fmt!("type {} does not contain field `{}`", t.long_name(), name))),
2034 },
2035 Value::Func(f) => match func_field(f, name) {
2036 Some(g) => Some(Value::Func(g)),
2037 None => match res!(self.style_field(f, name, span)) {
2038 Some(v) => Some(v),
2039 None => return Err(self.error(DiagnosticKind::Type, span, match f.name() {
2040 Some(n) => fmt!("function `{}` does not contain field `{}`", n, name),
2041 None => fmt!("function does not contain field `{}`", name),
2042 })),
2043 },
2044 },
2045 Value::Module(m) => match m.scope.get(name) {
2046 Some(v) => Some(v.clone()),
2047 None => return Err(self.error(DiagnosticKind::UnknownVariable, span, fmt!("module `{}` does not contain `{}`", m.name, name))),
2048 },
2049 Value::Length(_) | Value::Relative(_) | Value::Alignment(_) | Value::Stroke(_)
2050 => foundations::field(&v, name),
2051 _ => return Err(self.error(DiagnosticKind::Type, span, fmt!("cannot access fields on type {}", ty.long_name()))),
2052 };
2053 match found {
2054 Some(v) => Ok(v),
2055 None => Err(self.error(DiagnosticKind::Type, span, fmt!("{} does not contain field \"{}\"", ty.long_name(), name))),
2056 }
2057 }
2058
2059 /// Typst's get rule: `text.size` in a `context` is the value the styles in force give the element's
2060 /// settable field. `None` where `f` is not an element function with such a field; outside a context
2061 /// the field is known but its value is not, and that is an error.
2062 fn style_field(&mut self, f: &Func, name: &str, span: Span) -> Outcome<Option<Value>> {
2063 let kind = match f {
2064 Func::Element(k) => *k,
2065 _ => return Ok(None),
2066 };
2067 let id = match kind.field_id(name) {
2068 Some(id) => id,
2069 None => return Ok(None),
2070 };
2071 if !kind.field_spec(id).map(|spec| spec.settable).unwrap_or(false) {
2072 return Ok(None);
2073 }
2074 let styles = res!(intro::context_styles(self.engine, span));
2075 // A page's size is read through its paper when no width or height is set nearer.
2076 if kind == ElemKind::Page && (name == "width" || name == "height") {
2077 let (w, h) = lib::layout::page_dims(&styles);
2078 return Ok(Some(if name == "width" { w } else { h }));
2079 }
2080 match res!(styles.get(kind, id)) {
2081 Some(v) => Ok(Some(res!(lib::text::as_read(kind, name, v)))),
2082 None => Ok(content::default_field(kind, id)),
2083 }
2084 }
2085
2086 // Rules
2087
2088 fn eval_set(&mut self, node: &SyntaxNode) -> Outcome<Styles> {
2089 if let Some(cond) = expr_after(node, SyntaxKind::If) {
2090 let cond = cond.clone();
2091 if !res!(self.expect_bool(&cond)) {
2092 return Ok(Styles::new());
2093 }
2094 }
2095 let target = match expr_after(node, SyntaxKind::Set) {
2096 Some(t) => t.clone(),
2097 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "set rule without a target")),
2098 };
2099 let tv = res!(self.eval(&target));
2100 let kind = match &tv {
2101 Value::Func(f) => match f.element() {
2102 Some(k) => k,
2103 None => return Err(self.error(DiagnosticKind::Type, target.span(), "only element functions can be used in set rules")),
2104 },
2105 other => return Err(self.error(DiagnosticKind::Type, target.span(),
2106 fmt!("expected function, found {}", other.ty().long_name()))),
2107 };
2108 let args = res!(self.eval_args(node.child(SyntaxKind::Args), node.span()));
2109 let mark = self.engine.diags.len();
2110 match styles::set_rule(self.engine, kind, args) {
2111 Ok(s) => Ok(s.liftable()),
2112 Err(e) => {
2113 let span = self.fix(node.span());
2114 Err(self.engine.adopt(mark, span, e))
2115 }
2116 }
2117 }
2118
2119 fn eval_show(&mut self, node: &SyntaxNode) -> Outcome<Recipe> {
2120 let span = node.span();
2121 let before_colon: Vec<SyntaxNode> = node.children().iter()
2122 .take_while(|c| c.kind() != SyntaxKind::Colon)
2123 .filter(|c| is_code_expr(c.kind())).cloned().collect();
2124 let selector = match before_colon.first() {
2125 Some(s) => Some(res!(self.eval_selector(s))),
2126 None => None,
2127 };
2128 let transform_node = match node.children().iter().skip_while(|c| c.kind() != SyntaxKind::Colon)
2129 .skip(1).find(|c| is_code_expr(c.kind()))
2130 {
2131 Some(t) => t.clone(),
2132 None => return Err(self.error(DiagnosticKind::Syntax, span, "show rule without a transformation")),
2133 };
2134 let transform = if transform_node.kind() == SyntaxKind::SetRule {
2135 Transformation::Style(res!(self.eval_set(&transform_node)))
2136 } else {
2137 match res!(self.eval(&transform_node)) {
2138 Value::Content(c) => Transformation::Content(c),
2139 Value::Func(f) => Transformation::Func(f),
2140 Value::Styles(s) => Transformation::Style(s),
2141 v @ (Value::None | Value::Str(_) | Value::Symbol(_))
2142 => Transformation::Content(res!(self.display(v, transform_node.span()))),
2143 other => return Err(self.error(DiagnosticKind::Type, transform_node.span(),
2144 fmt!("expected content or function, found {}", other.ty().long_name()))),
2145 }
2146 };
2147 Ok(Recipe { selector, transform, span, outside: false })
2148 }
2149
2150 fn eval_selector(&mut self, node: &SyntaxNode) -> Outcome<Selector> {
2151 let v = res!(self.eval(node));
2152 select::cast_showable(self.engine, node.span(), v)
2153 }
2154
2155 fn eval_context(&mut self, node: &SyntaxNode) -> Outcome<Value> {
2156 let body = match last_expr(node) {
2157 Some(b) => b.clone(),
2158 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "context without a body")),
2159 };
2160 let captured = self.capture(&body);
2161 let closure = Closure::new(None, Vec::new(), body.clone(), captured, body.span());
2162 let func = Value::Func(Func::Closure(Arc::new(closure)));
2163 self.elem(ElemKind::Context, vec![("func", func)], node.span()).map(Value::Content)
2164 }
2165
2166 // Control flow
2167
2168 fn eval_if(&mut self, node: &SyntaxNode) -> Outcome<Value> {
2169 let exprs = code_exprs(node);
2170 let (cond, then) = match (exprs.first(), exprs.get(1)) {
2171 (Some(c), Some(t)) => ((*c).clone(), (*t).clone()),
2172 _ => return Err(self.error(DiagnosticKind::Syntax, node.span(), "incomplete conditional")),
2173 };
2174 let otherwise = expr_after(node, SyntaxKind::Else).cloned();
2175 let out = if res!(self.expect_bool(&cond)) {
2176 res!(self.eval(&then))
2177 } else {
2178 match otherwise {
2179 Some(e) => res!(self.eval(&e)),
2180 None => Value::None,
2181 }
2182 };
2183 self.mark_return_conditional();
2184 Ok(out)
2185 }
2186
2187 /// A `return` inside an `if` or a loop may not have run, so it discards nothing for certain.
2188 fn mark_return_conditional(&mut self) {
2189 if let Some(Flow::Return(_, _, conditional)) = &mut self.flow {
2190 *conditional = true;
2191 }
2192 }
2193
2194 /// Typst's warning for a `return` that throws away content the block had already produced.
2195 fn warn_discarded(&mut self, output: &Value) {
2196 let span = match &self.flow {
2197 Some(Flow::Return(span, Some(_), false)) => *span,
2198 _ => return,
2199 };
2200 let tree = match output {
2201 Value::Content(c) => c,
2202 _ => return,
2203 };
2204 let mut d = Diagnostic::warning(DiagnosticKind::Lint, self.fix(span), "this return unconditionally discards the content before it")
2205 .with_hint("try omitting the `return` to automatically join all values");
2206 if contains_update(tree, 0) {
2207 d = d.with_hint("state/counter updates are content that must end up in the document to have an effect");
2208 }
2209 self.engine.diags.push(d);
2210 }
2211
2212 fn eval_while(&mut self, node: &SyntaxNode) -> Outcome<Value> {
2213 let exprs = code_exprs(node);
2214 let (cond, body) = match (exprs.first(), exprs.get(1)) {
2215 (Some(c), Some(b)) => ((*c).clone(), (*b).clone()),
2216 _ => return Err(self.error(DiagnosticKind::Syntax, node.span(), "incomplete while loop")),
2217 };
2218 let outer = self.flow.take();
2219 let mut output = Value::None;
2220 let mut i = 0;
2221 while res!(self.expect_bool(&cond)) {
2222 if i == 0 && is_invariant(&cond) && !can_diverge(&body) {
2223 return Err(self.error(DiagnosticKind::Limit, cond.span(), "condition is always true"));
2224 }
2225 if i >= MAX_WHILE_ITERATIONS {
2226 return Err(self.error(DiagnosticKind::Limit, node.span(), "loop seems to be infinite"));
2227 }
2228 res!(self.burn(node.span()));
2229 let v = res!(self.eval(&body));
2230 output = match ops::join(output, v) {
2231 Ok(v) => v,
2232 Err(e) => return Err(self.fail(body.span(), e)),
2233 };
2234 match self.flow {
2235 Some(Flow::Break(_)) => {
2236 self.flow = None;
2237 break;
2238 }
2239 Some(Flow::Continue(_)) => self.flow = None,
2240 Some(Flow::Return(..)) => {
2241 self.mark_return_conditional();
2242 break;
2243 }
2244 None => (),
2245 }
2246 i += 1;
2247 }
2248 if outer.is_some() {
2249 self.flow = outer;
2250 }
2251 Ok(output)
2252 }
2253
2254 fn burn(&mut self, span: Span) -> Outcome<()> {
2255 let span = self.fix(span);
2256 self.engine.burn(span)
2257 }
2258
2259 fn eval_for(&mut self, node: &SyntaxNode) -> Outcome<Value> {
2260 let pattern = match pattern_after(node, SyntaxKind::For) {
2261 Some(p) => p.clone(),
2262 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "for loop without a pattern")),
2263 };
2264 let iterable = match expr_after(node, SyntaxKind::In) {
2265 Some(e) => e.clone(),
2266 None => return Err(self.error(DiagnosticKind::Type, node.span(), "for loop without an iterable")),
2267 };
2268 let body = match last_expr(node) {
2269 Some(b) => b.clone(),
2270 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "for loop without a body")),
2271 };
2272 let it = res!(self.eval(&iterable));
2273 let destructuring = pattern.kind() == SyntaxKind::Destructuring;
2274 let items: Vec<Value> = match it {
2275 Value::Array(a) => (*a).clone(),
2276 Value::Dict(d) => d.iter().map(|(k, v)| Value::array(vec![Value::str(k), v.clone()])).collect(),
2277 Value::Str(s) if !destructuring => segment::graphemes(&s).into_iter().map(Value::str).collect(),
2278 Value::Bytes(b) if !destructuring => b.iter().map(|x| Value::Int(*x as i64)).collect(),
2279 v @ (Value::Str(_) | Value::Bytes(_)) => return Err(self.error(DiagnosticKind::Type, pattern.span(),
2280 fmt!("cannot destructure values of {}", v.ty().long_name()))),
2281 other => return Err(self.error(DiagnosticKind::Type, iterable.span(), fmt!("cannot loop over {}", other.ty().long_name()))),
2282 };
2283 let outer = self.flow.take();
2284 let mut output = Value::None;
2285 self.frames.push(Frame::new());
2286 let mut result = Ok(());
2287 for v in items {
2288 if let Err(e) = self.burn(node.span()) {
2289 result = Err(e);
2290 break;
2291 }
2292 if let Err(e) = self.destructure(&pattern, v, Bind::Define) {
2293 result = Err(e);
2294 break;
2295 }
2296 let v = match self.eval(&body) {
2297 Ok(v) => v,
2298 Err(e) => {
2299 result = Err(e);
2300 break;
2301 }
2302 };
2303 output = match ops::join(std::mem::take(&mut output), v) {
2304 Ok(v) => v,
2305 Err(e) => {
2306 result = Err(self.fail(body.span(), e));
2307 break;
2308 }
2309 };
2310 match self.flow {
2311 Some(Flow::Break(_)) => {
2312 self.flow = None;
2313 break;
2314 }
2315 Some(Flow::Continue(_)) => self.flow = None,
2316 Some(Flow::Return(..)) => {
2317 self.mark_return_conditional();
2318 break;
2319 }
2320 None => (),
2321 }
2322 }
2323 self.frames.pop();
2324 res!(result);
2325 if outer.is_some() {
2326 self.flow = outer;
2327 }
2328 Ok(output)
2329 }
2330
2331 // Modules
2332
2333 fn eval_import(&mut self, node: &SyntaxNode) -> Outcome<Value> {
2334 let src_node = match expr_after(node, SyntaxKind::Import) {
2335 Some(s) => s.clone(),
2336 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "import without a source")),
2337 };
2338 let src_span = src_node.span();
2339 let source = res!(self.eval(&src_node));
2340 let source = match source {
2341 Value::Str(spec) => {
2342 let mark = self.engine.diags.len();
2343 match import::import_module(self.engine, &spec, self.file, self.fix(src_span)) {
2344 Ok(m) => Value::Module(m),
2345 Err(e) => {
2346 let span = self.fix(src_span);
2347 return Err(self.engine.adopt(mark, span, e));
2348 }
2349 }
2350 }
2351 Value::Func(Func::Closure(_)) => return Err(self.error(DiagnosticKind::Type, src_span, "cannot import from user-defined functions")),
2352 v @ (Value::Module(_) | Value::Func(_) | Value::Type(_)) => v,
2353 other => return Err(self.error(DiagnosticKind::Type, src_span, fmt!(
2354 "expected path, module, function, or type, found {}", other.ty().long_name()))),
2355 };
2356 let new_name = node.children().iter().skip_while(|c| c.kind() != SyntaxKind::As)
2357 .skip(1).find(|c| c.kind() == SyntaxKind::Ident).cloned();
2358 // `as` directly after the source renames the module; an `as` inside the item list does not.
2359 let colon_seen_before_as = node.children().iter()
2360 .position(|c| c.kind() == SyntaxKind::Colon)
2361 .zip(node.children().iter().position(|c| c.kind() == SyntaxKind::As))
2362 .map(|(c, a)| c < a).unwrap_or(false);
2363 let new_name = if colon_seen_before_as { None } else { new_name };
2364 if let Some(n) = &new_name {
2365 if src_node.kind() == SyntaxKind::Ident && src_node.text() == n.text() {
2366 self.engine.warn(DiagnosticKind::Lint, self.fix(n.span()), "unnecessary import rename to same name");
2367 }
2368 self.define(n.text(), source.clone(), n.span());
2369 }
2370 let imports = node.children().iter().skip_while(|c| c.kind() != SyntaxKind::Colon).skip(1)
2371 .find(|c| matches!(c.kind(), SyntaxKind::Star | SyntaxKind::ImportItems | SyntaxKind::Ident)).cloned();
2372 match imports {
2373 None => {
2374 if new_name.is_none() {
2375 let bare = match ast::ModuleImport::from_untyped(node) {
2376 Some(m) => m.bare_name(),
2377 None => Err(BareImportError::Dynamic),
2378 };
2379 match bare {
2380 // `import calc` binds `calc` to itself.
2381 Ok(_) if src_node.kind() == SyntaxKind::Ident => {
2382 self.engine.warn(DiagnosticKind::Lint, self.fix(src_span), "this import has no effect");
2383 }
2384 Ok(b) => self.define(&b, source, src_span),
2385 Err(BareImportError::Dynamic) => return Err(self.error_hint(DiagnosticKind::Syntax, src_span,
2386 "dynamic import requires an explicit name", "you can name the import with `as`")),
2387 Err(_) => return Err(self.error_hint(DiagnosticKind::Syntax, src_span,
2388 "module name would not be a valid identifier", "you can rename the import with `as`")),
2389 }
2390 }
2391 }
2392 Some(star) if star.kind() == SyntaxKind::Star => {
2393 let entries: Vec<(String, Value)> = match &source {
2394 Value::Module(m) => m.scope.iter().map(|(k, b)| (k.clone(), b.value.clone())).collect(),
2395 Value::Func(Func::Element(k)) => ElemKind::ALL.iter()
2396 .filter(|c| c.path().strip_prefix(k.path()).map(|r| r.starts_with('.') && !r[1..].contains('.')).unwrap_or(false))
2397 .map(|c| (c.name().to_string(), Value::Func(Func::Element(*c)))).collect(),
2398 _ => Vec::new(),
2399 };
2400 for (k, v) in entries {
2401 self.define(&k, v, star.span());
2402 }
2403 }
2404 Some(items) => {
2405 let list: Vec<SyntaxNode> = if items.kind() == SyntaxKind::Ident {
2406 vec![items.clone()]
2407 } else {
2408 items.children().iter().filter(|c| matches!(c.kind(),
2409 SyntaxKind::ImportItemPath | SyntaxKind::RenamedImportItem | SyntaxKind::Ident)).cloned().collect()
2410 };
2411 let mut failed = None;
2412 for item in &list {
2413 let (path, bound): (Vec<SyntaxNode>, SyntaxNode) = match item.kind() {
2414 SyntaxKind::Ident => (vec![item.clone()], item.clone()),
2415 SyntaxKind::ImportItemPath => {
2416 let p: Vec<SyntaxNode> = item.children().iter()
2417 .filter(|c| c.kind() == SyntaxKind::Ident).cloned().collect();
2418 match p.last() {
2419 Some(l) => (p.clone(), l.clone()),
2420 None => continue,
2421 }
2422 }
2423 _ => {
2424 let path_node = item.child(SyntaxKind::ImportItemPath);
2425 let p: Vec<SyntaxNode> = match path_node {
2426 Some(pn) => pn.children().iter().filter(|c| c.kind() == SyntaxKind::Ident).cloned().collect(),
2427 None => item.children().iter().take_while(|c| c.kind() != SyntaxKind::As)
2428 .filter(|c| c.kind() == SyntaxKind::Ident).cloned().collect(),
2429 };
2430 let b = item.children().iter().skip_while(|c| c.kind() != SyntaxKind::As).skip(1)
2431 .find(|c| c.kind() == SyntaxKind::Ident).cloned();
2432 match b {
2433 Some(b) => {
2434 if p.last().map(|l| l.text() == b.text()).unwrap_or(false) {
2435 self.engine.warn(DiagnosticKind::Lint, self.fix(b.span()), "unnecessary import rename to same name");
2436 }
2437 (p, b)
2438 }
2439 None => continue,
2440 }
2441 }
2442 };
2443 let mut cur = source.clone();
2444 let mut ok = true;
2445 for (i, comp) in path.iter().enumerate() {
2446 let next = scope_member(&cur, comp.text());
2447 match next {
2448 Some(v) => {
2449 if i + 1 < path.len() && !matches!(v, Value::Module(_) | Value::Func(_) | Value::Type(_)) {
2450 failed = Some(self.error(DiagnosticKind::Type, comp.span(), fmt!(
2451 "expected module, function, or type, found {}", v.ty().long_name())));
2452 ok = false;
2453 break;
2454 }
2455 cur = v;
2456 }
2457 None => {
2458 failed = Some(self.error(DiagnosticKind::UnknownVariable, comp.span(), "unresolved import"));
2459 ok = false;
2460 break;
2461 }
2462 }
2463 }
2464 if ok {
2465 self.define(bound.text(), cur, bound.span());
2466 }
2467 }
2468 if let Some(e) = failed {
2469 return Err(e);
2470 }
2471 }
2472 }
2473 Ok(Value::None)
2474 }
2475
2476 fn eval_include(&mut self, node: &SyntaxNode) -> Outcome<Value> {
2477 let src_node = match expr_after(node, SyntaxKind::Include) {
2478 Some(s) => s.clone(),
2479 None => return Err(self.error(DiagnosticKind::Syntax, node.span(), "include without a source")),
2480 };
2481 let span = self.fix(src_node.span());
2482 match res!(self.eval(&src_node)) {
2483 Value::Str(spec) => {
2484 let mark = self.engine.diags.len();
2485 match import::include(self.engine, &spec, self.file, span) {
2486 Ok(c) => Ok(Value::Content(c)),
2487 Err(e) => Err(self.engine.adopt(mark, span, e)),
2488 }
2489 }
2490 Value::Module(m) => Ok(Value::Content(m.content.clone())),
2491 other => Err(self.error(DiagnosticKind::Type, span, fmt!("expected path or module, found {}", other.ty().long_name()))),
2492 }
2493 }
2494}
2495
2496/// Is every segment of a dotted path a name the standard library binds: the first in its global scope, each
2497/// later one in the scope of what the one before names (`calc.pow`, `table.cell`, `str.len`)? The names
2498/// asked of it are a document's own, so it answers and never says more.
2499pub fn std_path_bound(path: &[&str]) -> bool {
2500 let lib = library();
2501 let mut it = path.iter();
2502 let mut v = match it.next().and_then(|n| lib.get(n)) {
2503 Some(v) => v.clone(),
2504 None => return false,
2505 };
2506 for name in it {
2507 v = match scope_member(&v, name) {
2508 Some(next) => next,
2509 None => return false,
2510 };
2511 }
2512 true
2513}
2514
2515// A name `import`ed from a module, function or type.
2516fn scope_member(v: &Value, name: &str) -> Option<Value> {
2517 match v {
2518 Value::Module(m) => m.scope.get(name).cloned(),
2519 Value::Func(f) => func_field(f, name).map(Value::Func),
2520 Value::Type(t) => methods::type_method(*t, name).map(|f| Value::Func(Func::Native(f))),
2521 _ => None,
2522 }
2523}
2524
2525// The name a bare `import "path"` binds: the package name or the file stem.
2526
2527// Does the content hold a counter or state update, anywhere in its tree?
2528fn contains_update(c: &Content, depth: usize) -> bool {
2529 if depth > 256 {
2530 return false;
2531 }
2532 match c {
2533 Content::Sequence(seq) => seq.children.iter().any(|k| contains_update(k, depth + 1)),
2534 Content::Styled(st) => contains_update(&st.child, depth + 1),
2535 Content::Elem(e) => matches!(e.kind, ElemKind::CounterUpdate | ElemKind::StateUpdate)
2536 || e.fields.iter().any(|(_, v)| match v {
2537 Value::Content(k) => contains_update(k, depth + 1),
2538 _ => false,
2539 }),
2540 }
2541}