Oregami
Repositories/oxedyne/fe2o3

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

9.7 KiB, 5 runs

created by r1870400018:63512, 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// U4 owns this file: selectors and the `selector` functions and methods. Two casts, as Typst has two:
2// `cast` for `selector(..)`, `query` and the combinators, and `cast_showable` for a `show` rule, which also
3// takes a symbol and refuses what only introspection can answer (a location, `before`, `after`).
4
5use crate::diag::DiagnosticKind;
6use crate::eval::args::Args;
7use crate::eval::content::{
8 self,
9 Content,
10 ElemKind,
11 FieldId,
12};
13use crate::eval::func::Func;
14use crate::eval::locate::Location;
15use crate::eval::ops;
16use crate::eval::styles::StyleChain;
17use crate::eval::value::{
18 Label,
19 RegexValue,
20 Value,
21};
22use crate::eval::Engine;
23use crate::syntax::Span;
24
25use oxedyne_fe2o3_core::prelude::*;
26
27use std::sync::Arc;
28
29#[derive(Clone, Debug)]
30pub enum Selector {
31 Elem(ElemKind, Option<Vec<(FieldId, Value)>>), // `heading`, `heading.where(level: 1)`
32 Label(Label),
33 Text(String), // `show "word"`
34 Regex(Arc<RegexValue>),
35 Location(Location),
36 Or(Vec<Selector>),
37 And(Vec<Selector>),
38 Before { selector: Arc<Selector>, end: Arc<Selector>, inclusive: bool },
39 After { selector: Arc<Selector>, start: Arc<Selector>, inclusive: bool },
40}
41
42impl Selector {
43 /// Does the element match? A `where` field is compared with the element's own value, else the
44 /// chain's (or the schema default without a chain), else the value synthesis gives an `auto` one, as Typst does. Text and regex selectors match
45 /// text runs, which `realise.rs` handles, and `before`/`after` only filter a query; here none of
46 /// them matches an element.
47 pub fn matches(&self, elem: &Content, styles: Option<&StyleChain>) -> Outcome<bool> {
48 match self {
49 Selector::Elem(kind, fields) => {
50 if elem.kind() != Some(*kind) {
51 return Ok(false);
52 }
53 let fields = match fields {
54 Some(f) => f,
55 None => return Ok(true),
56 };
57 let root = StyleChain::root();
58 let chain = styles.unwrap_or(&root);
59 for (id, want) in fields {
60 // A field that only synthesis fills in reads as it will once the element is prepared,
61 // so a rule written for it matches the element before realisation has met it.
62 let have = match res!(chain.resolve(elem, *id)) {
63 Some(Value::Auto) => match res!(content::derived_field(elem, *id, chain)) {
64 Some(v) => Some(v),
65 None => Some(Value::Auto),
66 },
67 // Nothing sets it: the default a field has, as Typst compares it.
68 None => content::default_field(*kind, *id),
69 other => other,
70 };
71 match have {
72 Some(have) if ops::equal(&have, want) => (),
73 _ => return Ok(false),
74 }
75 }
76 Ok(true)
77 }
78 Selector::Label(l) => Ok(elem.label() == Some(l)),
79 Selector::Location(loc) => Ok(elem.location() == Some(*loc)),
80 Selector::Or(ss) => {
81 for s in ss {
82 if res!(s.matches(elem, styles)) {
83 return Ok(true);
84 }
85 }
86 Ok(false)
87 }
88 Selector::And(ss) => {
89 for s in ss {
90 if !res!(s.matches(elem, styles)) {
91 return Ok(false);
92 }
93 }
94 Ok(true)
95 }
96 Selector::Text(_) | Selector::Regex(_) | Selector::Before { .. } | Selector::After { .. } => Ok(false),
97 }
98 }
99
100 /// Can a `show` rule use it? A location, `before` and `after` depend on layout, which a show rule may
101 /// not.
102 pub fn is_showable(&self) -> bool {
103 match self {
104 Selector::Location(_) | Selector::Before { .. } | Selector::After { .. } => false,
105 Selector::Or(ss) | Selector::And(ss) => ss.iter().all(|s| s.is_showable()),
106 _ => true,
107 }
108 }
109
110 /// The first match of a text or regex selector in `text`, as a byte range; `None` for any other
111 /// selector.
112 pub fn find_text(&self, text: &str) -> Outcome<Option<(usize, usize)>> {
113 match self {
114 Selector::Text(t) if !t.is_empty() => Ok(text.find(t.as_str()).map(|i| (i, i + t.len()))),
115 Selector::Regex(re) => Ok(res!(re.re.find(text)).map(|m| (m.start, m.end))),
116 _ => Ok(None),
117 }
118 }
119}
120
121/// A text selector; an empty one is refused.
122fn text_selector(engine: &mut Engine, span: Span, text: &str) -> Outcome<Selector> {
123 if text.is_empty() {
124 return Err(engine.error(DiagnosticKind::Type, span, "text selector is empty"));
125 }
126 Ok(Selector::Text(text.to_string()))
127}
128
129fn func_selector(engine: &mut Engine, span: Span, f: &Func) -> Outcome<Selector> {
130 match f.element() {
131 Some(k) => Ok(Selector::Elem(k, None)),
132 None => Err(engine.error(DiagnosticKind::Type, span, "only element functions can be used as selectors")),
133 }
134}
135
136/// Casts a value to a selector as `selector(..)` and `query` accept it.
137pub fn cast(engine: &mut Engine, span: Span, v: Value) -> Outcome<Selector> {
138 match v {
139 Value::Selector(s) => Ok((*s).clone()),
140 Value::Func(f) => func_selector(engine, span, &f),
141 Value::Label(l) => Ok(Selector::Label(l)),
142 Value::Str(s) => text_selector(engine, span, &s),
143 Value::Regex(r) => Ok(Selector::Regex(r)),
144 Value::Location(l) => Ok(Selector::Location(l)),
145 other => Err(engine.error(DiagnosticKind::Type, span, fmt!(
146 "expected string, function, label, regex, location, or selector, found {}", other.ty().long_name()))),
147 }
148}
149
150/// Casts a value to a selector as a `show` rule accepts it.
151pub fn cast_showable(engine: &mut Engine, span: Span, v: Value) -> Outcome<Selector> {
152 let sel = match v {
153 Value::Selector(s) => (*s).clone(),
154 Value::Func(f) => res!(func_selector(engine, span, &f)),
155 Value::Label(l) => Selector::Label(l),
156 Value::Str(s) => res!(text_selector(engine, span, &s)),
157 Value::Symbol(s) => res!(text_selector(engine, span, &ops::symbol_text(&s))),
158 Value::Regex(r) => Selector::Regex(r),
159 other => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
160 "expected symbol, string, label, function, regex, or selector, found {}", other.ty().long_name()))),
161 };
162 if !sel.is_showable() {
163 return Err(engine.error(DiagnosticKind::Type, span, "this selector cannot be used with show"));
164 }
165 Ok(sel)
166}
167
168native_fns! {
169 pub enum StyleFn {
170 Selector => "selector",
171 Or => "or",
172 And => "and",
173 Before => "before",
174 After => "after",
175 Where => "where",
176 }
177}
178
179/// The selector methods; `where` is the element function's.
180pub fn method(name: &str) -> Option<StyleFn> {
181 match name {
182 "or" => Some(StyleFn::Or),
183 "and" => Some(StyleFn::And),
184 "before" => Some(StyleFn::Before),
185 "after" => Some(StyleFn::After),
186 "where" => Some(StyleFn::Where),
187 _ => None,
188 }
189}
190
191/// Takes the next positional argument, or reports it missing at the call.
192fn take(engine: &mut Engine, args: &mut Args, what: &str) -> Outcome<(Span, Value)> {
193 match args.items.iter().position(|a| a.name.is_none()) {
194 Some(i) => {
195 let a = args.items.remove(i);
196 let span = if a.span.is_detached() { args.span } else { a.span };
197 Ok((span, a.value))
198 }
199 None => Err(engine.error(DiagnosticKind::Type, args.span, fmt!("missing argument: {}", what))),
200 }
201}
202
203fn finish(engine: &mut Engine, args: Args) -> Outcome<()> {
204 match args.items.first() {
205 None => Ok(()),
206 Some(a) => {
207 let span = if a.span.is_detached() { args.span } else { a.span };
208 let msg = match &a.name {
209 Some(n) => fmt!("unexpected argument: {}", n),
210 None => "unexpected argument".to_string(),
211 };
212 Err(engine.error(DiagnosticKind::Type, span, msg))
213 }
214 }
215}
216
217fn inclusive(engine: &mut Engine, args: &mut Args) -> Outcome<bool> {
218 match res!(args.named::<Value>("inclusive")) {
219 None => Ok(true),
220 Some(Value::Bool(b)) => Ok(b),
221 Some(other) => Err(engine.error(DiagnosticKind::Type, args.span, fmt!("expected boolean, found {}", other.ty().long_name()))),
222 }
223}
224
225/// Runs a selector function. A method arrives with its receiver as the first positional argument.
226pub fn call(f: StyleFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> {
227 let sel = match f {
228 StyleFn::Selector => {
229 let (span, v) = res!(take(engine, &mut args, "target"));
230 res!(cast(engine, span, v))
231 }
232 StyleFn::Or | StyleFn::And => {
233 let (span, v) = res!(take(engine, &mut args, "self"));
234 let mut all = vec![res!(cast(engine, span, v))];
235 while args.items.iter().any(|a| a.name.is_none()) {
236 let (span, v) = res!(take(engine, &mut args, "others"));
237 all.push(res!(cast(engine, span, v)));
238 }
239 if f == StyleFn::Or { Selector::Or(all) } else { Selector::And(all) }
240 }
241 StyleFn::Before | StyleFn::After => {
242 let (span, v) = res!(take(engine, &mut args, "self"));
243 let this = Arc::new(res!(cast(engine, span, v)));
244 let what = if f == StyleFn::Before { "end" } else { "start" };
245 let (span, v) = res!(take(engine, &mut args, what));
246 let bound = Arc::new(res!(cast(engine, span, v)));
247 let inclusive = res!(inclusive(engine, &mut args));
248 if f == StyleFn::Before {
249 Selector::Before { selector: this, end: bound, inclusive }
250 } else {
251 Selector::After { selector: this, start: bound, inclusive }
252 }
253 }
254 StyleFn::Where => {
255 let (span, v) = res!(take(engine, &mut args, "self"));
256 let kind = match &v {
257 Value::Func(func) => func.element(),
258 _ => None,
259 };
260 let kind = match kind {
261 Some(k) => k,
262 None => return Err(engine.error(DiagnosticKind::Type, span, "`where()` can only be called on element functions")),
263 };
264 let mut fields = Vec::new();
265 let mut i = 0;
266 while i < args.items.len() {
267 let name = match &args.items[i].name {
268 Some(n) => n.clone(),
269 None => { i += 1; continue; }
270 };
271 let a = args.items.remove(i);
272 let id = match kind.field_id(&name) {
273 Some(id) => id,
274 None => {
275 let span = if a.span.is_detached() { args.span } else { a.span };
276 return Err(engine.error(DiagnosticKind::Type, span, fmt!(
277 "element `{}` does not have field `{}`", kind.name(), name)));
278 }
279 };
280 match fields.iter_mut().find(|(f, _): &&mut (FieldId, Value)| *f == id) {
281 Some(slot) => slot.1 = a.value,
282 None => fields.push((id, a.value)),
283 }
284 }
285 Selector::Elem(kind, Some(fields))
286 }
287 };
288 res!(finish(engine, args));
289 Ok(Value::Selector(Arc::new(sel)))
290}