tawasuyu

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198635 Definitions

⎇ 3902763daa94397756ff2394116daef97814090a crates/modules/charka/charka-shadow/src/interp.rs Rust · 595 lines · 20.2 KB History Who touched what raw

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