⎇ 7867d6830e128b8a2afe95cb752093e12a184988
crates/modules/charka/charka-shadow/src/interp.rs
Historia
Quién tocó qué
crudo
feat(charka): EVALUATE TRUE y rangos WHEN ... THRU
1//! El intérprete del IR: la ejecución «sombra» del programa COBOL.
2//!
3//! Ejecuta el [`Ir`] directamente sobre los tipos de `charka-runtime`,
4//! sin compilar nada. Es una segunda ruta de ejecución, independiente
5//! del código que emite `charka-codegen` — eso es lo que lo hace un
6//! validador: si el intérprete y el transpilado divergen, hay un bug.
7
8use std::collections::HashMap;
9
10use charka_ir::{
11 BinOp, CmpOp, Cond, ConditionName, Expr, Figurative, InspectOp, Ir, Operand, Perform,
12 PerformControl, PerformTarget, Stmt, WhenTest,
13};
14use charka_runtime::{cobol_text_cmp, Decimal, Rounding};
15
16use crate::field::{build_fields, Cell};
17
18/// Tope de pasos: corta los bucles que no terminan (un `PERFORM UNTIL`
19/// con una condición que nunca se cumple) en vez de colgarse.
20const STEP_BUDGET: u64 = 5_000_000;
21
22/// Escala intermedia de la división dentro de una expresión.
23const DIV_SCALE: u8 = 9;
24
25/// El resultado de ejecutar un statement: cómo sigue el control.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Flow {
28 /// Sigue con el statement siguiente.
29 Normal,
30 /// Sale del párrafo actual (`EXIT`).
31 Exit,
32 /// Termina el programa (`STOP RUN`, `GOBACK`, tope de pasos).
33 Stop,
34}
35
36/// La máquina sombra: el estado y el motor de ejecución.
37pub(crate) struct Machine<'a> {
38 ir: &'a Ir,
39 fields: HashMap<String, Cell>,
40 para_index: HashMap<String, usize>,
41 conditions: HashMap<String, ConditionName>,
42 pub output: Vec<String>,
43 budget: u64,
44 pub step_limit_hit: bool,
45 pub stopped: bool,
46}
47
48impl<'a> Machine<'a> {
49 /// Prepara la máquina: aplana los datos e indexa los párrafos.
50 pub(crate) fn new(ir: &'a Ir) -> Self {
51 let mut para_index = HashMap::new();
52 for (i, proc) in ir.procedures.iter().enumerate() {
53 para_index.entry(proc.name.to_uppercase()).or_insert(i);
54 }
55 let conditions = ir
56 .model
57 .conditions
58 .iter()
59 .map(|c| (c.name.clone(), c.clone()))
60 .collect();
61 Self {
62 ir,
63 fields: build_fields(&ir.model),
64 para_index,
65 conditions,
66 output: Vec::new(),
67 budget: STEP_BUDGET,
68 step_limit_hit: false,
69 stopped: false,
70 }
71 }
72
73 /// Corre el programa: encadena los párrafos en orden (el «caer» de
74 /// COBOL) hasta un `STOP RUN` o el final.
75 pub(crate) fn run(&mut self) {
76 let ir = self.ir;
77 for i in 0..ir.procedures.len() {
78 if let Flow::Stop = self.exec_block(&ir.procedures[i].body) {
79 self.stopped = true;
80 break;
81 }
82 }
83 }
84
85 // ── Ejecución ─────────────────────────────────────────────────
86
87 /// Consume un paso del presupuesto. `true` si se agotó.
88 fn tick(&mut self) -> bool {
89 if self.budget == 0 {
90 self.step_limit_hit = true;
91 return true;
92 }
93 self.budget -= 1;
94 false
95 }
96
97 fn exec_block(&mut self, stmts: &'a [Stmt]) -> Flow {
98 for s in stmts {
99 match self.exec_stmt(s) {
100 Flow::Normal => {}
101 other => return other,
102 }
103 }
104 Flow::Normal
105 }
106
107 fn exec_stmt(&mut self, stmt: &'a Stmt) -> Flow {
108 if self.tick() {
109 return Flow::Stop;
110 }
111 match stmt {
112 Stmt::Move { from, to } => {
113 for t in to {
114 self.do_move(from, t);
115 }
116 Flow::Normal
117 }
118 Stmt::Display { items } => {
119 let line: String = items.iter().map(|o| self.eval_text(o)).collect();
120 self.output.push(line);
121 Flow::Normal
122 }
123 Stmt::Accept { .. } => Flow::Normal, // sin entrada: deja el campo igual
124 Stmt::Compute {
125 targets,
126 rounded,
127 expr,
128 } => {
129 let value = self.eval_expr(expr);
130 for t in targets {
131 self.store(t, value, *rounded);
132 }
133 Flow::Normal
134 }
135 Stmt::Add {
136 addends,
137 to,
138 giving,
139 rounded,
140 } => {
141 let sum = self.fold_sum(addends);
142 if giving.is_empty() {
143 for t in to {
144 let cur = self.eval_decimal(t);
145 self.store(t, cur.add(&sum), *rounded);
146 }
147 } else {
148 let base = match to.first() {
149 Some(first) => sum.add(&self.eval_decimal(first)),
150 None => sum,
151 };
152 for g in giving {
153 self.store(g, base, *rounded);
154 }
155 }
156 Flow::Normal
157 }
158 Stmt::Subtract {
159 amounts,
160 from,
161 giving,
162 rounded,
163 } => {
164 let sum = self.fold_sum(amounts);
165 if giving.is_empty() {
166 for t in from {
167 let cur = self.eval_decimal(t);
168 self.store(t, cur.sub(&sum), *rounded);
169 }
170 } else {
171 let minuend = from
172 .first()
173 .map(|f| self.eval_decimal(f))
174 .unwrap_or_else(Decimal::zero);
175 let value = minuend.sub(&sum);
176 for g in giving {
177 self.store(g, value, *rounded);
178 }
179 }
180 Flow::Normal
181 }
182 Stmt::Multiply {
183 left,
184 by,
185 giving,
186 rounded,
187 } => {
188 let value = self.eval_decimal(left).mul(&self.eval_decimal(by));
189 if giving.is_empty() {
190 // `MULTIPLY a BY b` sin GIVING: b queda con a*b.
191 self.store(by, value, *rounded);
192 } else {
193 for g in giving {
194 self.store(g, value, *rounded);
195 }
196 }
197 Flow::Normal
198 }
199 Stmt::Divide {
200 left,
201 right,
202 by_form,
203 giving,
204 rounded,
205 } => {
206 let (num, den) = if *by_form {
207 (self.eval_decimal(left), self.eval_decimal(right))
208 } else {
209 (self.eval_decimal(right), self.eval_decimal(left))
210 };
211 if giving.is_empty() {
212 // `DIVIDE a INTO b` sin GIVING: b queda con b/a.
213 let v = divide(num, den, self.target_scale(right));
214 self.store(right, v, *rounded);
215 } else {
216 for g in giving {
217 let v = divide(num, den, self.target_scale(g));
218 self.store(g, v, *rounded);
219 }
220 }
221 Flow::Normal
222 }
223 Stmt::If {
224 cond,
225 then_branch,
226 else_branch,
227 } => {
228 if self.eval_cond(cond) {
229 self.exec_block(then_branch)
230 } else {
231 self.exec_block(else_branch)
232 }
233 }
234 Stmt::Evaluate {
235 subject,
236 whens,
237 other,
238 } => {
239 for branch in whens {
240 if branch.tests.iter().any(|t| self.when_test(subject, t)) {
241 return self.exec_block(&branch.body);
242 }
243 }
244 self.exec_block(other)
245 }
246 Stmt::StringConcat { sources, into } => {
247 let s: String = sources.iter().map(|o| self.eval_text(o)).collect();
248 self.store_text(into, &s);
249 Flow::Normal
250 }
251 Stmt::Unstring {
252 source,
253 delimiter,
254 into,
255 } => {
256 let src = self.eval_text(source);
257 let delim = self.eval_text(delimiter);
258 let parts: Vec<String> = if delim.is_empty() {
259 vec![src]
260 } else {
261 src.split(delim.as_str()).map(|p| p.to_string()).collect()
262 };
263 for (i, target) in into.iter().enumerate() {
264 let piece = parts.get(i).cloned().unwrap_or_default();
265 self.store_text(target, &piece);
266 }
267 Flow::Normal
268 }
269 Stmt::Inspect { target, op } => {
270 match op {
271 InspectOp::TallyingForAll { counter, search } => {
272 let hay = self.eval_text(target);
273 let needle = self.eval_text(search);
274 let n = if needle.is_empty() {
275 0
276 } else {
277 hay.matches(needle.as_str()).count()
278 };
279 let cur = self.eval_decimal(counter);
280 self.store(counter, cur.add(&Decimal::from_integer(n as i128)), false);
281 }
282 InspectOp::ReplacingAll { from, to } => {
283 let hay = self.eval_text(target);
284 let f = self.eval_text(from);
285 let t = self.eval_text(to);
286 let new = if f.is_empty() {
287 hay
288 } else {
289 hay.replace(f.as_str(), t.as_str())
290 };
291 self.store_text(target, &new);
292 }
293 }
294 Flow::Normal
295 }
296 Stmt::Perform(p) => self.exec_perform(p),
297 Stmt::GoTo { target } => {
298 // Aproximación: ejecuta el destino y sale del párrafo.
299 match self.run_paragraph(target) {
300 Flow::Stop => Flow::Stop,
301 _ => Flow::Exit,
302 }
303 }
304 Stmt::StopRun | Stmt::Goback => Flow::Stop,
305 Stmt::Exit => Flow::Exit,
306 Stmt::Continue => Flow::Normal,
307 Stmt::Unknown { .. } => Flow::Normal, // verbo no soportado: se omite
308 }
309 }
310
311 fn exec_perform(&mut self, p: &'a Perform) -> Flow {
312 match &p.control {
313 PerformControl::Once => self.run_target(&p.target),
314 PerformControl::Times(n) => {
315 let count = self.count_of(n);
316 for _ in 0..count {
317 if self.tick() {
318 return Flow::Stop;
319 }
320 if let Flow::Stop = self.run_target(&p.target) {
321 return Flow::Stop;
322 }
323 }
324 Flow::Normal
325 }
326 PerformControl::Until(cond) => loop {
327 if self.tick() {
328 return Flow::Stop;
329 }
330 if self.eval_cond(cond) {
331 return Flow::Normal;
332 }
333 if let Flow::Stop = self.run_target(&p.target) {
334 return Flow::Stop;
335 }
336 },
337 PerformControl::Varying {
338 var,
339 from,
340 by,
341 until,
342 } => {
343 let var_op = Operand::Data(var.clone());
344 let start = self.eval_decimal(from);
345 self.store(&var_op, start, false);
346 loop {
347 if self.tick() {
348 return Flow::Stop;
349 }
350 if self.eval_cond(until) {
351 return Flow::Normal;
352 }
353 if let Flow::Stop = self.run_target(&p.target) {
354 return Flow::Stop;
355 }
356 let next = self.eval_decimal(&var_op).add(&self.eval_decimal(by));
357 self.store(&var_op, next, false);
358 }
359 }
360 }
361 }
362
363 /// Ejecuta una vez el cuerpo de un `PERFORM`. Un `EXIT` dentro de
364 /// él termina esa pasada, no el programa.
365 fn run_target(&mut self, target: &'a PerformTarget) -> Flow {
366 let flow = match target {
367 PerformTarget::Paragraph { name, .. } => self.run_paragraph(name),
368 PerformTarget::Inline(body) => self.exec_block(body),
369 };
370 match flow {
371 Flow::Stop => Flow::Stop,
372 _ => Flow::Normal,
373 }
374 }
375
376 fn run_paragraph(&mut self, name: &str) -> Flow {
377 let Some(&idx) = self.para_index.get(&name.to_uppercase()) else {
378 return Flow::Normal;
379 };
380 let ir = self.ir;
381 match self.exec_block(&ir.procedures[idx].body) {
382 Flow::Stop => Flow::Stop,
383 _ => Flow::Normal,
384 }
385 }
386
387 /// Resuelve una referencia a dato (escalar o elemento de tabla) a
388 /// su nombre y un índice 0-based. `None` si no es una referencia.
389 fn resolve(&self, op: &Operand) -> Option<(String, usize)> {
390 match op {
391 Operand::Data(name) => Some((name.to_uppercase(), 0)),
392 Operand::Indexed { name, index } => {
393 // El subíndice de COBOL es 1-based.
394 let i = self
395 .eval_decimal(index)
396 .rescale(0, Rounding::Truncate)
397 .mantissa();
398 let idx = if i < 1 { 0 } else { (i - 1) as usize };
399 Some((name.to_uppercase(), idx))
400 }
401 _ => None,
402 }
403 }
404
405 /// `MOVE from` a un solo destino (escalar o elemento de tabla).
406 fn do_move(&mut self, from: &Operand, target: &Operand) {
407 let Some((key, idx)) = self.resolve(target) else {
408 return;
409 };
410 let is_num = matches!(self.fields.get(&key), Some(Cell::Num(_)));
411 if is_num {
412 let v = self.eval_decimal(from);
413 if let Some(Cell::Num(arr)) = self.fields.get_mut(&key) {
414 if let Some(n) = arr.get_mut(idx) {
415 n.store(v);
416 }
417 }
418 } else if let Operand::Figurative(fig) = from {
419 let ch = figurative_fill(*fig);
420 if let Some(Cell::Text(arr)) = self.fields.get_mut(&key) {
421 if let Some(t) = arr.get_mut(idx) {
422 t.fill(ch);
423 }
424 }
425 } else {
426 let s = self.eval_text(from);
427 if let Some(Cell::Text(arr)) = self.fields.get_mut(&key) {
428 if let Some(t) = arr.get_mut(idx) {
429 t.store(&s);
430 }
431 }
432 }
433 }
434
435 /// Almacena un valor en un destino, conformándolo a su tipo.
436 fn store(&mut self, target: &Operand, value: Decimal, rounded: bool) {
437 let Some((key, idx)) = self.resolve(target) else {
438 return;
439 };
440 match self.fields.get_mut(&key) {
441 Some(Cell::Num(arr)) => {
442 if let Some(n) = arr.get_mut(idx) {
443 if rounded {
444 n.store_rounded(value);
445 } else {
446 n.store(value);
447 }
448 }
449 }
450 Some(Cell::Text(arr)) => {
451 if let Some(t) = arr.get_mut(idx) {
452 t.store(&value.to_string());
453 }
454 }
455 None => {}
456 }
457 }
458
459 /// Almacena un texto en un destino, conformándolo a su tipo.
460 fn store_text(&mut self, target: &Operand, text: &str) {
461 let Some((key, idx)) = self.resolve(target) else {
462 return;
463 };
464 match self.fields.get_mut(&key) {
465 Some(Cell::Text(arr)) => {
466 if let Some(t) = arr.get_mut(idx) {
467 t.store(text);
468 }
469 }
470 Some(Cell::Num(arr)) => {
471 if let Some(n) = arr.get_mut(idx) {
472 n.store(Decimal::parse(text.trim()).unwrap_or_else(|_| Decimal::zero()));
473 }
474 }
475 None => {}
476 }
477 }
478
479 // ── Evaluación ────────────────────────────────────────────────
480
481 fn eval_decimal(&self, op: &Operand) -> Decimal {
482 match op {
483 Operand::Num(n) => Decimal::parse(n).unwrap_or_else(|_| Decimal::zero()),
484 Operand::Str(s) => Decimal::parse(s).unwrap_or_else(|_| Decimal::zero()),
485 Operand::Figurative(_) => Decimal::zero(),
486 Operand::Data(_) | Operand::Indexed { .. } => {
487 let Some((key, idx)) = self.resolve(op) else {
488 return Decimal::zero();
489 };
490 match self.fields.get(&key) {
491 Some(Cell::Num(arr)) => arr
492 .get(idx)
493 .map(|n| n.value())
494 .unwrap_or_else(Decimal::zero),
495 Some(Cell::Text(arr)) => arr
496 .get(idx)
497 .and_then(|t| Decimal::parse(t.as_str().trim()).ok())
498 .unwrap_or_else(Decimal::zero),
499 None => Decimal::zero(),
500 }
501 }
502 }
503 }
504
505 fn eval_text(&self, op: &Operand) -> String {
506 match op {
507 Operand::Str(s) => s.clone(),
508 Operand::Num(n) => n.clone(),
509 Operand::Figurative(f) => figurative_text(*f).to_string(),
510 Operand::Data(_) | Operand::Indexed { .. } => {
511 let Some((key, idx)) = self.resolve(op) else {
512 return String::new();
513 };
514 match self.fields.get(&key) {
515 Some(Cell::Num(arr)) => arr.get(idx).map(|n| n.display()).unwrap_or_default(),
516 Some(Cell::Text(arr)) => arr.get(idx).map(|t| t.display()).unwrap_or_default(),
517 None => String::new(),
518 }
519 }
520 }
521 }
522
523 fn eval_expr(&self, e: &Expr) -> Decimal {
524 match e {
525 Expr::Operand(op) => self.eval_decimal(op),
526 Expr::Neg(inner) => Decimal::zero().sub(&self.eval_expr(inner)),
527 Expr::Binary { op, lhs, rhs } => {
528 let l = self.eval_expr(lhs);
529 let r = self.eval_expr(rhs);
530 match op {
531 BinOp::Add => l.add(&r),
532 BinOp::Sub => l.sub(&r),
533 BinOp::Mul => l.mul(&r),
534 BinOp::Div => divide(l, r, DIV_SCALE),
535 BinOp::Pow => pow(&l, &r),
536 }
537 }
538 }
539 }
540
541 fn eval_cond(&self, c: &Cond) -> bool {
542 match c {
543 Cond::Compare { lhs, op, rhs } => {
544 let ord = if self.is_text(lhs) || self.is_text(rhs) {
545 cobol_text_cmp(&self.eval_text(lhs), &self.eval_text(rhs))
546 } else {
547 self.eval_decimal(lhs).cmp(&self.eval_decimal(rhs))
548 };
549 match op {
550 CmpOp::Eq => ord.is_eq(),
551 CmpOp::Ne => ord.is_ne(),
552 CmpOp::Lt => ord.is_lt(),
553 CmpOp::Gt => ord.is_gt(),
554 CmpOp::Le => ord.is_le(),
555 CmpOp::Ge => ord.is_ge(),
556 }
557 }
558 Cond::Named(name) => match self.conditions.get(&name.to_uppercase()) {
559 // Un nombre de condición (88): el dato padre igual al
560 // valor que la hace verdadera.
561 Some(cn) => self.operands_equal(&Operand::Data(cn.parent.clone()), &cn.value),
562 None => false,
563 },
564 Cond::Not(inner) => !self.eval_cond(inner),
565 Cond::And(a, b) => self.eval_cond(a) && self.eval_cond(b),
566 Cond::Or(a, b) => self.eval_cond(a) || self.eval_cond(b),
567 }
568 }
569
570 fn is_text(&self, op: &Operand) -> bool {
571 match op {
572 Operand::Str(_) => true,
573 Operand::Data(_) | Operand::Indexed { .. } => match self.resolve(op) {
574 Some((key, _)) => matches!(self.fields.get(&key), Some(Cell::Text(_))),
575 None => false,
576 },
577 _ => false,
578 }
579 }
580
581 /// ¿Se cumple una prueba `WHEN` para el sujeto dado?
582 fn when_test(&self, subject: &Operand, test: &WhenTest) -> bool {
583 match test {
584 WhenTest::Value(v) => self.operands_equal(subject, v),
585 WhenTest::Range(lo, hi) => {
586 let s = self.eval_decimal(subject);
587 s >= self.eval_decimal(lo) && s <= self.eval_decimal(hi)
588 }
589 WhenTest::Cond(cond) => self.eval_cond(cond),
590 }
591 }
592
593 /// ¿Son iguales dos operandos? (Para las ramas `WHEN` del `EVALUATE`.)
594 fn operands_equal(&self, a: &Operand, b: &Operand) -> bool {
595 if self.is_text(a) || self.is_text(b) {
596 cobol_text_cmp(&self.eval_text(a), &self.eval_text(b)).is_eq()
597 } else {
598 self.eval_decimal(a) == self.eval_decimal(b)
599 }
600 }
601
602 /// La suma de una lista de operandos.
603 fn fold_sum(&self, ops: &[Operand]) -> Decimal {
604 let mut acc = Decimal::zero();
605 for o in ops {
606 acc = acc.add(&self.eval_decimal(o));
607 }
608 acc
609 }
610
611 /// Los dígitos fraccionarios de un destino numérico.
612 fn target_scale(&self, op: &Operand) -> u8 {
613 if let Some((key, idx)) = self.resolve(op) {
614 if let Some(Cell::Num(arr)) = self.fields.get(&key) {
615 if let Some(n) = arr.get(idx) {
616 return n.picture().fraction_digits;
617 }
618 }
619 }
620 4
621 }
622
623 /// El número de repeticiones de un `PERFORM ... TIMES`.
624 fn count_of(&self, op: &Operand) -> usize {
625 let m = self
626 .eval_decimal(op)
627 .rescale(0, Rounding::Truncate)
628 .mantissa();
629 if m < 0 {
630 0
631 } else {
632 m as usize
633 }
634 }
635}
636
637/// División con escala fija; una división por cero da cero.
638fn divide(num: Decimal, den: Decimal, scale: u8) -> Decimal {
639 num.div(&den, scale, Rounding::Truncate)
640 .unwrap_or_else(|_| Decimal::zero())
641}
642
643/// Potencia con exponente entero no negativo; en otro caso da 1.
644fn pow(base: &Decimal, exp: &Decimal) -> Decimal {
645 let e = exp.rescale(0, Rounding::Truncate).mantissa();
646 if !(0..=256).contains(&e) {
647 return Decimal::from_integer(1);
648 }
649 let mut acc = Decimal::from_integer(1);
650 for _ in 0..e {
651 acc = acc.mul(base);
652 }
653 acc
654}
655
656/// El texto que representa una constante figurativa.
657fn figurative_text(f: Figurative) -> &'static str {
658 match f {
659 Figurative::Zero => "0",
660 Figurative::Space => " ",
661 Figurative::Quote => "\"",
662 Figurative::HighValue | Figurative::LowValue | Figurative::Null => "",
663 }
664}
665
666/// El carácter de relleno de una figurativa, para `Text::fill`.
667fn figurative_fill(f: Figurative) -> char {
668 match f {
669 Figurative::Zero => '0',
670 Figurative::Quote => '"',
671 _ => ' ',
672 }
673}