Skip to main content

dive_pluscal/translate/
checksum.rs

1//! Bounded serialization of the original and post-translation ASTs, matching
2//! the pinned translator's output.
3use super::{
4    FairnessOption, TranslationError, TranslationOptions, TranslationStage, error, labels, lower,
5    macros,
6};
7use crate::{
8    Code,
9    ast::{
10        BindingKind, Block, Body, Branch, Decl, Expr, Fairness, Label, Process, Span,
11        StatementKind, StmtId, WithBinding,
12    },
13};
14use serde::{Deserialize, Serialize};
15
16/// Exact reference AST bytes and the corresponding algorithm checksum.
17/// This is serialization evidence, not TLA admission or a model proof.
18#[derive(Clone, Debug, Serialize, Deserialize)]
19pub struct AlgorithmChecksum {
20    /// Pinned `AST.toString()` bytes of the original stored AST after generation.
21    /// The separately exploded `xast` is not this algorithm-header CRC authority.
22    pub serialized_ast: String,
23    /// Pinned CRC, including the recorded `--fair` precedence limitation.
24    pub checksum: String,
25}
26pub(super) fn unsupported(span: Span, detail: &str) -> TranslationError {
27    error(
28        TranslationStage::Normalization,
29        Code::Unsupported,
30        span,
31        format!("unsupported post-translation AST checksum: {detail}"),
32    )
33}
34type Groups = Vec<(String, Vec<StmtId>)>;
35pub(super) fn flatten(
36    parsed: &macros::Expanded,
37    ids: &[StmtId],
38    span: Span,
39) -> Result<Vec<StmtId>, TranslationError> {
40    let mut pending: Vec<_> = ids.iter().rev().copied().collect();
41    let mut flat = Vec::new();
42    let mut visited = 0usize;
43    while let Some(id) = pending.pop() {
44        visited = visited.saturating_add(1);
45        if visited > parsed.statements.len() {
46            return Err(unsupported(span, "non-tree statement references"));
47        }
48        let statement = parsed
49            .statement(id)
50            .ok_or_else(|| unsupported(span, "invalid statement reference"))?;
51        if let StatementKind::Block(block) = &statement.kind {
52            if statement.label.is_some() {
53                return Err(unsupported(statement.span, "labelled C block wrapper"));
54            }
55            pending.extend(block.statements.iter().rev().copied());
56        } else {
57            flat.push(id);
58        }
59    }
60    Ok(flat)
61}
62pub(super) fn groups(
63    parsed: &macros::Expanded,
64    block: &Block,
65) -> Result<(Vec<StmtId>, Groups), TranslationError> {
66    let mut unlabelled = Vec::new();
67    let mut groups: Groups = Vec::new();
68    for id in flatten(parsed, &block.statements, block.span)? {
69        let statement = parsed
70            .statement(id)
71            .ok_or_else(|| unsupported(block.span, "invalid statement reference"))?;
72        if let Some(label) = &statement.label {
73            groups.push((label.name.text.clone(), Vec::new()));
74        }
75        if let Some((_, ids)) = groups.last_mut() {
76            ids.push(id);
77        } else {
78            unlabelled.push(id);
79        }
80    }
81    Ok((unlabelled, groups))
82}
83type TokenPositions = Vec<(usize, (usize, usize))>;
84pub(super) fn token_positions(
85    parsed: &macros::Expanded,
86) -> Result<TokenPositions, TranslationError> {
87    token_positions_parts(&parsed.source, &parsed.tokens, parsed.algorithm.span)
88}
89fn token_positions_parts(
90    source: &str,
91    tokens: &[crate::ast::Token],
92    span: Span,
93) -> Result<TokenPositions, TranslationError> {
94    let mut positions = Vec::with_capacity(tokens.len());
95    let mut tokens = tokens.iter().peekable();
96    let mut line = 0;
97    let mut column = 0;
98    for (offset, character) in source.char_indices() {
99        if tokens
100            .peek()
101            .is_some_and(|token| token.span.start == offset)
102        {
103            positions.push((offset, (line, column)));
104            tokens.next();
105        }
106        match character {
107            '\n' => {
108                line += 1;
109                column = 0;
110            }
111            '\t' => column += 8 - column % 8,
112            '\r' if source.as_bytes().get(offset + 1) == Some(&b'\n') => {}
113            '\r' => {
114                return Err(unsupported(span, "bare carriage-return line semantics"));
115            }
116            _ => column += character.len_utf16(),
117        }
118    }
119    if tokens.next().is_some() {
120        return Err(unsupported(span, "unknown expression token location"));
121    }
122    Ok(positions)
123}
124struct Writer {
125    positions: TokenPositions,
126    debug: bool,
127    text: String,
128    indents: Vec<usize>,
129    limit: usize,
130    span: Span,
131}
132impl Writer {
133    fn location(&self, at: Option<usize>) -> Result<String, TranslationError> {
134        if !self.debug {
135            return Ok(String::new());
136        }
137        let (line, column) = if let Some(at) = at {
138            let index = self
139                .positions
140                .binary_search_by_key(&at, |(offset, _)| *offset)
141                .map_err(|_| unsupported(self.span, "debug source location"))?;
142            let (line, column) = self.positions[index].1;
143            (line + 1, column + 1)
144        } else {
145            (0, 0)
146        };
147        Ok(format!("(*{line}, {column}*)"))
148    }
149    fn located_indent(&mut self, at: Option<usize>) -> Result<(), TranslationError> {
150        let prefix = self.location(at)?;
151        self.indent(&prefix)
152    }
153    fn statement_at(parsed: &macros::Expanded, id: StmtId) -> Result<usize, TranslationError> {
154        let statement = parsed
155            .statement(id)
156            .ok_or_else(|| unsupported(parsed.algorithm.span, "invalid debug statement"))?;
157        let begin = statement
158            .label
159            .as_ref()
160            .map_or(statement.span.start, |label| label.span.end);
161        let index = parsed
162            .tokens
163            .partition_point(|token| token.span.start < begin);
164        parsed
165            .tokens
166            .get(index)
167            .filter(|token| token.span.start < statement.span.end)
168            .map(|token| token.span.start)
169            .ok_or_else(|| unsupported(statement.span, "debug statement token"))
170    }
171    fn push(&mut self, text: &str) -> Result<(), TranslationError> {
172        if self.text.len().saturating_add(text.len()) > self.limit {
173            return Err(error(
174                TranslationStage::Generation,
175                Code::Resource,
176                self.span,
177                "PlusCal AST serialization byte limit reached",
178            ));
179        }
180        self.text.push_str(text);
181        Ok(())
182    }
183    fn indent(&mut self, prefix: &str) -> Result<(), TranslationError> {
184        let indent = self
185            .indents
186            .last()
187            .copied()
188            .unwrap_or_default()
189            .saturating_add(prefix.len());
190        self.push(prefix)?;
191        self.indents.push(indent);
192        Ok(())
193    }
194    fn end(&mut self) {
195        self.indents.pop();
196    }
197    fn newline(&mut self) -> Result<(), TranslationError> {
198        self.push("\n")?;
199        let indent = self.indents.last().copied().unwrap_or_default();
200        for _ in 0..indent {
201            self.push(" ")?;
202        }
203        Ok(())
204    }
205    fn sequence<T>(
206        &mut self,
207        items: &[T],
208        mut item: impl FnMut(&mut Self, &T) -> Result<(), TranslationError>,
209    ) -> Result<(), TranslationError> {
210        self.indent("<<")?;
211        for (i, value) in items.iter().enumerate() {
212            if i > 0 {
213                self.push(", ")?;
214                self.newline()?;
215            }
216            item(self, value)?;
217        }
218        self.push(">>")?;
219        self.end();
220        Ok(())
221    }
222    fn declarations(
223        &mut self,
224        parsed: &macros::Expanded,
225        declarations: &[Decl],
226    ) -> Result<(), TranslationError> {
227        self.sequence(declarations, |writer, v| {
228            writer.located_indent(Some(v.name.span.start))?;
229            writer.push("[var |-> \"")?;
230            writer.push(&v.name.text)?;
231            writer.push("\", eqOrIn |-> ")?;
232            writer.push(
233                if v.initial
234                    .as_ref()
235                    .is_none_or(|initial| initial.kind == BindingKind::Equal)
236                {
237                    "\"=\""
238                } else {
239                    "\"\\\\in\""
240                },
241            )?;
242            writer.push(", val |-> ")?;
243            if let Some(initial) = &v.initial {
244                writer.expression(parsed, Some(initial.expression))?;
245            } else {
246                writer.push("<< \"defaultInitValue\" >>")?;
247            }
248            writer.push("]")?;
249            writer.end();
250            Ok(())
251        })
252    }
253    fn statements(
254        &mut self,
255        parsed: &macros::Expanded,
256        ids: &[StmtId],
257    ) -> Result<(), TranslationError> {
258        self.sequence(ids, |writer, id| writer.statement(parsed, *id))
259    }
260    fn quoted_labels(&mut self, labels: &[&Label], modifier: char) -> Result<(), TranslationError> {
261        self.indent("<<")?;
262        let mut first = true;
263        for label in labels
264            .iter()
265            .filter(|label| label.modifier == Some(modifier))
266        {
267            if !first {
268                self.push(", ")?;
269            }
270            first = false;
271            self.push("\"")?;
272            self.push(&label.name.text)?;
273            self.push("\"")?;
274        }
275        self.push(">>")?;
276        self.end();
277        Ok(())
278    }
279    fn process(
280        &mut self,
281        parsed: &macros::Expanded,
282        process: &Process,
283        labels: &[&Label],
284        options: &TranslationOptions,
285    ) -> Result<(), TranslationError> {
286        let process_at = parsed
287            .tokens
288            .iter()
289            .find(|token| {
290                token.span.start >= process.span.start
291                    && token.span.end <= process.name.span.start
292                    && token.text == "process"
293            })
294            .map_or(process.span.start, |token| token.span.start);
295        self.located_indent(Some(process_at))?;
296        self.push("[name   |-> \"")?;
297        self.push(&process.name.text)?;
298        self.push("\",")?;
299        self.newline()?;
300        self.push(" fairness |-> \"")?;
301        // ParseAlgorithm 377–394 records declared fairness even under -nof;
302        // wf/sf only supply missing declarations. Generator suppression is a
303        // separate contract and must not alter the serialized source AST.
304        let fairness = match (process.fairness, options.fairness) {
305            (Fairness::Unfair, FairnessOption::Weak) => Fairness::Weak,
306            (Fairness::Unfair, FairnessOption::Strong) => Fairness::Strong,
307            (declared, _) => declared,
308        };
309        self.push(match fairness {
310            Fairness::Unfair => "unfair",
311            Fairness::Weak => "wf",
312            Fairness::Strong => "sf",
313        })?;
314        self.push("\", minusLabels |-> ")?;
315        self.quoted_labels(labels, '-')?;
316        self.push(", plusLabels |->")?;
317        self.quoted_labels(labels, '+')?;
318        self.push(", proceduresCalled |-><<")?;
319        self.push(">>,")?;
320        self.newline()?;
321        self.push(" eqOrIn |-> ")?;
322        self.push(if process.id.kind == BindingKind::Equal {
323            "\"=\""
324        } else {
325            "\"\\\\in\""
326        })?;
327        self.push(",")?;
328        self.newline()?;
329        self.push(" id     |-> ")?;
330        self.expression(parsed, Some(process.id.expression))?;
331        self.push(",")?;
332        self.newline()?;
333        self.indent(" decls  |-> ")?;
334        self.declarations(parsed, &process.variables)?;
335        self.push(",")?;
336        self.end();
337        self.newline()?;
338        self.indent(" body   |-> ")?;
339        let (unlabelled, groups) = groups(parsed, &process.body)?;
340        if !unlabelled.is_empty() {
341            return Err(unsupported(
342                process.body.span,
343                "missing initial process label",
344            ));
345        }
346        self.labelled(parsed, &groups)?;
347        self.push("]")?;
348        self.end();
349        self.end();
350        Ok(())
351    }
352    fn processes(
353        &mut self,
354        parsed: &macros::Expanded,
355        processes: &[Process],
356        options: &TranslationOptions,
357    ) -> Result<(), TranslationError> {
358        // ParseAlgorithm appends modifiers in lexical encounter order. Arena
359        // construction can allocate children before parents; preserve source
360        // order explicitly and index each owner range without repeated walks.
361        let mut labels: Vec<_> = parsed
362            .statements
363            .iter()
364            .filter_map(|statement| statement.label.as_ref())
365            .collect();
366        labels.sort_by_key(|label| label.span.start);
367        self.sequence(processes, |writer, process| {
368            let start = labels.partition_point(|label| label.span.start < process.span.start);
369            let end = labels.partition_point(|label| label.span.start < process.span.end);
370            writer.process(parsed, process, &labels[start..end], options)
371        })
372    }
373    // Keep the exact token/position serialization contract together for audit.
374    #[allow(clippy::too_many_lines)]
375    fn expression(
376        &mut self,
377        parsed: &macros::Expanded,
378        expr: Option<Expr>,
379    ) -> Result<(), TranslationError> {
380        self.push("<< ")?;
381        if let Some(expr) = expr {
382            let diagnostic_span = parsed.origin(expr.span);
383            let text = parsed.text(expr.span).unwrap_or_default();
384            // The shared SANY lexer recognizes proof-step tokens; pinned
385            // PlusCal Tokenize does not. Never invent a reference AST from
386            // that broader lexical surface until its split contract is ported.
387            if dive_syntax::tokens::tokenize_spec(text)
388                .iter()
389                .any(|token| {
390                    use dive_syntax::SyntaxKind::{
391                        STEP_BARE, STEP_DOT, STEP_IMPLICIT, STEP_NUMBER, STEP_UNNUMBERED,
392                    };
393                    matches!(
394                        token.kind,
395                        STEP_NUMBER | STEP_IMPLICIT | STEP_DOT | STEP_BARE | STEP_UNNUMBERED
396                    )
397                })
398            {
399                return Err(unsupported(
400                    diagnostic_span,
401                    "proof-step-shaped expression lexer tokens",
402                ));
403            }
404            let tokens = parsed.tokens(expr);
405            let substituted = parsed.substituted(expr);
406            if substituted
407                && tokens
408                    .iter()
409                    .any(|token| matches!(token.text.as_str(), "/\\" | "\\/"))
410            {
411                return Err(unsupported(
412                    diagnostic_span,
413                    "junction columns in substituted macro expressions",
414                ));
415            }
416            let mut located = Vec::with_capacity(tokens.len());
417            let mut previous = None;
418            let mut minimum = usize::MAX;
419            for token in tokens {
420                if substituted {
421                    // ParseAlgorithm substitutes single-line arguments in the
422                    // macro expression's logical line. Provenance spans can
423                    // point to different physical definition/call lines.
424                    located.push((0, 0));
425                    minimum = 0;
426                    continue;
427                }
428                let index = self
429                    .positions
430                    .binary_search_by_key(&token.span.start, |(offset, _)| *offset)
431                    .map_err(|_| {
432                        unsupported(diagnostic_span, "unknown expression token location")
433                    })?;
434                let (line, column) = self.positions[index].1;
435                if previous != Some(line) {
436                    minimum = minimum.min(column);
437                }
438                previous = Some(line);
439                located.push((line, column));
440            }
441            let mut previous = None;
442            for (i, (token, &(line, column))) in tokens.iter().zip(&located).enumerate() {
443                if let Some(before) = previous {
444                    for _ in before..line {
445                        self.push("\n")?;
446                    }
447                }
448                previous = Some(line);
449                if i > 0 {
450                    self.push(", ")?;
451                }
452                if token.text == "/\\" || token.text == "\\/" {
453                    let column = column.saturating_sub(minimum);
454                    self.push(&format!(
455                        "\"(col{column}) {}\"",
456                        token.text.replace('\\', "\\\\")
457                    ))?;
458                    continue;
459                }
460                if let Some(string) = token
461                    .text
462                    .strip_prefix('"')
463                    .and_then(|s| s.strip_suffix('"'))
464                {
465                    self.push("\"\\\"\", \"")?;
466                    self.push(string)?;
467                    self.push("\", \"\\\"\"")?;
468                } else {
469                    self.push("\"")?;
470                    if token.text.starts_with('\\') {
471                        self.push("\\")?;
472                    }
473                    self.push(&token.text)?;
474                    self.push("\"")?;
475                }
476            }
477        }
478        self.push(" >>")
479    }
480    #[allow(
481        clippy::too_many_lines,
482        reason = "the pinned AST templates are kept explicit for byte-level review"
483    )]
484    fn statement(&mut self, parsed: &macros::Expanded, id: StmtId) -> Result<(), TranslationError> {
485        let statement = parsed
486            .statement(id)
487            .ok_or_else(|| unsupported(self.span, "invalid statement reference"))?;
488        let at = if self.debug {
489            Self::statement_at(parsed, id)?
490        } else {
491            0
492        };
493        let indented = matches!(
494            statement.kind,
495            StatementKind::Assign(_)
496                | StatementKind::Await { .. }
497                | StatementKind::Assert(_)
498                | StatementKind::Print(_)
499        );
500        if indented {
501            self.located_indent(Some(at))?;
502        } else if self.debug {
503            self.push(&self.location(Some(at))?)?;
504        }
505        let result = match &statement.kind {
506            StatementKind::Call { .. } | StatementKind::Return => Err(unsupported(
507                statement.span,
508                "procedure AST checksum is unavailable",
509            )),
510            StatementKind::Skip => self.push("[type |-> \"skip\"]"),
511            StatementKind::Goto(name) => {
512                self.push("[type |-> \"goto\",  to |-> \"")?;
513                self.push(name.text.trim_matches('"'))?;
514                self.push("\"]")
515            }
516            StatementKind::Await { condition, .. }
517            | StatementKind::Assert(condition)
518            | StatementKind::Print(condition) => {
519                let kind = match statement.kind {
520                    StatementKind::Await { .. } => "when",
521                    StatementKind::Assert(_) => "assert",
522                    _ => "print",
523                };
524                self.push(&format!("[type |-> \"{kind}\", "))?;
525                self.newline()?;
526                self.push(" exp |-> ")?;
527                self.expression(parsed, Some(*condition))?;
528                self.push("]")
529            }
530            StatementKind::Assign(assignments) => {
531                self.push("[type |-> \"assignment\",")?;
532                self.newline()?;
533                self.indent(" ass  |-> ")?;
534                self.sequence(assignments, |writer, a| {
535                    writer.located_indent(Some(a.variable.span.start))?;
536                    writer.push("[lhs |-> ")?;
537                    writer.push(&writer.location(Some(a.variable.span.start))?)?;
538                    writer.push("[var |-> \"")?;
539                    writer.push(&a.variable.text)?;
540                    writer.push("\", sub |-> ")?;
541                    writer.expression(parsed, a.selectors)?;
542                    writer.push("],")?;
543                    writer.newline()?;
544                    writer.push(" rhs |-> ")?;
545                    writer.expression(parsed, Some(a.value))?;
546                    writer.push("]")?;
547                    writer.end();
548                    Ok(())
549                })?;
550                self.push("]")?;
551                self.end();
552                Ok(())
553            }
554            StatementKind::If {
555                branches,
556                otherwise,
557            } => self.if_branches(parsed, branches, otherwise.as_ref()),
558            StatementKind::Either(blocks) => {
559                self.push("[type |-> \"either\", ")?;
560                self.newline()?;
561                self.indent(" ors  |-> ")?;
562                self.indent("<< ")?;
563                for (i, block) in blocks.iter().enumerate() {
564                    if i > 0 {
565                        self.push(", ")?;
566                        self.newline()?;
567                    }
568                    self.plain_block(parsed, block)?;
569                }
570                self.push(" >>")?;
571                self.end();
572                self.push("]")?;
573                self.end();
574                Ok(())
575            }
576            StatementKind::With { bindings, body } => self.with_bindings(parsed, bindings, body),
577            StatementKind::While { test, body } => {
578                let (unlabelled, labelled) = groups(parsed, body)?;
579                self.push("[type    |-> \"while\", ")?;
580                self.newline()?;
581                self.push(" test    |-> ")?;
582                self.expression(parsed, Some(*test))?;
583                self.push(",")?;
584                self.newline()?;
585                self.indent(" labDo   |-> ")?;
586                self.labelled(parsed, &labelled)?;
587                self.push(",")?;
588                self.end();
589                self.newline()?;
590                self.indent(" unlabDo |-> ")?;
591                self.statements(parsed, &unlabelled)?;
592                self.push("]")?;
593                self.end();
594                Ok(())
595            }
596            _ => Err(unsupported(
597                statement.span,
598                "calls or nested statement blocks",
599            )),
600        };
601        if indented {
602            self.end();
603        }
604        result
605    }
606    fn if_branches(
607        &mut self,
608        parsed: &macros::Expanded,
609        branches: &[Branch],
610        otherwise: Option<&Block>,
611    ) -> Result<(), TranslationError> {
612        self.if_branches_from(parsed, branches, otherwise, 0)
613    }
614    fn if_branches_from(
615        &mut self,
616        parsed: &macros::Expanded,
617        branches: &[Branch],
618        otherwise: Option<&Block>,
619        start: usize,
620    ) -> Result<(), TranslationError> {
621        if start >= branches.len() {
622            return Err(unsupported(self.span, "empty conditional AST"));
623        }
624        let mut opened = 0usize;
625        for (index, branch) in branches.iter().enumerate().skip(start) {
626            opened += 1;
627            self.push("[type    |-> \"if\", ")?;
628            self.newline()?;
629            self.push(" test    |-> ")?;
630            self.expression(parsed, Some(branch.test))?;
631            self.push(",")?;
632            self.newline()?;
633            self.indent(" then |-> ")?;
634            self.plain_block(parsed, &branch.body)?;
635            self.push(",")?;
636            self.end();
637            self.newline()?;
638            self.indent(" else |-> ")?;
639            if index + 1 < branches.len() {
640                self.indent("<<")?;
641            } else if let Some(block) = otherwise {
642                self.plain_block(parsed, block)?;
643            } else {
644                self.sequence::<StmtId>(&[], |_, _| Ok(()))?;
645            }
646        }
647        for index in (0..opened).rev() {
648            self.push("]")?;
649            self.end();
650            if index > 0 {
651                self.push(">>")?;
652                self.end();
653            }
654        }
655        Ok(())
656    }
657    fn with_bindings(
658        &mut self,
659        parsed: &macros::Expanded,
660        bindings: &[WithBinding],
661        body: &Block,
662    ) -> Result<(), TranslationError> {
663        if bindings.is_empty() {
664            return Err(unsupported(body.span, "empty With binder AST"));
665        }
666        for (index, binding) in bindings.iter().enumerate() {
667            self.push("[type   |-> \"with\", ")?;
668            self.newline()?;
669            self.push(" var    |-> \"")?;
670            self.push(&binding.name.text)?;
671            self.push("\",")?;
672            self.newline()?;
673            self.push(" eqOrIn |-> ")?;
674            self.push(if binding.binding.kind == BindingKind::Equal {
675                "\"=\""
676            } else {
677                "\"\\\\in\""
678            })?;
679            self.push(",")?;
680            self.newline()?;
681            self.push(" exp    |-> ")?;
682            self.expression(parsed, Some(binding.binding.expression))?;
683            self.push(",")?;
684            self.newline()?;
685            self.indent(" do     |-> ")?;
686            if index + 1 < bindings.len() {
687                self.indent("<<")?;
688            } else {
689                self.plain_block(parsed, body)?;
690            }
691        }
692        for index in (0..bindings.len()).rev() {
693            self.push("]")?;
694            self.end();
695            if index > 0 {
696                self.push(">>")?;
697                self.end();
698            }
699        }
700        Ok(())
701    }
702    fn plain_block(
703        &mut self,
704        parsed: &macros::Expanded,
705        block: &Block,
706    ) -> Result<(), TranslationError> {
707        let flat = flatten(parsed, &block.statements, block.span)?;
708        if flat
709            .iter()
710            .any(|id| parsed.statement(*id).is_none_or(|s| s.label.is_some()))
711        {
712            return Err(unsupported(block.span, "branch-internal labelled AST"));
713        }
714        self.statements(parsed, &flat)
715    }
716    fn labelled(
717        &mut self,
718        parsed: &macros::Expanded,
719        groups: &Groups,
720    ) -> Result<(), TranslationError> {
721        self.sequence(groups, |writer, (label, ids)| {
722            let id = ids
723                .first()
724                .copied()
725                .ok_or_else(|| unsupported(writer.span, "empty labelled statement"))?;
726            let at = if writer.debug {
727                Some(Self::statement_at(parsed, id)?)
728            } else {
729                None
730            };
731            writer.located_indent(at)?;
732            writer.push("[label |-> \"")?;
733            writer.push(label)?;
734            writer.push("\",")?;
735            writer.newline()?;
736            writer.indent(" stmts |-> ")?;
737            writer.statements(parsed, ids)?;
738            writer.push("]")?;
739            writer.end();
740            writer.end();
741            Ok(())
742        })
743    }
744}
745
746/// Serialize exact procedure-free algorithm checksum shapes.
747/// Expression layout, macros, labels and supported debug locations follow the
748/// pinned serializer. Unsupported serialization returns a named diagnostic;
749/// translation and rewriting use an optional checksum and proceed without it.
750/// Procedure header transfer emulation is intentionally unavailable.
751///
752/// # Errors
753/// Named source/normalization/unsupported/resource diagnostics; no partial CRC.
754#[allow(
755    clippy::too_many_lines,
756    reason = "ordered bounded AST admission and top-level reference serialization remain together"
757)]
758pub fn algorithm_checksum_at(
759    source: &str,
760    region: std::ops::Range<usize>,
761    options: &TranslationOptions,
762) -> Result<AlgorithmChecksum, TranslationError> {
763    std::thread::scope(|scope| {
764        let worker = std::thread::Builder::new()
765            .name("dive-pluscal-checksum".into())
766            .stack_size(16 * 1024 * 1024)
767            .spawn_scoped(scope, || {
768                serialize_inline(source, region, options, false).map(|(header, _, _)| header)
769            })
770            .map_err(|failure| {
771                error(
772                    TranslationStage::Generation,
773                    Code::Resource,
774                    Span::default(),
775                    format!("cannot start PlusCal checksum worker: {failure}"),
776                )
777            })?;
778        worker.join().map_err(|_| {
779            error(
780                TranslationStage::Generation,
781                Code::Internal,
782                Span::default(),
783                "PlusCal checksum worker failed; report this input as a bug",
784            )
785        })?
786    })
787}
788#[allow(
789    clippy::too_many_lines,
790    reason = "ordered bounded AST admission and top-level reference serialization remain together"
791)]
792fn serialize_inline(
793    source: &str,
794    region: std::ops::Range<usize>,
795    options: &TranslationOptions,
796    original_stage: bool,
797) -> Result<(AlgorithmChecksum, String, super::TranslationContext), TranslationError> {
798    let context = super::resolve_translation_options(source, options)?;
799    let options = &context.effective;
800    let mut parser = options.parser.clone();
801    parser.input_version = super::options::version_weight(options.version.as_deref())?;
802    let parsed =
803        crate::parse_at(source, region, &parser).map_err(|diagnostic| TranslationError {
804            stage: TranslationStage::Source,
805            diagnostic,
806        })?;
807    super::options::admit_version_shape(&parsed, parser.input_version)?;
808    let algorithm = &parsed.algorithm;
809    if original_stage {
810        return serialize_original(
811            &parsed,
812            options,
813            context.clone(),
814            parser.input_version,
815            false,
816        );
817    }
818    if !algorithm.procedures.is_empty() {
819        return Err(unsupported(
820            algorithm.span,
821            "procedure AST checksum is unavailable",
822        ));
823    }
824    if options.debug {
825        return serialize_original(
826            &parsed,
827            options,
828            context.clone(),
829            parser.input_version,
830            true,
831        );
832    }
833    for statement in &parsed.statements {
834        if !options.debug
835            && let StatementKind::MacroCall { arguments, .. } = &statement.kind
836        {
837            for argument in arguments {
838                if parsed
839                    .text(argument.span)
840                    .is_some_and(|text| text.contains(['\n', '\r']))
841                {
842                    return Err(unsupported(
843                        argument.span,
844                        "multiline macro argument layout",
845                    ));
846                }
847            }
848        }
849    }
850    let mut parsed = macros::expand(parsed, options)?;
851    labels::normalize(&mut parsed, options)?;
852    // The exact CRC operation retains its serializer boundary. Generation and
853    // rewriting do not depend on this narrower operation succeeding.
854    lower::normalize(&parsed, options)?;
855    let sequential = matches!(parsed.algorithm.body, Body::Sequential(_));
856    let mut w = Writer {
857        positions: token_positions(&parsed)?,
858        debug: options.debug,
859        text: String::new(),
860        indents: vec![0],
861        limit: options.max_output_bytes.min(4_194_304),
862        span: parsed.algorithm.span,
863    };
864    w.located_indent(None)?;
865    w.push(if sequential {
866        "[type     |-> \"uniprocess\", "
867    } else {
868        "[type    |-> \"multiprocess\", "
869    })?;
870    w.newline()?;
871    w.push(" name  |-> \"")?;
872    w.push(&parsed.algorithm.name.text)?;
873    w.push("\", ")?;
874    w.newline()?;
875    w.indent(if sequential {
876        " decls  |-> "
877    } else {
878        " decls |-> "
879    })?;
880    w.declarations(&parsed, &parsed.algorithm.variables)?;
881    w.push(",")?;
882    w.end();
883    w.newline()?;
884    w.push(if sequential {
885        " defs   |-> "
886    } else {
887        " defs  |-> "
888    })?;
889    w.expression(&parsed, parsed.algorithm.definitions)?;
890    w.push(",")?;
891    w.newline()?;
892    w.indent(if sequential {
893        " prcds  |-> "
894    } else {
895        " prcds |-> "
896    })?;
897    w.sequence::<StmtId>(&[], |_, _| Ok(()))?;
898    w.push(",")?;
899    w.end();
900    w.newline()?;
901    match &parsed.algorithm.body {
902        Body::Sequential(block) => {
903            let (unlabelled, groups) = groups(&parsed, block)?;
904            if !unlabelled.is_empty() {
905                return Err(unsupported(block.span, "missing initial normalized label"));
906            }
907            w.indent(" body  |-> ")?;
908            w.labelled(&parsed, &groups)?;
909        }
910        Body::Processes(processes) => {
911            w.indent(" procs |-> ")?;
912            w.processes(&parsed, processes, options)?;
913        }
914    }
915    w.push("]")?;
916    w.end();
917    w.end();
918    let fair = parsed.algorithm.fairness == Fairness::Weak;
919    // AST CRC includes newline bytes, unlike the generated-body line CRC.
920    let checksum = crate::rewrite::crc32(if fair {
921        "fair".as_bytes()
922    } else {
923        w.text.as_bytes()
924    });
925    let original_fairness = if sequential && (fair || parsed.algorithm.legacy_fair) {
926        "wf"
927    } else {
928        super::fairness_name(options.fairness)
929    }
930    .to_owned();
931    Ok((
932        AlgorithmChecksum {
933            serialized_ast: w.text,
934            checksum,
935        },
936        original_fairness,
937        context,
938    ))
939}
940
941fn serialize_original(
942    parsed: &crate::Parsed,
943    options: &TranslationOptions,
944    context: super::TranslationContext,
945    input_version: i32,
946    header: bool,
947) -> Result<(AlgorithmChecksum, String, super::TranslationContext), TranslationError> {
948    if input_version < 1500
949        && (!parsed.algorithm.procedures.is_empty() || !parsed.algorithm.macros.is_empty())
950    {
951        return Err(unsupported(
952            parsed.algorithm.span,
953            "historical original procedure/macro AST fields",
954        ));
955    }
956    labels::validate_root(options, parsed.algorithm.span)?;
957    token_positions_parts(&parsed.source, &parsed.tokens, parsed.algorithm.span)?;
958    let mut settings = options.clone();
959    settings.parser.input_version = input_version;
960    let serialized_ast = if header {
961        super::pcal::serialize_debug_header(parsed, &settings)
962    } else {
963        super::pcal::serialize_original(parsed, &settings)
964    }
965    .map_err(|failure| {
966        let span = failure.at.map_or(parsed.algorithm.span, |at| {
967            parsed
968                .tokens
969                .iter()
970                .find(|token| token.span.start >= at)
971                .map_or(Span { start: at, end: at }, |token| token.span)
972        });
973        error(
974            if failure.in_generation {
975                TranslationStage::Generation
976            } else {
977                TranslationStage::Normalization
978            },
979            failure.code,
980            span,
981            failure.message,
982        )
983    })?;
984    let fair = parsed.algorithm.fairness == Fairness::Weak;
985    let checksum = crate::rewrite::crc32(if fair {
986        b"fair"
987    } else {
988        serialized_ast.as_bytes()
989    });
990    let fairness = if matches!(parsed.algorithm.body, Body::Sequential(_))
991        && (fair || parsed.algorithm.legacy_fair)
992    {
993        "wf"
994    } else {
995        super::fairness_name(options.fairness)
996    }
997    .to_owned();
998    Ok((
999        AlgorithmChecksum {
1000            serialized_ast,
1001            checksum,
1002        },
1003        fairness,
1004        context,
1005    ))
1006}
1007
1008/// The pinned original-stage `AST.tla` contents returned in memory.
1009/// This artifact precedes identifier fixing and generation; it does not certify
1010/// an enclosing module, a model, a header CRC, or a filesystem write.
1011#[derive(Clone, Debug, Serialize, Deserialize)]
1012pub struct OriginalAstArtifact {
1013    /// Exact `AST.toString()` bytes before translation mutates shared nodes.
1014    pub serialized_ast: String,
1015    /// The reference `AST.tla` wrapper, with LF separators.
1016    pub module_source: String,
1017    /// Requested/effective option context.
1018    pub option_context: super::TranslationContext,
1019}
1020
1021/// Returns a bounded normalized original AST using the pinned semantic serializer.
1022/// Modern procedure/macro ownership and compound locations follow the typed
1023/// source stages. Historical fields and broader original-stage coverage remain
1024/// unfinished; availability is not generated-module or model acceptance.
1025/// No Java or filesystem write occurs, and no translation checksum is returned.
1026///
1027/// ```
1028/// let source = "--algorithm A begin L:skip; end algorithm";
1029/// let artifact = dive_pluscal::original_ast_at(source, 0..source.len(),
1030///     &dive_pluscal::TranslationOptions::default())?;
1031/// assert!(artifact.module_source.starts_with("------ MODULE AST -------\n"));
1032/// # Ok::<(), dive_pluscal::TranslationError>(())
1033/// ```
1034///
1035/// # Errors
1036/// Named source, normalization, unsupported or resource diagnostics.
1037pub fn original_ast_at(
1038    source: &str,
1039    region: std::ops::Range<usize>,
1040    options: &TranslationOptions,
1041) -> Result<OriginalAstArtifact, TranslationError> {
1042    std::thread::scope(|scope| {
1043        let worker = std::thread::Builder::new()
1044            .name("dive-pluscal-original-ast".into())
1045            .stack_size(16 * 1024 * 1024)
1046            .spawn_scoped(scope, || {
1047                let (original, fairness, context) = serialize_inline(source, region, options, true).map_err(|mut failure| {
1048                    if let Some(detail) = failure.diagnostic.message.strip_prefix("unsupported post-translation AST checksum: ") {
1049                        failure.diagnostic.message = format!("unsupported original-stage AST serialization: {detail}");
1050                    }
1051                    failure
1052                })?;
1053                let prefix = format!("------ MODULE AST -------\nEXTENDS TLC\nfairness == \"{fairness}\"\n \nast == \n");
1054                let suffix = "\n==========================\n";
1055                if prefix.len().saturating_add(original.serialized_ast.len()).saturating_add(suffix.len())
1056                    > options.max_output_bytes.min(4_194_304) {
1057                    return Err(error(TranslationStage::Generation, Code::Resource, Span::default(),
1058                        "PlusCal AST artifact byte limit reached"));
1059                }
1060                Ok(OriginalAstArtifact {
1061                    module_source: format!("{prefix}{}{suffix}", original.serialized_ast),
1062                    serialized_ast: original.serialized_ast,
1063                    option_context: context,
1064                })
1065            }).map_err(|failure| error(TranslationStage::Normalization, Code::Resource, Span::default(),
1066                format!("cannot start PlusCal original AST worker: {failure}")))?;
1067        worker.join().map_err(|_| {
1068            error(
1069                TranslationStage::Generation,
1070                Code::Internal,
1071                Span::default(),
1072                "PlusCal original AST worker failed; report this input as a bug",
1073            )
1074        })?
1075    })
1076}