1use std::collections::HashMap;
40
41use crate::error::{Error, Result};
42
43#[derive(Debug, Clone, PartialEq)]
45pub enum Value {
46 Num(f64),
47 Str(String),
48}
49
50impl Value {
51 fn num(&self, line: usize) -> Result<f64> {
52 match self {
53 Value::Num(x) => Ok(*x),
54 Value::Str(_) => Err(err(line, "a string where a number is needed")),
55 }
56 }
57 fn str(&self, line: usize) -> Result<&str> {
58 match self {
59 Value::Str(s) => Ok(s),
60 Value::Num(_) => Err(err(line, "a number where a string is needed")),
61 }
62 }
63}
64
65pub trait Host {
67 fn function(&mut self, name: &str, args: &[Value]) -> Option<Result<Value>>;
69 fn command(&mut self, name: &str, args: &[Value]) -> Option<Result<Flow>>;
71}
72
73#[derive(Debug, Clone, PartialEq)]
75pub enum Flow {
76 Go,
78 Abort(String),
80}
81
82pub struct NoHost;
84impl Host for NoHost {
85 fn function(&mut self, _: &str, _: &[Value]) -> Option<Result<Value>> {
86 None
87 }
88 fn command(&mut self, _: &str, _: &[Value]) -> Option<Result<Flow>> {
89 None
90 }
91}
92
93fn err(line: usize, e: impl std::fmt::Display) -> Error {
94 Error::Invalid(format!("ZPL line {line}: {e}"))
95}
96fn unsupported(line: usize, e: impl std::fmt::Display) -> Error {
97 Error::NotImplemented(format!("ZPL line {line}: {e}"))
98}
99
100#[derive(Debug, Clone, PartialEq)]
103enum Tok {
104 Num(f64),
105 Str(String),
106 Id(String),
108 Op(&'static str),
110}
111
112const OPS: [&str; 15] = [
113 "==", "!=", "<=", ">=", "+", "-", "*", "/", "(", ")", ",", "=", "<", ">", "!",
114];
115
116fn lex(src: &str, line: usize) -> Result<Vec<Tok>> {
117 let c: Vec<char> = src.chars().collect();
118 let mut out = vec![];
119 let mut i = 0;
120 while i < c.len() {
121 let ch = c[i];
122 if ch.is_whitespace() {
123 i += 1;
124 } else if ch == '#' {
125 break; } else if ch == '"' {
127 let j = (i + 1..c.len())
128 .find(|&j| c[j] == '"')
129 .ok_or_else(|| err(line, "the string is not closed"))?;
130 out.push(Tok::Str(c[i + 1..j].iter().collect()));
131 i = j + 1;
132 } else if ch.is_ascii_digit()
133 || (ch == '.' && c.get(i + 1).is_some_and(|d| d.is_ascii_digit()))
134 {
135 let mut j = i;
136 while j < c.len() && (c[j].is_ascii_digit() || c[j] == '.') {
137 j += 1;
138 }
139 if j < c.len() && (c[j] == 'e' || c[j] == 'E') {
140 let k = j + 1 + usize::from(c.get(j + 1).is_some_and(|s| *s == '+' || *s == '-'));
141 if c.get(k).is_some_and(|d| d.is_ascii_digit()) {
142 j = k;
143 while j < c.len() && c[j].is_ascii_digit() {
144 j += 1;
145 }
146 }
147 }
148 let s: String = c[i..j].iter().collect();
149 out.push(Tok::Num(
150 s.parse().map_err(|_| err(line, format!("number {s}")))?,
151 ));
152 i = j;
153 } else if ch.is_alphabetic() || ch == '_' || ch == '$' {
154 let mut j = i + 1;
155 while j < c.len() && (c[j].is_alphanumeric() || c[j] == '_') {
156 j += 1;
157 }
158 if j < c.len() && c[j] == '$' {
159 j += 1;
160 }
161 out.push(Tok::Id(c[i..j].iter().collect::<String>().to_uppercase()));
162 i = j;
163 } else if ch == '&' || ch == '|' || ch == '^' {
164 out.push(Tok::Op(match ch {
165 '&' => "&",
166 '|' => "|",
167 _ => "^",
168 }));
169 i += 1;
170 } else {
171 let rest: String = c[i..(i + 2).min(c.len())].iter().collect();
172 let op = OPS
173 .iter()
174 .find(|o| rest.starts_with(**o))
175 .ok_or_else(|| err(line, format!("character {ch:?}")))?;
176 out.push(Tok::Op(op));
177 i += op.len();
178 }
179 }
180 Ok(out)
181}
182
183#[derive(Debug, Clone, PartialEq)]
186enum Expr {
187 Lit(Value),
188 Var(String),
189 Call(String, Vec<Expr>),
190 Neg(Box<Expr>),
191 Not(Box<Expr>),
192 Bin(&'static str, Box<Expr>, Box<Expr>),
193}
194
195fn prec(op: &str) -> Option<u8> {
197 Some(match op {
198 "|" | "^" | "&" | "==" | "!=" | "<" | ">" | "<=" | ">=" => 1,
200 "+" | "-" => 2,
201 "*" | "/" => 3,
202 _ => return None,
203 })
204}
205
206struct Parser<'a> {
207 t: &'a [Tok],
208 i: usize,
209 line: usize,
210 depth: usize,
212}
213
214const MAX_EXPR_DEPTH: usize = 200;
216
217impl Parser<'_> {
218 fn peek(&self) -> Option<&Tok> {
219 self.t.get(self.i)
220 }
221 fn is_op(&self, op: &str) -> bool {
222 matches!(self.peek(), Some(Tok::Op(o)) if *o == op)
223 }
224 fn eat_op(&mut self, op: &str) -> bool {
225 let y = self.is_op(op);
226 self.i += usize::from(y);
227 y
228 }
229 fn expect_op(&mut self, op: &str) -> Result<()> {
230 if self.eat_op(op) {
231 Ok(())
232 } else {
233 Err(err(self.line, format!("{op} is needed")))
234 }
235 }
236 fn done(&self) -> bool {
237 self.i >= self.t.len()
238 }
239
240 fn expr(&mut self, min: u8) -> Result<Expr> {
241 self.depth += 1;
242 if self.depth > MAX_EXPR_DEPTH {
243 return Err(err(
244 self.line,
245 format!("expressions nested too deep (up to {MAX_EXPR_DEPTH})"),
246 ));
247 }
248 let r = self.expr_in(min);
249 self.depth -= 1;
250 r
251 }
252
253 fn expr_in(&mut self, min: u8) -> Result<Expr> {
254 let mut l = self.unary()?;
255 while let Some((op, p)) = match self.peek() {
256 Some(Tok::Op(o)) => prec(o).filter(|p| *p >= min).map(|p| (*o, p)),
257 _ => None,
258 } {
259 self.i += 1;
260 let r = self.expr(p + 1)?;
261 l = Expr::Bin(op, Box::new(l), Box::new(r));
262 }
263 Ok(l)
264 }
265
266 fn unary(&mut self) -> Result<Expr> {
267 self.depth += 1;
268 if self.depth > MAX_EXPR_DEPTH {
269 return Err(err(
270 self.line,
271 format!("expressions nested too deep (up to {MAX_EXPR_DEPTH})"),
272 ));
273 }
274 let r = self.unary_in();
275 self.depth -= 1;
276 r
277 }
278
279 fn unary_in(&mut self) -> Result<Expr> {
280 if self.eat_op("-") {
281 return Ok(Expr::Neg(Box::new(self.unary()?)));
282 }
283 if self.eat_op("+") {
284 return self.unary();
285 }
286 if self.eat_op("!") {
287 return Ok(Expr::Not(Box::new(self.unary()?)));
288 }
289 let line = self.line;
290 match self.t.get(self.i).cloned() {
291 Some(Tok::Num(x)) => {
292 self.i += 1;
293 Ok(Expr::Lit(Value::Num(x)))
294 }
295 Some(Tok::Str(s)) => {
296 self.i += 1;
297 Ok(Expr::Lit(Value::Str(s)))
298 }
299 Some(Tok::Op("(")) => {
300 self.i += 1;
301 let e = self.expr(0)?;
302 self.expect_op(")")?;
303 Ok(e)
304 }
305 Some(Tok::Id(name)) => {
306 self.i += 1;
307 if self.eat_op("(") {
308 let mut args = vec![];
309 if !self.eat_op(")") {
310 loop {
311 args.push(self.expr(0)?);
312 if self.eat_op(")") {
313 break;
314 }
315 self.expect_op(",")?;
316 }
317 }
318 Ok(Expr::Call(name, args))
319 } else {
320 Ok(Expr::Var(name))
321 }
322 }
323 Some(t) => Err(err(line, format!("{t:?} in the middle of an expression"))),
324 None => Err(err(line, "an expression is needed")),
325 }
326 }
327
328 fn list(&mut self) -> Result<Vec<Expr>> {
330 let mut v = vec![];
331 if self.done() {
332 return Ok(v);
333 }
334 loop {
335 v.push(self.expr(0)?);
336 if !self.eat_op(",") {
337 break;
338 }
339 }
340 Ok(v)
341 }
342
343 fn end(&self) -> Result<()> {
344 match self.peek() {
345 None => Ok(()),
346 Some(t) => Err(err(
347 self.line,
348 format!("extra {t:?} at the end of the line"),
349 )),
350 }
351 }
352}
353
354#[derive(Debug, Clone, PartialEq)]
357enum Op {
358 Assign(String, Expr),
359 JumpIfNot(Expr, usize),
361 Jump(usize),
362 ForInit(String, Expr, Expr, Expr, usize),
364 ForNext(usize, usize),
366 Gosub(String),
367 Return,
368 End,
369 FallIntoSub,
371 SolveReturn(Expr),
372 Command(String, Vec<Expr>),
373 Nop,
374 Fail(Error),
376}
377
378enum Stop {
380 Err(Error),
382 Keep(Error),
384 Abort(Error),
386 Limit(Error),
388}
389
390impl From<Error> for Stop {
391 fn from(e: Error) -> Stop {
392 Stop::Err(e)
393 }
394}
395
396#[derive(Debug, Clone, PartialEq)]
398pub struct Outcome {
399 pub value: Option<f64>,
401 pub error: Option<String>,
403}
404
405#[derive(Debug, Clone)]
407pub struct Program {
408 ops: Vec<Op>,
409 lines: Vec<usize>,
411 labels: HashMap<String, usize>,
412 subs: HashMap<String, usize>,
413 nfor: usize,
414}
415
416const IGNORED: [&str; 4] = ["PRINT", "FORMAT", "BEEP", "PAUSE"];
418
419impl Program {
420 pub fn parse(src: &str) -> Result<Program> {
422 Program::parse_inner(src, true)
423 }
424
425 fn parse_inner(src: &str, resolve: bool) -> Result<Program> {
427 let mut p = Program {
428 ops: vec![],
429 lines: vec![],
430 labels: HashMap::new(),
431 subs: HashMap::new(),
432 nfor: 0,
433 };
434 enum Open {
436 If(usize, Option<usize>),
437 For(String, usize, usize),
438 }
439 let mut open: Vec<Open> = vec![];
440 for (k, raw) in src.lines().enumerate() {
441 let line = k + 1;
442 let s = raw.trim();
443 if s.is_empty() || s.starts_with('!') {
444 continue;
445 }
446 let at0 = p.ops.len();
447 let r = (|| -> Result<()> {
448 let t = lex(s, line)?;
449 let Some(Tok::Id(head)) = t.first().cloned() else {
450 if t.is_empty() {
451 return Ok(());
452 }
453 return Err(err(line, "a line must start with a name"));
454 };
455 if head == "REM" {
456 return Ok(());
457 }
458 let mut ps = Parser {
459 t: &t,
460 i: 1,
461 line,
462 depth: 0,
463 };
464 let at = p.ops.len();
465 let push = |p: &mut Program, op: Op| {
466 p.ops.push(op);
467 p.lines.push(line);
468 };
469 if ps.is_op("=") {
470 ps.i += 1;
471 let e = ps.expr(0)?;
472 ps.end()?;
473 push(&mut p, Op::Assign(head, e));
474 return Ok(());
475 }
476 match head.as_str() {
477 "IF" => {
478 let then = t.iter().position(|x| *x == Tok::Id("THEN".into()));
479 match then {
480 Some(j) => {
481 let c = Parser {
483 t: &t[..j],
484 i: 1,
485 line,
486 depth: 0,
487 }
488 .whole()?;
489 let body =
490 &s[then_offset(s).ok_or_else(|| err(line, "after THEN"))?..];
491 let sub = Program::parse_inner(body, false)
492 .map_err(|e| e.at(format!("ZPL line {line} after THEN")))?;
493 if sub.ops.len() != 1
494 || !sub.labels.is_empty()
495 || !sub.subs.is_empty()
496 || sub.nfor > 0
497 {
498 return Err(err(line, "only one statement after THEN"));
499 }
500 push(&mut p, Op::JumpIfNot(c, at + 2));
501 let op = sub
502 .ops
503 .into_iter()
504 .next()
505 .expect("one statement checked above");
506 if matches!(op, Op::JumpIfNot(..)) {
507 return Err(unsupported(line, "IF after THEN"));
508 }
509 push(&mut p, op);
510 }
511 None => {
512 let c = ps.expr(0)?;
513 ps.end()?;
514 push(&mut p, Op::JumpIfNot(c, usize::MAX));
515 open.push(Open::If(at, None));
516 }
517 }
518 }
519 "ELSE" => {
520 ps.end()?;
521 match open.last_mut() {
522 Some(Open::If(j, e @ None)) => {
523 let j = *j;
524 *e = Some(at);
525 push(&mut p, Op::Jump(usize::MAX));
526 p.ops[j] = match p.ops[j].clone() {
527 Op::JumpIfNot(c, _) => Op::JumpIfNot(c, at + 1),
528 o => o,
529 };
530 }
531 _ => return Err(err(line, "ELSE without a matching IF")),
532 }
533 }
534 "ENDIF" => {
535 ps.end()?;
536 match open.pop() {
537 Some(Open::If(j, e)) => {
538 match e {
539 Some(e) => p.ops[e] = Op::Jump(at),
540 None => {
541 if let Op::JumpIfNot(c, _) = p.ops[j].clone() {
542 p.ops[j] = Op::JumpIfNot(c, at);
543 }
544 }
545 }
546 push(&mut p, Op::Nop);
547 }
548 _ => return Err(err(line, "ENDIF without a matching IF")),
549 }
550 }
551 "FOR" => {
552 let v = match ps.t.get(1) {
553 Some(Tok::Id(v)) if !v.ends_with('$') => v.clone(),
554 _ => {
555 return Err(err(line, "FOR must be followed by a number variable"))
556 }
557 };
558 ps.i = 2;
559 ps.expect_op(",")?;
560 let a = ps.list()?;
561 ps.end()?;
562 let [a, b, c]: [Expr; 3] = a
563 .try_into()
564 .map_err(|_| err(line, "FOR variable, start, end, step"))?;
565 let n = p.nfor;
566 p.nfor += 1;
567 push(&mut p, Op::ForInit(v.clone(), a, b, c, n));
568 open.push(Open::For(v, n, at + 1));
569 }
570 "NEXT" => {
571 match open.pop() {
573 Some(Open::For(v, n, body)) => {
574 match ps.t.get(1) {
575 None => {}
576 Some(Tok::Id(w)) if *w == v && ps.t.len() == 2 => {}
577 _ => {
578 return Err(err(
579 line,
580 format!("NEXT must be followed by {v}"),
581 ))
582 }
583 }
584 push(&mut p, Op::ForNext(n, body));
585 }
586 _ => return Err(err(line, "NEXT without a matching FOR")),
587 }
588 }
589 "LABEL" | "GOTO" | "GOSUB" | "SUB" => {
590 let name = match (&t.get(1), t.len()) {
591 (Some(Tok::Id(x)), 2) => x.clone(),
592 (Some(Tok::Num(x)), 2) => format!("{x}"),
593 _ => {
594 return Err(err(
595 line,
596 format!("{head} must be followed by one name or number"),
597 ))
598 }
599 };
600 match head.as_str() {
601 "LABEL" => {
602 if p.labels.insert(name.clone(), at).is_some() {
603 return Err(err(line, format!("label {name} appears twice")));
604 }
605 push(&mut p, Op::Nop);
606 }
607 "SUB" => {
608 if !open.is_empty() {
609 return Err(err(line, "SUB inside IF or FOR"));
610 }
611 if p.subs.insert(name.clone(), at + 1).is_some() {
612 return Err(err(line, format!("SUB {name} appears twice")));
613 }
614 push(&mut p, Op::FallIntoSub);
615 }
616 "GOTO" => push(&mut p, Op::Jump(usize::MAX - 1)),
617 _ => push(&mut p, Op::Gosub(name.clone())),
618 }
619 if head == "GOTO" {
620 p.pending_goto(at, name);
622 }
623 }
624 "RETURN" => {
625 ps.end()?;
626 push(&mut p, Op::Return);
627 }
628 "END" => {
629 ps.end()?;
630 push(&mut p, Op::End);
631 }
632 "SOLVERETURN" => {
633 let e = ps.expr(0)?;
634 ps.end()?;
635 push(&mut p, Op::SolveReturn(e));
636 }
637 h if IGNORED.contains(&h) => push(&mut p, Op::Nop),
638 _ => {
639 let a = ps.list()?;
640 ps.end()?;
641 push(&mut p, Op::Command(head, a));
642 }
643 }
644 Ok(())
645 })();
646 if let Err(e) = r {
647 p.ops.truncate(at0);
649 p.lines.truncate(at0);
650 p.ops.push(Op::Fail(e));
651 p.lines.push(line);
652 }
653 }
654 if resolve {
656 p.resolve_gotos()?;
657 }
658 Ok(p)
659 }
660
661 fn pending_goto(&mut self, at: usize, name: String) {
662 self.ops[at] = Op::Command(format!("\u{0}GOTO {name}"), vec![]);
664 }
665
666 fn resolve_gotos(&mut self) -> Result<()> {
667 for k in 0..self.ops.len() {
668 if let Op::Command(c, _) = &self.ops[k] {
669 if let Some(name) = c.strip_prefix("\u{0}GOTO ") {
670 self.ops[k] = match self.labels.get(name) {
671 Some(&to) => Op::Jump(to),
672 None => Op::Fail(err(self.lines[k], format!("no label {name}"))),
673 };
674 }
675 }
676 }
677 for k in 0..self.ops.len() {
678 if let Op::Gosub(n) = &self.ops[k] {
679 if !self.subs.contains_key(n) {
680 self.ops[k] = Op::Fail(err(self.lines[k], format!("no SUB {n}")));
681 }
682 }
683 }
684 Ok(())
685 }
686
687 pub fn run(&self, host: &mut dyn Host, vars: &mut Vars) -> Result<Option<f64>> {
689 let mut ret = None;
690 match self.exec(host, vars, &mut ret) {
691 Ok(()) => Ok(ret),
692 Err(Stop::Err(e) | Stop::Keep(e) | Stop::Abort(e) | Stop::Limit(e)) => Err(e),
693 }
694 }
695
696 pub fn run_term(&self, host: &mut dyn Host, vars: &mut Vars) -> Result<()> {
699 let mut ret = None;
700 match self.exec(host, vars, &mut ret) {
701 Ok(()) | Err(Stop::Abort(_)) => Ok(()),
702 Err(Stop::Err(e) | Stop::Keep(e) | Stop::Limit(e)) => Err(e),
703 }
704 }
705
706 pub fn solve(&self, host: &mut dyn Host) -> Result<Outcome> {
710 let mut ret = None;
711 let r = self.exec(host, &mut Vars::default(), &mut ret);
712 let fin = |v: Option<f64>| v.filter(|x| x.is_finite());
713 Ok(match r {
714 Ok(()) => Outcome {
715 value: fin(ret),
716 error: None,
717 },
718 Err(
719 Stop::Err(e @ Error::NotImplemented(_))
720 | Stop::Keep(e @ Error::NotImplemented(_))
721 | Stop::Abort(e @ Error::NotImplemented(_))
722 | Stop::Limit(e),
723 ) => return Err(e),
724 Err(Stop::Err(e)) => Outcome {
725 value: fin(Some(ret.unwrap_or(0.0))),
726 error: Some(e.to_string()),
727 },
728 Err(Stop::Keep(e) | Stop::Abort(e)) => Outcome {
729 value: None,
730 error: Some(e.to_string()),
731 },
732 })
733 }
734
735 fn exec(
736 &self,
737 host: &mut dyn Host,
738 vars: &mut Vars,
739 ret: &mut Option<f64>,
740 ) -> std::result::Result<(), Stop> {
741 const MAX_STEPS: usize = 5_000_000;
744 #[cfg(not(target_arch = "wasm32"))]
745 const MAX_SECS: f64 = 2.0;
746 #[cfg(not(target_arch = "wasm32"))]
747 let t0 = std::time::Instant::now();
748 const MAX_DEPTH: usize = 100;
749 let mut pc = 0;
750 let mut stack: Vec<usize> = vec![];
751 let mut fors: Vec<(f64, f64, i8)> = vec![(0.0, 0.0, 0); self.nfor];
753 let mut steps = 0;
754 while pc < self.ops.len() {
755 steps += 1;
756 let line = self.lines[pc];
757 if steps > MAX_STEPS {
758 return Err(Stop::Limit(err(
759 line,
760 format!("over {MAX_STEPS} statements (an endless loop?)"),
761 )));
762 }
763 #[cfg(not(target_arch = "wasm32"))]
764 if steps % 4096 == 0 && t0.elapsed().as_secs_f64() > MAX_SECS {
765 return Err(Stop::Limit(err(
766 line,
767 format!("over {MAX_SECS} seconds (an endless loop?)"),
768 )));
769 }
770 let mut ev = Eval {
771 host: &mut *host,
772 vars: &*vars,
773 line,
774 };
775 match &self.ops[pc] {
776 Op::Assign(name, e) => {
777 let v = ev.expr(e)?;
778 match (name.ends_with('$'), &v) {
779 (true, Value::Str(_)) | (false, Value::Num(_)) => {}
780 _ => {
781 return Err(err(line, format!("wrong kind of value for {name}")).into())
782 }
783 }
784 vars.0.insert(name.clone(), v);
785 }
786 Op::JumpIfNot(c, to) => {
787 if ev.expr(c)?.num(line)? == 0.0 {
788 pc = *to;
789 continue;
790 }
791 }
792 Op::Jump(to) => {
793 pc = *to;
794 continue;
795 }
796 Op::ForInit(v, a, b, c, n) => {
797 let a = ev.expr(a)?.num(line)?;
798 let b = ev.expr(b)?.num(line)?;
799 let c = ev.expr(c)?.num(line)?;
800 let dir = if a < b {
801 1
802 } else if a > b {
803 -1
804 } else {
805 0
806 };
807 if (dir == 1 && !(c > 0.0)) || (dir == -1 && !(c < 0.0)) {
808 return Err(Stop::Keep(err(
809 line,
810 format!("FOR step {c} doesn't go the way of {a} → {b}"),
811 )));
812 }
813 fors[*n] = (b, c, dir);
814 vars.0.insert(v.clone(), Value::Num(a));
815 }
816 Op::ForNext(n, body) => {
817 let (stop, inc, dir) = fors[*n];
818 let Op::ForInit(v, ..) = &self.ops[body - 1] else {
819 unreachable!()
820 };
821 let x = match vars.0.get(v) {
823 Some(Value::Num(x)) => *x,
824 _ => 0.0,
825 } + inc;
826 vars.0.insert(v.clone(), Value::Num(x));
827 let again = match dir {
828 1 => x <= stop,
829 -1 => x >= stop,
830 _ => false,
831 };
832 if again {
833 pc = *body;
834 continue;
835 }
836 }
837 Op::Gosub(name) => {
838 if stack.len() >= MAX_DEPTH {
839 return Err(err(line, "GOSUB nested too deep").into());
840 }
841 stack.push(pc + 1);
842 pc = self.subs[name];
843 continue;
844 }
845 Op::Return => match stack.pop() {
846 Some(r) => {
847 pc = r;
848 continue;
849 }
850 None => return Err(err(line, "RETURN outside GOSUB").into()),
851 },
852 Op::End => break,
853 Op::FallIntoSub => break,
855 Op::SolveReturn(e) => *ret = Some(ev.expr(e)?.num(line)?),
856 Op::Command(name, args) => {
857 let a = args
858 .iter()
859 .map(|e| ev.expr(e))
860 .collect::<Result<Vec<_>>>()?;
861 match host.command(name, &a) {
862 Some(r) => {
863 if let Flow::Abort(why) =
864 r.map_err(|e| e.at(format!("ZPL line {line}")))?
865 {
866 return Err(Stop::Abort(err(line, why)));
867 }
868 }
869 None => return Err(unsupported(line, format!("statement {name}")).into()),
870 }
871 }
872 Op::Nop => {}
873 Op::Fail(e) => return Err(e.clone().into()),
874 }
875 pc += 1;
876 }
877 Ok(())
878 }
879}
880
881fn then_offset(s: &str) -> Option<usize> {
883 let up = s.to_uppercase();
884 let b = up.as_bytes();
885 let mut in_str = false;
886 for i in 0..b.len() {
887 if b[i] == b'"' {
888 in_str = !in_str;
889 }
890 if !in_str
891 && up[i..].starts_with("THEN")
892 && (i == 0 || !(b[i - 1] as char).is_alphanumeric() && b[i - 1] != b'_')
893 && b.get(i + 4)
894 .is_none_or(|c| !(*c as char).is_alphanumeric() && *c != b'_')
895 {
896 return Some(i + 4);
897 }
898 }
899 None
900}
901
902impl Parser<'_> {
903 fn whole(mut self) -> Result<Expr> {
905 let e = self.expr(0)?;
906 self.end()?;
907 Ok(e)
908 }
909}
910
911#[derive(Debug, Clone, Default)]
913pub struct Vars(HashMap<String, Value>);
914
915impl Vars {
916 pub fn get_num(&self, name: &str) -> f64 {
917 match self.0.get(&name.to_uppercase()) {
918 Some(Value::Num(x)) => *x,
919 _ => 0.0,
920 }
921 }
922 pub fn set_num(&mut self, name: &str, x: f64) {
923 self.0.insert(name.to_uppercase(), Value::Num(x));
924 }
925}
926
927struct Eval<'a> {
930 host: &'a mut dyn Host,
931 vars: &'a Vars,
932 line: usize,
933}
934
935impl Eval<'_> {
936 fn expr(&mut self, e: &Expr) -> Result<Value> {
937 let line = self.line;
938 Ok(match e {
939 Expr::Lit(v) => v.clone(),
940 Expr::Var(n) => self
941 .vars
942 .0
943 .get(n)
944 .cloned()
945 .ok_or_else(|| err(line, format!("variable {n} has no value yet")))?,
946 Expr::Neg(a) => Value::Num(-self.expr(a)?.num(line)?),
947 Expr::Not(a) => Value::Num(b(self.expr(a)?.num(line)? == 0.0)),
948 Expr::Bin(op, a, c) => {
949 let x = self.expr(a)?;
950 let y = self.expr(c)?;
951 if let (Value::Str(s), "+") = (&x, *op) {
952 return Ok(Value::Str(format!("{s}{}", y.str(line)?)));
953 }
954 let (x, y) = (x.num(line)?, y.num(line)?);
955 Value::Num(match *op {
956 "+" => x + y,
957 "-" => x - y,
958 "*" => x * y,
959 "/" => {
961 if y == 0.0 {
962 0.0
963 } else {
964 x / y
965 }
966 }
967 "==" => b(x == y),
968 "!=" => b(x != y),
969 "<" => b(x < y),
970 ">" => b(x > y),
971 "<=" => b(x <= y),
972 ">=" => b(x >= y),
973 "&" => b(x != 0.0 && y != 0.0),
974 "|" => b(x != 0.0 || y != 0.0),
975 "^" => b((x != 0.0) != (y != 0.0)),
976 _ => unreachable!(),
977 })
978 }
979 Expr::Call(name, args) => {
980 let a = args
981 .iter()
982 .map(|e| self.expr(e))
983 .collect::<Result<Vec<_>>>()?;
984 if let Some(v) = builtin(name, &a, line)? {
985 return Ok(v);
986 }
987 match self.host.function(name, &a) {
988 Some(r) => r.map_err(|e| e.at(format!("ZPL line {line}")))?,
989 None => return Err(unsupported(line, format!("function {name}"))),
990 }
991 }
992 })
993 }
994}
995
996fn b(x: bool) -> f64 {
997 if x {
998 1.0
999 } else {
1000 0.0
1001 }
1002}
1003
1004fn builtin(name: &str, a: &[Value], line: usize) -> Result<Option<Value>> {
1006 let one = |f: fn(f64) -> f64| -> Result<Option<Value>> {
1007 match a {
1008 [x] => Ok(Some(Value::Num(f(x.num(line)?)))),
1009 _ => Err(err(line, format!("{name} takes one argument"))),
1010 }
1011 };
1012 let dom = |ok: fn(f64) -> bool, f: fn(f64) -> f64, or: Option<f64>| -> Result<Option<Value>> {
1014 match a {
1015 [x] => {
1016 let x = x.num(line)?;
1017 Ok(Some(Value::Num(if ok(x) { f(x) } else { or.unwrap_or(x) })))
1018 }
1019 _ => Err(err(line, format!("{name} takes one argument"))),
1020 }
1021 };
1022 match name {
1023 "ABSO" => one(f64::abs),
1024 "ACOS" => dom(|x| (-1.0..=1.0).contains(&x), f64::acos, Some(0.0)),
1026 "ASIN" => dom(|x| (-1.0..=1.0).contains(&x), f64::asin, Some(f64::NAN)),
1027 "ATAN" => one(f64::atan),
1028 "COSI" => one(f64::cos),
1029 "SINE" => one(f64::sin),
1030 "TANG" => one(f64::tan),
1031 "EXPE" => one(f64::exp),
1032 "EXPT" => one(|x| 10f64.powf(x)),
1033 "LOGE" => dom(|x| x > 0.0, f64::ln, None),
1035 "LOGT" => dom(|x| x > 0.0, f64::log10, None),
1036 "INTE" => one(f64::floor),
1037 "SIGN" => one(|x| {
1038 if x > 0.0 {
1039 1.0
1040 } else if x < 0.0 {
1041 -1.0
1042 } else {
1043 0.0
1044 }
1045 }),
1046 "SQRT" => dom(|x| x >= 0.0, f64::sqrt, None),
1047 "POWR" => match a {
1048 [x, y] => Ok(Some(Value::Num(x.num(line)?.abs().powf(y.num(line)?)))),
1049 _ => Err(err(line, "POWR takes two arguments")),
1050 },
1051 _ => Ok(None),
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058
1059 fn run(src: &str) -> Result<Option<f64>> {
1060 Program::parse(src)?.run(&mut NoHost, &mut Vars::default())
1061 }
1062 fn val(src: &str) -> f64 {
1063 run(src).unwrap().unwrap()
1064 }
1065
1066 #[test]
1067 fn arithmetic_and_precedence() {
1068 assert_eq!(val("SOLVERETURN 1 + 2 * 3"), 7.0);
1069 assert_eq!(val("SOLVERETURN (1 + 2) * 3"), 9.0);
1070 assert_eq!(val("SOLVERETURN 8 / 4 / 2"), 1.0);
1071 assert_eq!(val("SOLVERETURN 1 - 2 - 3"), -4.0);
1072 assert_eq!(val("SOLVERETURN -2 * -3"), 6.0);
1073 assert_eq!(val("SOLVERETURN 1.5e2 + .5"), 150.5);
1074 assert_eq!(val("SOLVERETURN 1 + 1 == 2"), 1.0);
1075 assert_eq!(val("SOLVERETURN 1 < 2 & 3 > 4"), 0.0);
1077 assert_eq!(val("SOLVERETURN 1 | 0 & 0"), 0.0);
1078 assert_eq!(val("SOLVERETURN 0 & 0 == 0"), 1.0);
1079 assert_eq!(val("SOLVERETURN 0 == 0 & 0"), 0.0);
1080 assert_eq!(val("SOLVERETURN 1 | 0 == 0"), 0.0);
1081 assert_eq!(val("SOLVERETURN 1 | 1 ^ 1"), 0.0);
1082 assert_eq!(val("SOLVERETURN 1 ^ 1 | 1"), 1.0);
1083 assert_eq!(val("SOLVERETURN 0 & 2 < 3"), 1.0);
1084 assert_eq!(val("SOLVERETURN 3 > 2 > 1"), 0.0);
1085 assert_eq!(val("SOLVERETURN 1 + 1 ^ 1"), 0.0);
1086 assert_eq!(val("SOLVERETURN 2 == 2 + 1"), 0.0);
1087 assert_eq!(val("SOLVERETURN !0 + 1"), 2.0);
1088 assert_eq!(val("SOLVERETURN !1 == 0"), 1.0);
1089 assert_eq!(val("SOLVERETURN 2 & 3"), 1.0);
1090 assert_eq!(val("SOLVERETURN 1 ^ 1"), 0.0); assert_eq!(val("SOLVERETURN 0 | 2"), 1.0);
1092 assert_eq!(val("SOLVERETURN !0"), 1.0);
1093 assert!(run("SOLVERETURN 3 <> 3").is_err());
1094 }
1095
1096 #[test]
1097 fn functions() {
1098 assert_eq!(val("SOLVERETURN SQRT(16) + ABSO(-1)"), 5.0);
1099 assert_eq!(val("SOLVERETURN POWR(-2, 3)"), 8.0);
1100 assert_eq!(val("SOLVERETURN INTE(-2.7)"), -3.0);
1101 assert_eq!(val("SOLVERETURN INTE(2.7)"), 2.0);
1102 assert_eq!(val("SOLVERETURN SIGN(0) + SIGN(-3) * 10"), -10.0);
1103 assert_eq!(val("SOLVERETURN ATAN(1) * 4"), std::f64::consts::PI);
1104 assert_eq!(val("SOLVERETURN EXPT(2)"), 100.0);
1105 assert_eq!(val("SOLVERETURN SQRT(-4) + 10"), 6.0);
1107 assert_eq!(val("SOLVERETURN LOGE(0) + 10"), 10.0);
1108 assert_eq!(val("SOLVERETURN LOGT(-1) + 7"), 6.0);
1109 assert_eq!(val("SOLVERETURN ACOS(2) + 7"), 7.0);
1110 assert!(val("SOLVERETURN ASIN(2) + 7").is_nan());
1111 assert_eq!(val("SOLVERETURN 5 + 1 / 0"), 5.0);
1112 assert!(matches!(
1113 run("SOLVERETURN FOOB(1)"),
1114 Err(Error::NotImplemented(_))
1115 ));
1116 }
1117
1118 #[test]
1119 fn variables_comments_case() {
1120 let src = "! 注釈\nrem 注釈\nx = 2 # 行の途中の注釈\nY = X * 3\nname$ = \"a#b\" + \"c\"\nSolveReturn y";
1121 assert_eq!(val(src), 6.0);
1122 assert!(run("SOLVERETURN undefined + 1").is_err());
1123 assert!(run("x = 6 ! 注釈ではない\nSOLVERETURN x").is_err());
1124 assert!(run("x = \"a\"").is_err());
1125 }
1126
1127 #[test]
1128 fn if_blocks() {
1129 let src = "x = 3\nIF (x > 2)\n IF x > 5\n y = 1\n ELSE\n y = 2\n ENDIF\nELSE\n y = 3\nENDIF\nSOLVERETURN y";
1130 assert_eq!(val(src), 2.0);
1131 assert_eq!(val("x = 0\nIF x THEN x = 5\nSOLVERETURN x"), 0.0);
1132 assert_eq!(
1133 val("x = 1\nSOLVERETURN x\nIF x == 1 THEN SOLVERETURN 7"),
1134 7.0
1135 );
1136 assert_eq!(val("y = 1\nIF y THEN y = 4\nSOLVERETURN y"), 4.0);
1137 assert!(run("IF 1\nx = 1").is_ok()); assert!(run("ENDIF").is_err());
1139 }
1140
1141 #[test]
1142 fn for_loops() {
1143 assert_eq!(
1144 val("s = 0\nFOR i, 1, 10, 1\ns = s + i\nNEXT\nSOLVERETURN s"),
1145 55.0
1146 );
1147 assert_eq!(
1148 val("s = 0\nFOR i, 10, 1, -3\ns = s + i\nNEXT i\nSOLVERETURN s"),
1149 22.0
1150 ); assert_eq!(
1152 val("s = 0\nFOR i, 5, 5, -1\ns = s + 1\nNEXT\nSOLVERETURN s"),
1153 1.0
1154 );
1155 assert_eq!(
1157 val("n = 3\ns = 0\nFOR i, 1, n, 1\nn = 10\ns = s + 1\nNEXT\nSOLVERETURN s"),
1158 3.0
1159 );
1160 assert_eq!(
1161 val("s = 0\nFOR i, 1, 3, 1\nFOR j, 1, 2, 1\ns = s + 1\nNEXT\nNEXT\nSOLVERETURN s"),
1162 6.0
1163 );
1164 assert_eq!(val("FOR i, 1, 3, 1\nNEXT\nSOLVERETURN i"), 4.0);
1165 assert_eq!(val("FOR i, 3, 1, -1\nNEXT\nSOLVERETURN i"), 0.0);
1166 assert!(run("FOR i, 1, 3, -1\nNEXT\nSOLVERETURN 1").is_err());
1168 assert!(run("FOR i, 3, 1, 1\nNEXT\nSOLVERETURN 1").is_err());
1169 assert!(run("FOR i, 1, 3, 0\nNEXT\nSOLVERETURN 1").is_err());
1170 }
1171
1172 #[test]
1173 fn goto_gosub_end() {
1174 assert_eq!(
1175 val("x = 0\nLABEL 1\nx = x + 1\nIF x < 5 THEN GOTO 1\nSOLVERETURN x"),
1176 5.0
1177 );
1178 assert!(run("IF 1 THEN IF 1 THEN x = 1").is_err());
1179 let src = "x = 0\nLABEL top\nx = x + 1\nIF (x < 5)\nGOTO top\nENDIF\nGOSUB twice\nSOLVERETURN x\nEND\nSUB twice\nx = x * 2\nRETURN";
1180 assert_eq!(val(src), 10.0);
1181 assert_eq!(
1183 val("x = 1\nSOLVERETURN x\nSUB a\nx = 5\nSOLVERETURN x\nRETURN"),
1184 1.0
1185 );
1186 assert!(run("GOTO nowhere").is_err());
1187 assert_eq!(run("x = 1").unwrap(), None);
1188 assert_eq!(
1189 Program::parse("x = 1")
1190 .unwrap()
1191 .solve(&mut NoHost)
1192 .unwrap()
1193 .value,
1194 None
1195 );
1196 }
1197
1198 #[test]
1199 fn last_solvereturn_wins_and_print_ignored() {
1200 assert_eq!(val("SOLVERETURN 1\nPRINT \"x\", 3\nSOLVERETURN 2"), 2.0);
1201 }
1202
1203 #[test]
1204 fn host_functions_and_commands() {
1205 struct H(f64);
1206 impl Host for H {
1207 fn function(&mut self, name: &str, a: &[Value]) -> Option<Result<Value>> {
1208 (name == "CURV").then(|| Ok(Value::Num(self.0 * a[0].num(0).unwrap())))
1209 }
1210 fn command(&mut self, name: &str, a: &[Value]) -> Option<Result<Flow>> {
1211 match name {
1212 "SETX" => {
1213 self.0 = a[0].num(0).unwrap();
1214 Some(Ok(Flow::Go))
1215 }
1216 "STOPNOW" => Some(Ok(Flow::Abort("止める".into()))),
1217 _ => None,
1218 }
1219 }
1220 }
1221 let p = Program::parse("SETX 3\nSOLVERETURN curv(2)").unwrap();
1222 assert_eq!(p.solve(&mut H(1.0)).unwrap().value, Some(6.0));
1223 let p = Program::parse("SOLVERETURN 1\nSTOPNOW\nSOLVERETURN 2").unwrap();
1225 assert_eq!(p.solve(&mut H(1.0)).unwrap().value, None);
1226 assert!(matches!(
1227 Program::parse("RAYTRACE 0, 1, 0, 1")
1228 .unwrap()
1229 .solve(&mut H(1.0)),
1230 Err(Error::NotImplemented(_))
1231 ));
1232 }
1233
1234 #[test]
1236 fn solve_outcome_like_opticstudio() {
1237 let out = |src: &str| {
1238 Program::parse(src)
1239 .unwrap()
1240 .solve(&mut NoHost)
1241 .unwrap()
1242 .value
1243 };
1244 assert_eq!(out("SOLVERETURN 7\nx = undefinedvar"), Some(7.0));
1246 assert_eq!(out("x = undefinedvar\nSOLVERETURN 7"), Some(0.0));
1247 assert_eq!(out("SOLVERETURN 7\nx = 3 <> 2"), Some(7.0));
1248 assert_eq!(out("SOLVERETURN 7\nx = 6 ! note"), Some(7.0));
1249 assert_eq!(out("SOLVERETURN 3\nEND\nSOLVERETURN 4"), Some(3.0));
1250 assert_eq!(out("x = 1"), None);
1252 assert_eq!(
1253 out("s = 0\nFOR i, 1, 3, -1\ns = s + 1\nNEXT\nSOLVERETURN 100 + s"),
1254 None
1255 );
1256 assert_eq!(out("SOLVERETURN ASIN(2) + 7"), None);
1257 assert_eq!(
1259 out("FOR i, 1, 3, 1\nIF i == 2 THEN GOTO 9\nNEXT\nLABEL 9\nSOLVERETURN 100 + i"),
1260 Some(102.0)
1261 );
1262 }
1263
1264 #[test]
1265 fn infinite_loop_stops() {
1266 assert!(run("LABEL 1\nGOTO 1").is_err());
1267 }
1268}