Oregami
Repositories/oxedyne/fe2o3

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

11.5 KiB, 5 runs

created by r1870400018:63500, 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// U2 owns this file: method dispatch by receiver type. A method belongs to the area that owns its
2// receiver's type (`str` -> `lib/string.rs`, `counter` -> `lib/intro.rs`, `selector` -> `select.rs`); each
3// such area exposes `method(name) -> Option<XFn>`, and this file maps receiver type to area. The four
4// mutating methods (`push`, `pop`, `insert`, `remove` on arrays and dictionaries) are carried out here on
5// the place itself, as Typst's own evaluator does, since a native function only ever sees a copy.
6
7use crate::diag::DiagnosticKind;
8use crate::eval::args::Args;
9use crate::eval::content::{
10 Content,
11 FieldId,
12};
13use crate::eval::func::{
14 Func,
15 NativeFunc,
16};
17use crate::eval::lib;
18use crate::eval::select;
19use crate::eval::value::{
20 Dict,
21 Type,
22 Value,
23};
24use crate::eval::Engine;
25use crate::syntax::Span;
26
27use oxedyne_fe2o3_core::prelude::*;
28
29use std::sync::Arc;
30
31native_fns! {
32 /// Methods on content, functions, arguments and modules, which no library area owns.
33 pub enum CoreFn {
34 With => "with",
35 ContentFields => "fields",
36 ContentHas => "has",
37 ContentAt => "at",
38 ContentFunc => "func",
39 ContentLocation => "location",
40 ArgsPos => "pos",
41 ArgsNamed => "named",
42 ArgsAt => "at",
43 }
44}
45
46fn fail(msg: String) -> Error<ErrTag> { err!("{}", msg; Input, Invalid) }
47
48/// The method a value of this type answers to by `name`, or a static function in the type's scope
49/// (`str.from-unicode`, `datetime.today`), from the area that owns the type.
50pub fn type_method(ty: Type, name: &str) -> Option<NativeFunc> {
51 match ty {
52 Type::Str => lib::string::method(name).map(NativeFunc::Str),
53 Type::Array => lib::array::method(name).map(NativeFunc::Array),
54 Type::Dict => lib::dict::method(name).map(NativeFunc::Dict),
55 Type::Color | Type::Gradient
56 => lib::color::method(name).map(NativeFunc::Color),
57 Type::Datetime | Type::Duration
58 => lib::datetime::method(name).map(NativeFunc::Datetime),
59 Type::Version | Type::Bytes | Type::Int | Type::Float
60 => lib::foundations::method(name).map(NativeFunc::Found),
61 Type::Symbol => lib::sym::method(name).map(NativeFunc::Sym),
62 Type::Length | Type::Angle | Type::Ratio | Type::Relative | Type::Fraction | Type::Alignment
63 | Type::Direction
64 => lib::geom::method(name).map(NativeFunc::Geom),
65 Type::Counter | Type::State | Type::Location
66 => lib::intro::method(name).map(NativeFunc::Intro),
67 Type::Selector => select::method(name).map(NativeFunc::Style),
68 Type::Func => match name {
69 "with" => Some(NativeFunc::Core(CoreFn::With)),
70 "where" => select::method(name).map(NativeFunc::Style),
71 _ => None,
72 },
73 Type::Content => match name {
74 "fields" => Some(NativeFunc::Core(CoreFn::ContentFields)),
75 "has" => Some(NativeFunc::Core(CoreFn::ContentHas)),
76 "at" => Some(NativeFunc::Core(CoreFn::ContentAt)),
77 "func" => Some(NativeFunc::Core(CoreFn::ContentFunc)),
78 "location" => Some(NativeFunc::Core(CoreFn::ContentLocation)),
79 _ => None,
80 },
81 Type::Args => match name {
82 "pos" => Some(NativeFunc::Core(CoreFn::ArgsPos)),
83 "named" => Some(NativeFunc::Core(CoreFn::ArgsNamed)),
84 "at" => Some(NativeFunc::Core(CoreFn::ArgsAt)),
85 _ => None,
86 },
87 _ => None,
88 }
89}
90
91/// Is `name` one of the methods that change their receiver in place?
92pub fn is_mutating(name: &str) -> bool { matches!(name, "push" | "pop" | "insert" | "remove") }
93
94pub fn call(f: CoreFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
95 let _ = engine;
96 let receiver = res!(args.expect::<Value>("self"));
97 let out = match (f, receiver) {
98 (CoreFn::With, Value::Func(func)) => {
99 let bound = std::mem::take(&mut args);
100 return Ok(Value::Func(func.with(bound)));
101 }
102 (CoreFn::ContentFields, Value::Content(c)) => Value::dict(content_fields(&c)),
103 (CoreFn::ContentHas, Value::Content(c)) => {
104 let name = res!(args.expect::<String>("field"));
105 Value::Bool(content_field(&c, &name).is_some())
106 }
107 (CoreFn::ContentAt, Value::Content(c)) => {
108 let name = res!(args.expect::<String>("field"));
109 let default = res!(args.named::<Value>("default"));
110 match (content_field(&c, &name), default) {
111 (Some(v), _) => v,
112 (None, Some(d)) => d,
113 (None, None) => return Err(fail(fmt!(
114 "{} does not have field \"{}\" and no default was specified", content_name(&c), name))),
115 }
116 }
117 (CoreFn::ContentFunc, Value::Content(c)) => Value::Func(Func::Element(c.func_kind())),
118 (CoreFn::ContentLocation, Value::Content(c)) => match c.location() {
119 Some(l) => Value::Location(l),
120 None => Value::None,
121 },
122 (CoreFn::ArgsPos, Value::Args(a)) => Value::array(
123 a.items.iter().filter(|i| i.name.is_none()).map(|i| i.value.clone()).collect()),
124 (CoreFn::ArgsNamed, Value::Args(a)) => {
125 let mut d = Dict::new();
126 for i in a.items.iter() {
127 if let Some(n) = &i.name {
128 d.insert(n, i.value.clone());
129 }
130 }
131 Value::dict(d)
132 }
133 (CoreFn::ArgsAt, Value::Args(a)) => {
134 let key = res!(args.expect::<Value>("key")).symbol_as_str();
135 let default = res!(args.named::<Value>("default"));
136 let found = match &key {
137 Value::Int(i) => {
138 let pos: Vec<&Value> = a.items.iter().filter(|x| x.name.is_none()).map(|x| &x.value).collect();
139 let idx = if *i < 0 { pos.len() as i64 + i } else { *i };
140 if idx >= 0 { pos.get(idx as usize).map(|v| (*v).clone()) } else { None }
141 }
142 Value::Str(s) => a.items.iter().rev().find(|x| x.name.as_deref() == Some(s.as_str()))
143 .map(|x| x.value.clone()),
144 other => return Err(fail(fmt!("expected integer or string, found {}", other.ty().long_name()))),
145 };
146 match (found, default, key) {
147 (Some(v), _, _) => v,
148 (None, Some(d), _) => d,
149 (None, None, Value::Int(i)) => return Err(fail(fmt!(
150 "no positional argument at index {} and no default value was specified", i))),
151 (None, None, Value::Str(s)) => return Err(fail(fmt!(
152 "arguments do not contain key \"{}\" and no default value was specified", s))),
153 (None, None, _) => Value::None,
154 }
155 }
156 (f, other) => return Err(fail(fmt!("type {} has no method `{}`", other.ty().long_name(), f.name()))),
157 };
158 res!(args.finish());
159 Ok(out)
160}
161
162/// The name Typst gives a content value's element: `strong`, `sequence`, `styled`.
163pub fn content_name(c: &Content) -> &'static str {
164 match c {
165 Content::Elem(e) => e.kind.name(),
166 Content::Sequence(_) => "sequence",
167 Content::Styled(_) => "styled",
168 }
169}
170
171/// A field as `it.name` reads it: a stored field, the label, a sequence's children or a styled
172/// content's child and styles.
173pub fn content_field(c: &Content, name: &str) -> Option<Value> {
174 if name == "label" {
175 return c.label().map(|l| Value::Label(l.clone()));
176 }
177 match c {
178 // A Typst-internal field is not reachable from code, as in Typst.
179 Content::Elem(e) => match e.kind.field_id(name).and_then(|id| e.kind.field_spec(id)) {
180 Some(spec) if spec.internal => None,
181 _ => c.field(name).cloned(),
182 },
183 Content::Sequence(s) => match name {
184 "children" => Some(Value::array(s.children.iter().cloned().map(Value::Content).collect())),
185 _ => None,
186 },
187 Content::Styled(s) => match name {
188 "child" => Some(Value::Content(s.child.clone())),
189 "styles" => Some(Value::Styles(s.styles.clone())),
190 _ => None,
191 },
192 }
193}
194
195/// `content.fields()`: every stored field in schema order, then the label.
196pub fn content_fields(c: &Content) -> Dict {
197 let mut d = Dict::new();
198 match c {
199 Content::Elem(e) => {
200 let mut fields: Vec<&(FieldId, Value)> = e.fields.iter().collect();
201 fields.sort_by_key(|(id, _)| *id);
202 for (id, v) in fields {
203 match e.kind.field_spec(*id) {
204 Some(spec) if !spec.internal => d.insert(spec.name, v.clone()),
205 _ => (),
206 }
207 }
208 }
209 Content::Sequence(s) => {
210 d.insert("children", Value::array(s.children.iter().cloned().map(Value::Content).collect()));
211 }
212 Content::Styled(s) => {
213 d.insert("child", Value::Content(s.child.clone()));
214 d.insert("styles", Value::Styles(s.styles.clone()));
215 }
216 }
217 if let Some(l) = c.label() {
218 d.insert("label", Value::Label(l.clone()));
219 }
220 d
221}
222
223/// `receiver.name(args)` for a receiver the call does not mutate.
224pub fn call_method(
225 engine: &mut Engine,
226 receiver: Value,
227 name: &str,
228 mut args: Args,
229 span: Span,
230)
231 -> Outcome<Value>
232{
233 if is_mutating(name) && matches!(receiver, Value::Array(_) | Value::Dict(_)) {
234 return Err(engine.error(DiagnosticKind::Syntax, span, "cannot mutate a temporary value"));
235 }
236 match type_method(receiver.ty(), name).or_else(|| element_method(&receiver, name)) {
237 Some(f) => {
238 args.prepend(span, receiver);
239 engine.call_func(&Func::Native(f), args)
240 }
241 None => Err(engine.error(DiagnosticKind::Type, span, fmt!("type {} has no method `{}`", receiver.ty().long_name(), name))),
242 }
243}
244
245/// A function in the scope of the receiver's element, which Typst lets content call as a method after
246/// the content type's own: `it.indented(it.prefix(), it.inner())` on an `outline.entry`.
247pub fn element_method(receiver: &Value, name: &str) -> Option<NativeFunc> {
248 match receiver {
249 Value::Content(Content::Elem(e)) => lib::model::method(e.kind, name).map(NativeFunc::Model),
250 _ => None,
251 }
252}
253
254/// `receiver.name(args)` where the receiver is a place (`arr.push(x)`) and may be changed in it. A
255/// method that does not mutate is passed on to [`call_method`] with a copy.
256pub fn call_method_mut(
257 engine: &mut Engine,
258 receiver: &mut Value,
259 name: &str,
260 args: Args,
261 span: Span,
262)
263 -> Outcome<Value>
264{
265 let out = match receiver {
266 Value::Array(a) if is_mutating(name) => array_mut(Arc::make_mut(a), name, args),
267 Value::Dict(d) if is_mutating(name) => dict_mut(Arc::make_mut(d), name, args),
268 _ => return call_method(engine, receiver.clone(), name, args, span),
269 };
270 match out {
271 Ok(v) => Ok(v),
272 Err(e) => Err(engine.error(DiagnosticKind::Type, span, e.plain())),
273 }
274}
275
276fn index(len: usize, i: i64, allow_end: bool) -> Outcome<usize> {
277 let idx = if i < 0 { len as i64 + i } else { i };
278 let limit = if allow_end { len as i64 } else { len as i64 - 1 };
279 if idx < 0 || idx > limit {
280 return Err(fail(fmt!("array index out of bounds (index: {}, len: {})", i, len)));
281 }
282 Ok(idx as usize)
283}
284
285fn array_mut(a: &mut Vec<Value>, name: &str, mut args: Args) -> Outcome<Value> {
286 let out = match name {
287 "push" => {
288 let v = res!(args.expect::<Value>("value"));
289 a.push(v);
290 Value::None
291 }
292 "pop" => match a.pop() {
293 Some(v) => v,
294 None => return Err(fail("array is empty".to_string())),
295 },
296 "insert" => {
297 let i = res!(args.expect::<i64>("index"));
298 let v = res!(args.expect::<Value>("value"));
299 let at = res!(index(a.len(), i, true));
300 a.insert(at, v);
301 Value::None
302 }
303 _ => {
304 let i = res!(args.expect::<i64>("index"));
305 let default = res!(args.named::<Value>("default"));
306 match (index(a.len(), i, false), default) {
307 (Ok(at), _) => a.remove(at),
308 (Err(_), Some(d)) => d,
309 (Err(_), None) => return Err(fail(fmt!(
310 "array index out of bounds (index: {}, len: {}) and no default value was specified",
311 i, a.len()))),
312 }
313 }
314 };
315 res!(args.finish());
316 Ok(out)
317}
318
319fn dict_mut(d: &mut Dict, name: &str, mut args: Args) -> Outcome<Value> {
320 let out = match name {
321 "insert" => {
322 let k = res!(args.expect::<String>("key"));
323 let v = res!(args.expect::<Value>("value"));
324 d.insert(&k, v);
325 Value::None
326 }
327 "remove" => {
328 let k = res!(args.expect::<String>("key"));
329 let default = res!(args.named::<Value>("default"));
330 match (d.remove(&k), default) {
331 (Some(v), _) => v,
332 (None, Some(v)) => v,
333 (None, None) => return Err(fail(fmt!("dictionary does not contain key \"{}\"", k))),
334 }
335 }
336 other => return Err(fail(fmt!("type dictionary has no method `{}`", other))),
337 };
338 res!(args.finish());
339 Ok(out)
340}