tawasuyu

tawasuyu/brahman

Rust 230TOML 69JSON 14HTML 12901 Definiciones

⎇ 2728698f5ef15234be868988d5c330ef6c0f2533 crates/modules/charka/charka-shadow/src/interp.rs Rust · 665 líneas · 22.9 KB Historia Quién tocó qué crudo

feat(charka): INSPECT — contar y reemplazar caracteres 2728698f5 · sergio ·

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,
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
241                        .values
242                        .iter()
243                        .any(|v| self.operands_equal(subject, v))
244                    {
245                        return self.exec_block(&branch.body);
246                    }
247                }
248                self.exec_block(other)
249            }
250            Stmt::StringConcat { sources, into } => {
251                let s: String = sources.iter().map(|o| self.eval_text(o)).collect();
252                self.store_text(into, &s);
253                Flow::Normal
254            }
255            Stmt::Unstring {
256                source,
257                delimiter,
258                into,
259            } => {
260                let src = self.eval_text(source);
261                let delim = self.eval_text(delimiter);
262                let parts: Vec<String> = if delim.is_empty() {
263                    vec![src]
264                } else {
265                    src.split(delim.as_str()).map(|p| p.to_string()).collect()
266                };
267                for (i, target) in into.iter().enumerate() {
268                    let piece = parts.get(i).cloned().unwrap_or_default();
269                    self.store_text(target, &piece);
270                }
271                Flow::Normal
272            }
273            Stmt::Inspect { target, op } => {
274                match op {
275                    InspectOp::TallyingForAll { counter, search } => {
276                        let hay = self.eval_text(target);
277                        let needle = self.eval_text(search);
278                        let n = if needle.is_empty() {
279                            0
280                        } else {
281                            hay.matches(needle.as_str()).count()
282                        };
283                        let cur = self.eval_decimal(counter);
284                        self.store(counter, cur.add(&Decimal::from_integer(n as i128)), false);
285                    }
286                    InspectOp::ReplacingAll { from, to } => {
287                        let hay = self.eval_text(target);
288                        let f = self.eval_text(from);
289                        let t = self.eval_text(to);
290                        let new = if f.is_empty() {
291                            hay
292                        } else {
293                            hay.replace(f.as_str(), t.as_str())
294                        };
295                        self.store_text(target, &new);
296                    }
297                }
298                Flow::Normal
299            }
300            Stmt::Perform(p) => self.exec_perform(p),
301            Stmt::GoTo { target } => {
302                // Aproximación: ejecuta el destino y sale del párrafo.
303                match self.run_paragraph(target) {
304                    Flow::Stop => Flow::Stop,
305                    _ => Flow::Exit,
306                }
307            }
308            Stmt::StopRun | Stmt::Goback => Flow::Stop,
309            Stmt::Exit => Flow::Exit,
310            Stmt::Continue => Flow::Normal,
311            Stmt::Unknown { .. } => Flow::Normal, // verbo no soportado: se omite
312        }
313    }
314
315    fn exec_perform(&mut self, p: &'a Perform) -> Flow {
316        match &p.control {
317            PerformControl::Once => self.run_target(&p.target),
318            PerformControl::Times(n) => {
319                let count = self.count_of(n);
320                for _ in 0..count {
321                    if self.tick() {
322                        return Flow::Stop;
323                    }
324                    if let Flow::Stop = self.run_target(&p.target) {
325                        return Flow::Stop;
326                    }
327                }
328                Flow::Normal
329            }
330            PerformControl::Until(cond) => loop {
331                if self.tick() {
332                    return Flow::Stop;
333                }
334                if self.eval_cond(cond) {
335                    return Flow::Normal;
336                }
337                if let Flow::Stop = self.run_target(&p.target) {
338                    return Flow::Stop;
339                }
340            },
341            PerformControl::Varying {
342                var,
343                from,
344                by,
345                until,
346            } => {
347                let var_op = Operand::Data(var.clone());
348                let start = self.eval_decimal(from);
349                self.store(&var_op, start, false);
350                loop {
351                    if self.tick() {
352                        return Flow::Stop;
353                    }
354                    if self.eval_cond(until) {
355                        return Flow::Normal;
356                    }
357                    if let Flow::Stop = self.run_target(&p.target) {
358                        return Flow::Stop;
359                    }
360                    let next = self.eval_decimal(&var_op).add(&self.eval_decimal(by));
361                    self.store(&var_op, next, false);
362                }
363            }
364        }
365    }
366
367    /// Ejecuta una vez el cuerpo de un `PERFORM`. Un `EXIT` dentro de
368    /// él termina esa pasada, no el programa.
369    fn run_target(&mut self, target: &'a PerformTarget) -> Flow {
370        let flow = match target {
371            PerformTarget::Paragraph { name, .. } => self.run_paragraph(name),
372            PerformTarget::Inline(body) => self.exec_block(body),
373        };
374        match flow {
375            Flow::Stop => Flow::Stop,
376            _ => Flow::Normal,
377        }
378    }
379
380    fn run_paragraph(&mut self, name: &str) -> Flow {
381        let Some(&idx) = self.para_index.get(&name.to_uppercase()) else {
382            return Flow::Normal;
383        };
384        let ir = self.ir;
385        match self.exec_block(&ir.procedures[idx].body) {
386            Flow::Stop => Flow::Stop,
387            _ => Flow::Normal,
388        }
389    }
390
391    /// Resuelve una referencia a dato (escalar o elemento de tabla) a
392    /// su nombre y un índice 0-based. `None` si no es una referencia.
393    fn resolve(&self, op: &Operand) -> Option<(String, usize)> {
394        match op {
395            Operand::Data(name) => Some((name.to_uppercase(), 0)),
396            Operand::Indexed { name, index } => {
397                // El subíndice de COBOL es 1-based.
398                let i = self
399                    .eval_decimal(index)
400                    .rescale(0, Rounding::Truncate)
401                    .mantissa();
402                let idx = if i < 1 { 0 } else { (i - 1) as usize };
403                Some((name.to_uppercase(), idx))
404            }
405            _ => None,
406        }
407    }
408
409    /// `MOVE from` a un solo destino (escalar o elemento de tabla).
410    fn do_move(&mut self, from: &Operand, target: &Operand) {
411        let Some((key, idx)) = self.resolve(target) else {
412            return;
413        };
414        let is_num = matches!(self.fields.get(&key), Some(Cell::Num(_)));
415        if is_num {
416            let v = self.eval_decimal(from);
417            if let Some(Cell::Num(arr)) = self.fields.get_mut(&key) {
418                if let Some(n) = arr.get_mut(idx) {
419                    n.store(v);
420                }
421            }
422        } else if let Operand::Figurative(fig) = from {
423            let ch = figurative_fill(*fig);
424            if let Some(Cell::Text(arr)) = self.fields.get_mut(&key) {
425                if let Some(t) = arr.get_mut(idx) {
426                    t.fill(ch);
427                }
428            }
429        } else {
430            let s = self.eval_text(from);
431            if let Some(Cell::Text(arr)) = self.fields.get_mut(&key) {
432                if let Some(t) = arr.get_mut(idx) {
433                    t.store(&s);
434                }
435            }
436        }
437    }
438
439    /// Almacena un valor en un destino, conformándolo a su tipo.
440    fn store(&mut self, target: &Operand, value: Decimal, rounded: bool) {
441        let Some((key, idx)) = self.resolve(target) else {
442            return;
443        };
444        match self.fields.get_mut(&key) {
445            Some(Cell::Num(arr)) => {
446                if let Some(n) = arr.get_mut(idx) {
447                    if rounded {
448                        n.store_rounded(value);
449                    } else {
450                        n.store(value);
451                    }
452                }
453            }
454            Some(Cell::Text(arr)) => {
455                if let Some(t) = arr.get_mut(idx) {
456                    t.store(&value.to_string());
457                }
458            }
459            None => {}
460        }
461    }
462
463    /// Almacena un texto en un destino, conformándolo a su tipo.
464    fn store_text(&mut self, target: &Operand, text: &str) {
465        let Some((key, idx)) = self.resolve(target) else {
466            return;
467        };
468        match self.fields.get_mut(&key) {
469            Some(Cell::Text(arr)) => {
470                if let Some(t) = arr.get_mut(idx) {
471                    t.store(text);
472                }
473            }
474            Some(Cell::Num(arr)) => {
475                if let Some(n) = arr.get_mut(idx) {
476                    n.store(Decimal::parse(text.trim()).unwrap_or_else(|_| Decimal::zero()));
477                }
478            }
479            None => {}
480        }
481    }
482
483    // ── Evaluación ────────────────────────────────────────────────
484
485    fn eval_decimal(&self, op: &Operand) -> Decimal {
486        match op {
487            Operand::Num(n) => Decimal::parse(n).unwrap_or_else(|_| Decimal::zero()),
488            Operand::Str(s) => Decimal::parse(s).unwrap_or_else(|_| Decimal::zero()),
489            Operand::Figurative(_) => Decimal::zero(),
490            Operand::Data(_) | Operand::Indexed { .. } => {
491                let Some((key, idx)) = self.resolve(op) else {
492                    return Decimal::zero();
493                };
494                match self.fields.get(&key) {
495                    Some(Cell::Num(arr)) => arr
496                        .get(idx)
497                        .map(|n| n.value())
498                        .unwrap_or_else(Decimal::zero),
499                    Some(Cell::Text(arr)) => arr
500                        .get(idx)
501                        .and_then(|t| Decimal::parse(t.as_str().trim()).ok())
502                        .unwrap_or_else(Decimal::zero),
503                    None => Decimal::zero(),
504                }
505            }
506        }
507    }
508
509    fn eval_text(&self, op: &Operand) -> String {
510        match op {
511            Operand::Str(s) => s.clone(),
512            Operand::Num(n) => n.clone(),
513            Operand::Figurative(f) => figurative_text(*f).to_string(),
514            Operand::Data(_) | Operand::Indexed { .. } => {
515                let Some((key, idx)) = self.resolve(op) else {
516                    return String::new();
517                };
518                match self.fields.get(&key) {
519                    Some(Cell::Num(arr)) => arr.get(idx).map(|n| n.display()).unwrap_or_default(),
520                    Some(Cell::Text(arr)) => arr.get(idx).map(|t| t.display()).unwrap_or_default(),
521                    None => String::new(),
522                }
523            }
524        }
525    }
526
527    fn eval_expr(&self, e: &Expr) -> Decimal {
528        match e {
529            Expr::Operand(op) => self.eval_decimal(op),
530            Expr::Neg(inner) => Decimal::zero().sub(&self.eval_expr(inner)),
531            Expr::Binary { op, lhs, rhs } => {
532                let l = self.eval_expr(lhs);
533                let r = self.eval_expr(rhs);
534                match op {
535                    BinOp::Add => l.add(&r),
536                    BinOp::Sub => l.sub(&r),
537                    BinOp::Mul => l.mul(&r),
538                    BinOp::Div => divide(l, r, DIV_SCALE),
539                    BinOp::Pow => pow(&l, &r),
540                }
541            }
542        }
543    }
544
545    fn eval_cond(&self, c: &Cond) -> bool {
546        match c {
547            Cond::Compare { lhs, op, rhs } => {
548                let ord = if self.is_text(lhs) || self.is_text(rhs) {
549                    cobol_text_cmp(&self.eval_text(lhs), &self.eval_text(rhs))
550                } else {
551                    self.eval_decimal(lhs).cmp(&self.eval_decimal(rhs))
552                };
553                match op {
554                    CmpOp::Eq => ord.is_eq(),
555                    CmpOp::Ne => ord.is_ne(),
556                    CmpOp::Lt => ord.is_lt(),
557                    CmpOp::Gt => ord.is_gt(),
558                    CmpOp::Le => ord.is_le(),
559                    CmpOp::Ge => ord.is_ge(),
560                }
561            }
562            Cond::Named(name) => match self.conditions.get(&name.to_uppercase()) {
563                // Un nombre de condición (88): el dato padre igual al
564                // valor que la hace verdadera.
565                Some(cn) => self.operands_equal(&Operand::Data(cn.parent.clone()), &cn.value),
566                None => false,
567            },
568            Cond::Not(inner) => !self.eval_cond(inner),
569            Cond::And(a, b) => self.eval_cond(a) && self.eval_cond(b),
570            Cond::Or(a, b) => self.eval_cond(a) || self.eval_cond(b),
571        }
572    }
573
574    fn is_text(&self, op: &Operand) -> bool {
575        match op {
576            Operand::Str(_) => true,
577            Operand::Data(_) | Operand::Indexed { .. } => match self.resolve(op) {
578                Some((key, _)) => matches!(self.fields.get(&key), Some(Cell::Text(_))),
579                None => false,
580            },
581            _ => false,
582        }
583    }
584
585    /// ¿Son iguales dos operandos? (Para las ramas `WHEN` del `EVALUATE`.)
586    fn operands_equal(&self, a: &Operand, b: &Operand) -> bool {
587        if self.is_text(a) || self.is_text(b) {
588            cobol_text_cmp(&self.eval_text(a), &self.eval_text(b)).is_eq()
589        } else {
590            self.eval_decimal(a) == self.eval_decimal(b)
591        }
592    }
593
594    /// La suma de una lista de operandos.
595    fn fold_sum(&self, ops: &[Operand]) -> Decimal {
596        let mut acc = Decimal::zero();
597        for o in ops {
598            acc = acc.add(&self.eval_decimal(o));
599        }
600        acc
601    }
602
603    /// Los dígitos fraccionarios de un destino numérico.
604    fn target_scale(&self, op: &Operand) -> u8 {
605        if let Some((key, idx)) = self.resolve(op) {
606            if let Some(Cell::Num(arr)) = self.fields.get(&key) {
607                if let Some(n) = arr.get(idx) {
608                    return n.picture().fraction_digits;
609                }
610            }
611        }
612        4
613    }
614
615    /// El número de repeticiones de un `PERFORM ... TIMES`.
616    fn count_of(&self, op: &Operand) -> usize {
617        let m = self
618            .eval_decimal(op)
619            .rescale(0, Rounding::Truncate)
620            .mantissa();
621        if m < 0 {
622            0
623        } else {
624            m as usize
625        }
626    }
627}
628
629/// División con escala fija; una división por cero da cero.
630fn divide(num: Decimal, den: Decimal, scale: u8) -> Decimal {
631    num.div(&den, scale, Rounding::Truncate)
632        .unwrap_or_else(|_| Decimal::zero())
633}
634
635/// Potencia con exponente entero no negativo; en otro caso da 1.
636fn pow(base: &Decimal, exp: &Decimal) -> Decimal {
637    let e = exp.rescale(0, Rounding::Truncate).mantissa();
638    if !(0..=256).contains(&e) {
639        return Decimal::from_integer(1);
640    }
641    let mut acc = Decimal::from_integer(1);
642    for _ in 0..e {
643        acc = acc.mul(base);
644    }
645    acc
646}
647
648/// El texto que representa una constante figurativa.
649fn figurative_text(f: Figurative) -> &'static str {
650    match f {
651        Figurative::Zero => "0",
652        Figurative::Space => " ",
653        Figurative::Quote => "\"",
654        Figurative::HighValue | Figurative::LowValue | Figurative::Null => "",
655    }
656}
657
658/// El carácter de relleno de una figurativa, para `Text::fill`.
659fn figurative_fill(f: Figurative) -> char {
660    match f {
661        Figurative::Zero => '0',
662        Figurative::Quote => '"',
663        _ => ' ',
664    }
665}