1use std::collections::BTreeMap;
9use std::rc::Rc;
10use std::sync::Arc;
11
12use super::executor::Executor;
13use super::program::Expr;
14use super::results::{Res, content_start};
15use super::text::column_of;
16
17const SAFE_INTEGER: i64 = (1 << 53) - 1;
19
20#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub enum OperationValue {
23 Integer(i64),
25 Text(String),
27}
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub(super) enum Abort {
32 StepLimit,
33 NestingTooDeep,
34 MemoryBudget,
35 Operation,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub(super) enum OpError {
42 Failed,
44 Abort(Abort),
46}
47
48impl From<Abort> for OpError {
49 fn from(abort: Abort) -> Self {
50 Self::Abort(abort)
51 }
52}
53
54pub(super) type OpResult<T> = Result<T, OpError>;
55
56#[derive(Debug, PartialEq, Eq, Hash)]
59pub(super) struct StateData {
60 pub(super) modes: Vec<Arc<str>>,
61 pub(super) stacks: BTreeMap<Arc<str>, Vec<OperationValue>>,
62 pub(super) variables: BTreeMap<Arc<str>, OperationValue>,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq, Hash)]
67pub(super) struct State(pub(super) Rc<StateData>);
68
69impl State {
70 pub(super) fn initial() -> Self {
72 Self(Rc::new(StateData {
73 modes: vec![Arc::from("default")],
74 stacks: BTreeMap::new(),
75 variables: BTreeMap::new(),
76 }))
77 }
78
79 pub(super) fn mode(&self) -> &str {
81 self.0.modes.last().map_or("default", |mode| mode)
82 }
83
84 pub(super) fn working(&self) -> Working {
86 Working {
87 modes: self.0.modes.clone(),
88 stacks: self.0.stacks.clone(),
89 variables: self.0.variables.clone(),
90 }
91 }
92}
93
94#[derive(Clone, Debug)]
96pub(super) struct Working {
97 pub(super) modes: Vec<Arc<str>>,
98 pub(super) stacks: BTreeMap<Arc<str>, Vec<OperationValue>>,
99 pub(super) variables: BTreeMap<Arc<str>, OperationValue>,
100}
101
102impl Working {
103 pub(super) fn settle(self) -> State {
105 let mut stacks = self.stacks;
106 stacks.retain(|_, values| !values.is_empty());
107 State(Rc::new(StateData {
108 modes: self.modes,
109 stacks,
110 variables: self.variables,
111 }))
112 }
113}
114
115#[derive(Debug)]
117pub(super) enum ValueOp {
118 Integer(i64),
119 Text(String),
120 Variable(Arc<str>),
121 Top(Arc<str>),
122 Depth(Arc<str>),
123 Column,
124 Matched,
125 Mode,
126 Attribute(String, String),
127 SumOf(String, String),
128 FieldText(String),
129 Length(Box<Self>),
130 Uppercase(Box<Self>),
131 Number(Box<Self>),
132 Add(Box<Self>, Box<Self>),
133 Subtract(Box<Self>, Box<Self>),
134 Multiply(Box<Self>, Box<Self>),
135}
136
137#[derive(Debug)]
139pub(super) enum Condition {
140 Valid(Arc<str>),
141 Expected(usize),
144 Next(Expr),
145 AtEnd,
146 Equal(ValueOp, ValueOp),
147 Less(ValueOp, ValueOp),
148 Greater(ValueOp, ValueOp),
149 All(Vec<Self>),
150 Some(Vec<Self>),
151 Not(Box<Self>),
152}
153
154#[derive(Debug)]
156pub(super) enum Statement {
157 Advance,
158 Consume(Expr),
159 Skip(Expr),
160 Mark,
161 Emit(Arc<str>),
162 Fail,
163 If(Condition, Vec<Self>, Option<Vec<Self>>),
164 While(Condition, Vec<Self>),
165 Push(Arc<str>, ValueOp),
166 Pop(Arc<str>),
167 Set(Arc<str>, ValueOp),
168 PushMode(Arc<str>),
169 PopMode,
170 SetMode(Arc<str>),
171 SetAttribute(String, ValueOp),
172 BuildNode(Arc<str>),
173}
174
175pub(super) trait Machine {
179 fn state(&mut self) -> &mut Working;
180 fn step(&mut self) -> Result<(), Abort>;
181 fn requested(&self) -> Option<&str> {
182 None
183 }
184 fn expected(&mut self, _id: usize) -> bool {
185 false
186 }
187 fn column(&mut self) -> usize;
188 fn at_end(&mut self) -> bool;
189 fn matched(&mut self) -> OpResult<String> {
190 Err(OpError::Failed)
191 }
192 fn lookahead(&mut self, _item: &Expr) -> OpResult<bool> {
193 Ok(false)
194 }
195 fn attribute(&mut self, _field: &str, _name: &str) -> OpResult<OperationValue> {
196 Err(OpError::Failed)
197 }
198 fn attributes(&mut self, _field: &str, _name: &str) -> OpResult<Vec<OperationValue>> {
199 Err(OpError::Failed)
200 }
201 fn field_text(&mut self, _field: &str) -> OpResult<String> {
202 Err(OpError::Failed)
203 }
204 fn advance(&mut self) -> OpResult<()> {
205 Err(OpError::Failed)
206 }
207 fn consume(&mut self, _item: &Expr) -> OpResult<()> {
208 Err(OpError::Failed)
209 }
210 fn skip(&mut self, _item: &Expr) -> OpResult<()> {
211 Err(OpError::Failed)
212 }
213 fn mark(&mut self) {}
214 fn set_attribute(&mut self, _name: &str, _value: OperationValue) {}
215 fn build_node(&mut self, _kind: &Arc<str>) {}
216}
217
218const fn integer(value: &OperationValue) -> OpResult<i64> {
219 match value {
220 OperationValue::Integer(value) => Ok(*value),
221 OperationValue::Text(_) => Err(OpError::Failed),
222 }
223}
224
225fn checked(value: Option<i64>) -> OpResult<OperationValue> {
226 match value {
227 Some(value) if (-SAFE_INTEGER..=SAFE_INTEGER).contains(&value) => {
228 Ok(OperationValue::Integer(value))
229 }
230 _ => Err(OpError::Failed),
231 }
232}
233
234fn to_integer(value: usize) -> OperationValue {
235 OperationValue::Integer(i64::try_from(value).unwrap_or(i64::MAX))
236}
237
238fn arithmetic(
239 left: &ValueOp,
240 right: &ValueOp,
241 machine: &mut dyn Machine,
242 combine: fn(i64, i64) -> Option<i64>,
243) -> OpResult<OperationValue> {
244 let left = integer(&evaluate_value(left, machine)?)?;
245 let right = integer(&evaluate_value(right, machine)?)?;
246 checked(combine(left, right))
247}
248
249fn is_number_text(text: &str) -> bool {
250 let digits = text.strip_prefix('-').unwrap_or(text);
251 (1..=15).contains(&digits.len()) && digits.bytes().all(|byte| byte.is_ascii_digit())
252}
253
254pub(super) fn evaluate_value(
256 value: &ValueOp,
257 machine: &mut dyn Machine,
258) -> OpResult<OperationValue> {
259 machine.step()?;
260 Ok(match value {
261 ValueOp::Integer(value) => OperationValue::Integer(*value),
262 ValueOp::Text(value) => OperationValue::Text(value.clone()),
263 ValueOp::Variable(name) => machine
264 .state()
265 .variables
266 .get(name)
267 .cloned()
268 .unwrap_or(OperationValue::Integer(0)),
269 ValueOp::Top(stack) => machine
270 .state()
271 .stacks
272 .get(stack)
273 .and_then(|values| values.last().cloned())
274 .unwrap_or(OperationValue::Integer(0)),
275 ValueOp::Depth(stack) => to_integer(machine.state().stacks.get(stack).map_or(0, Vec::len)),
276 ValueOp::Column => to_integer(machine.column()),
277 ValueOp::Matched => OperationValue::Text(machine.matched()?),
278 ValueOp::Mode => OperationValue::Text(
279 machine
280 .state()
281 .modes
282 .last()
283 .map_or_else(String::new, std::string::ToString::to_string),
284 ),
285 ValueOp::Attribute(field, name) => machine.attribute(field, name)?,
286 ValueOp::SumOf(field, name) => {
287 let mut sum = OperationValue::Integer(0);
288 for item in machine.attributes(field, name)? {
289 sum = checked(integer(&sum)?.checked_add(integer(&item)?))?;
290 }
291 sum
292 }
293 ValueOp::FieldText(field) => OperationValue::Text(machine.field_text(field)?),
294 ValueOp::Uppercase(inner) => match evaluate_value(inner, machine)? {
295 OperationValue::Text(text) => OperationValue::Text(
296 text.chars()
297 .map(|character| {
298 let mut upper = character.to_uppercase();
299 let first = upper.next().unwrap_or(character);
300 if upper.next().is_none() {
301 first
302 } else {
303 character
304 }
305 })
306 .collect(),
307 ),
308 OperationValue::Integer(_) => return Err(OpError::Failed),
309 },
310 ValueOp::Length(inner) => match evaluate_value(inner, machine)? {
311 OperationValue::Text(text) => to_integer(text.chars().count()),
312 OperationValue::Integer(_) => return Err(OpError::Failed),
313 },
314 ValueOp::Number(inner) => match evaluate_value(inner, machine)? {
315 number @ OperationValue::Integer(_) => number,
316 OperationValue::Text(text) => {
317 if !is_number_text(&text) {
318 return Err(OpError::Failed);
319 }
320 OperationValue::Integer(text.parse().map_err(|_| OpError::Failed)?)
321 }
322 },
323 ValueOp::Add(left, right) => arithmetic(left, right, machine, i64::checked_add)?,
324 ValueOp::Subtract(left, right) => arithmetic(left, right, machine, i64::checked_sub)?,
325 ValueOp::Multiply(left, right) => arithmetic(left, right, machine, i64::checked_mul)?,
326 })
327}
328
329pub(super) fn evaluate_condition(
331 condition: &Condition,
332 machine: &mut dyn Machine,
333) -> OpResult<bool> {
334 machine.step()?;
335 Ok(match condition {
336 Condition::Valid(token) => machine.requested() == Some(&**token),
337 Condition::Expected(id) => machine.expected(*id),
338 Condition::Next(item) => machine.lookahead(item)?,
339 Condition::AtEnd => machine.at_end(),
340 Condition::Equal(left, right) => {
341 let left = evaluate_value(left, machine)?;
342 let right = evaluate_value(right, machine)?;
343 left == right
344 }
345 Condition::Less(left, right) => {
346 let left = integer(&evaluate_value(left, machine)?)?;
347 left < integer(&evaluate_value(right, machine)?)?
348 }
349 Condition::Greater(left, right) => {
350 let left = integer(&evaluate_value(left, machine)?)?;
351 left > integer(&evaluate_value(right, machine)?)?
352 }
353 Condition::All(items) => {
354 for item in items {
355 if !evaluate_condition(item, machine)? {
356 return Ok(false);
357 }
358 }
359 true
360 }
361 Condition::Some(items) => {
362 for item in items {
363 if evaluate_condition(item, machine)? {
364 return Ok(true);
365 }
366 }
367 false
368 }
369 Condition::Not(inner) => !evaluate_condition(inner, machine)?,
370 })
371}
372
373pub(super) fn run_statements(
376 statements: &[Statement],
377 machine: &mut dyn Machine,
378) -> OpResult<Option<Arc<str>>> {
379 for statement in statements {
380 machine.step()?;
381 match statement {
382 Statement::Advance => machine.advance()?,
383 Statement::Consume(item) => machine.consume(item)?,
384 Statement::Skip(item) => machine.skip(item)?,
385 Statement::Mark => machine.mark(),
386 Statement::Emit(token) => return Ok(Some(token.clone())),
387 Statement::Fail => return Err(OpError::Failed),
388 Statement::If(condition, consequent, alternative) => {
389 let branch = if evaluate_condition(condition, machine)? {
390 Some(consequent)
391 } else {
392 alternative.as_ref()
393 };
394 if let Some(branch) = branch
395 && let Some(signal) = run_statements(branch, machine)?
396 {
397 return Ok(Some(signal));
398 }
399 }
400 Statement::While(condition, body) => {
401 while evaluate_condition(condition, machine)? {
402 if let Some(signal) = run_statements(body, machine)? {
403 return Ok(Some(signal));
404 }
405 }
406 }
407 Statement::Push(stack, value) => {
408 let value = evaluate_value(value, machine)?;
409 machine
410 .state()
411 .stacks
412 .entry(stack.clone())
413 .or_default()
414 .push(value);
415 }
416 Statement::Pop(stack) => {
417 let popped = machine.state().stacks.get_mut(stack).and_then(Vec::pop);
418 if popped.is_none() {
419 return Err(OpError::Failed);
420 }
421 }
422 Statement::Set(variable, value) => {
423 let value = evaluate_value(value, machine)?;
424 machine.state().variables.insert(variable.clone(), value);
425 }
426 Statement::PushMode(mode) => machine.state().modes.push(mode.clone()),
427 Statement::PopMode => {
428 let modes = &mut machine.state().modes;
429 if modes.len() <= 1 {
430 return Err(OpError::Failed);
431 }
432 modes.pop();
433 }
434 Statement::SetMode(mode) => {
435 if let Some(last) = machine.state().modes.last_mut() {
436 *last = mode.clone();
437 }
438 }
439 Statement::SetAttribute(name, value) => {
440 let value = evaluate_value(value, machine)?;
441 machine.set_attribute(name, value);
442 }
443 Statement::BuildNode(kind) => machine.build_node(kind),
444 }
445 }
446 Ok(None)
447}
448
449pub(super) fn allowed_in(context: &str, operation: &str) -> bool {
451 const COMMON: &[&str] = &[
452 "if",
453 "while",
454 "push",
455 "pop",
456 "set",
457 "pushMode",
458 "popMode",
459 "setMode",
460 "atEnd",
461 "equal",
462 "less",
463 "greater",
464 "all",
465 "some",
466 "not",
467 "integer",
468 "text",
469 "variable",
470 "top",
471 "depth",
472 "column",
473 "mode",
474 "length",
475 "uppercase",
476 "number",
477 "add",
478 "subtract",
479 "multiply",
480 ];
481 const SCANNER: &[&str] = &[
482 "advance", "consume", "skip", "mark", "emit", "fail", "valid", "expected", "next",
483 "matched",
484 ];
485 const ACTION: &[&str] = &[
486 "fail",
487 "setAttribute",
488 "buildNode",
489 "matched",
490 "attribute",
491 "sumOf",
492 "fieldText",
493 ];
494 const PREDICATE: &[&str] = &[
495 "atEnd",
496 "equal",
497 "less",
498 "greater",
499 "all",
500 "some",
501 "not",
502 "integer",
503 "text",
504 "variable",
505 "top",
506 "depth",
507 "column",
508 "matched",
509 "mode",
510 "length",
511 "uppercase",
512 "number",
513 "add",
514 "subtract",
515 "multiply",
516 ];
517 match context {
518 "scanner" => COMMON.contains(&operation) || SCANNER.contains(&operation),
519 "action" => COMMON.contains(&operation) || ACTION.contains(&operation),
520 _ => PREDICATE.contains(&operation),
521 }
522}
523
524pub(super) struct ValueMachine<'e, 'c> {
526 executor: &'e mut Executor<'c>,
527 working: Working,
528 start: usize,
529 end: usize,
530}
531
532impl<'e, 'c> ValueMachine<'e, 'c> {
533 pub(super) fn new(executor: &'e mut Executor<'c>, result: &Res, from: usize) -> Self {
534 Self {
535 start: content_start(&result.children, from),
536 end: result.end,
537 working: result.state.working(),
538 executor,
539 }
540 }
541}
542
543impl Machine for ValueMachine<'_, '_> {
544 fn state(&mut self) -> &mut Working {
545 &mut self.working
546 }
547
548 fn step(&mut self) -> Result<(), Abort> {
549 self.executor.step()
550 }
551
552 fn column(&mut self) -> usize {
553 column_of(self.executor.bytes, self.start, self.executor.begin)
554 }
555
556 fn at_end(&mut self) -> bool {
557 self.end == self.executor.end
558 }
559
560 fn matched(&mut self) -> OpResult<String> {
561 Ok(self.executor.text(self.start, self.end))
562 }
563}