Skip to main content

dive_api/
original_ast.rs

1//! Original-stage PlusCal AST artifacts, separate from translation admission.
2use crate::{ApiError, TranslationRequest};
3use dive_pluscal::{Code, Diagnostic};
4use serde_json::{Value, json};
5use std::{io::Read as _, path::Path};
6
7/// An in-memory original AST result; it never admits a generated specification.
8#[derive(Clone, Debug)]
9pub struct OriginalAstReport {
10    document: Value,
11    status: u8,
12}
13impl OriginalAstReport {
14    /// Whether exact original AST bytes are available in the report.
15    #[must_use]
16    pub const fn artifact_available(&self) -> bool {
17        self.status == 0
18    }
19    /// Zero artifact, one source rejection, three unsupported/resource, four bug.
20    /// This is the native in-memory operation's exit, not `pcal.trans -writeAST`.
21    #[must_use]
22    pub const fn exit_code(&self) -> u8 {
23        self.status
24    }
25    /// Stage, artifact, option context and explicit non-admission qualifications.
26    #[must_use]
27    pub fn to_json(&self) -> Value {
28        self.document.clone()
29    }
30}
31fn original_artifact_json(artifact: &dive_pluscal::OriginalAstArtifact) -> Value {
32    let mut value = json!(artifact);
33    if let Some(object) = value.as_object_mut() {
34        object.remove("option_context");
35    }
36    value
37}
38fn report(
39    file: &str,
40    request: &TranslationRequest,
41    status: u8,
42    details: Value,
43) -> OriginalAstReport {
44    let mut document = json!({"schema_version":crate::REPORT_SCHEMA_VERSION,"command":"original-ast","file":file,
45        "profile":if request.compat_tlc {"tlc"} else {"dive"},"exit_code":status,
46        "stage":"original-ast","result":match status { 0=>"ast-artifact", 1=>"rejected", 3=>"unsupported", _=>"internal-error" },
47        "artifact_available":status==0,"accepted":false,
48        "generated_module_accepted":false,
49        "writes_performed":false,"requested_translation_options":request.limits});
50    if let (Some(object), Value::Object(extra)) = (document.as_object_mut(), details) {
51        object.extend(extra);
52    }
53    OriginalAstReport { document, status }
54}
55fn failure(file: &str, request: &TranslationRequest, diagnostic: &Diagnostic) -> OriginalAstReport {
56    let status = match diagnostic.code {
57        Code::Unsupported | Code::Resource => 3,
58        Code::Internal => 4,
59        _ => 1,
60    };
61    report(
62        file,
63        request,
64        status,
65        json!({"code":diagnostic.code.as_str(),"diagnostic":diagnostic}),
66    )
67}
68
69/// Returns normalized original AST bytes for one algorithm in a module.
70/// This explicit in-memory operation neither translates nor writes `AST.tla`.
71/// It therefore performs no generated-module analysis or model checking.
72/// Modern procedure/macro ownership and compound source locations use genuine
73/// pre-generation controls; historical fields and full original-stage coverage
74/// remain unfinished. No original-stage header checksum is advertised.
75///
76/// ```
77/// let source = "---- MODULE A ----\n(* --algorithm A begin L:skip; end algorithm *)\n====\n";
78/// let report = dive_api::original_ast_source("A.tla", source, &dive_api::TranslationRequest::default());
79/// assert!(report.artifact_available());
80/// assert_eq!(report.to_json()["accepted"], false);
81/// ```
82#[must_use]
83pub fn original_ast_source(
84    file: &str,
85    source: &str,
86    request: &TranslationRequest,
87) -> OriginalAstReport {
88    if source.len() > 4_194_304 {
89        return failure(
90            file,
91            request,
92            &Diagnostic {
93                code: Code::Resource,
94                span: dive_pluscal::ast::Span::default(),
95                message: "PlusCal module source exceeds 4 MiB".into(),
96            },
97        );
98    }
99    let context = match dive_pluscal::resolve_translation_options(source, &request.limits) {
100        Ok(context) => context,
101        Err(error) => return failure(file, request, &error.diagnostic),
102    };
103    let selection = match dive_pluscal::rewrite::select_rewrite_with_parser(
104        source,
105        &dive_pluscal::rewrite::RewriteOptions::default(),
106        &context.effective.parser,
107    ) {
108        Ok(selection) => selection,
109        Err(diagnostic) => return failure(file, request, &diagnostic),
110    };
111    if let (Some(previous), Some(declaration)) = (selection.previous, &context.source_declaration)
112        && declaration.span.start < previous.end
113        && declaration.span.end > previous.start
114    {
115        return failure(file, request, &Diagnostic { code:Code::Unsupported, span:declaration.span,
116            message:"unsupported PlusCal source option declaration inside previous translation; masking would change the deciding context".into() });
117    }
118    // Shared ownership uses the resolved grammar and limits. A malformed first
119    // algorithm retains its raw candidate and the deciding strict parser error.
120    let region = selection.algorithm;
121    match dive_pluscal::original_ast_at(source, region.start..region.end, &request.limits) {
122        Ok(artifact) => report(
123            file,
124            request,
125            0,
126            json!({"translation_options":artifact.option_context.effective,
127            "source_options":artifact.option_context.source_declaration,"ast_artifact":original_artifact_json(&artifact),
128            "artifact_stage":"normalized-original-before-name-fixing"}),
129        ),
130        Err(error) => failure(file, request, &error.diagnostic),
131    }
132}
133
134/// Reads bounded module source and returns its original AST entirely in memory.
135///
136/// # Errors
137/// An I/O API error if input cannot be read as UTF-8; stage failures are reports.
138pub fn original_ast_file(
139    path: &Path,
140    request: &TranslationRequest,
141) -> Result<OriginalAstReport, ApiError> {
142    let file = path.display().to_string();
143    let reader = std::fs::File::open(path).map_err(|error| ApiError::Io {
144        path: file.clone(),
145        error,
146    })?;
147    let mut bytes = Vec::new();
148    reader
149        .take(4_194_305)
150        .read_to_end(&mut bytes)
151        .map_err(|error| ApiError::Io {
152            path: file.clone(),
153            error,
154        })?;
155    if bytes.len() > 4_194_304 {
156        return Ok(failure(
157            &file,
158            request,
159            &Diagnostic {
160                code: Code::Resource,
161                span: dive_pluscal::ast::Span::default(),
162                message: "PlusCal module source exceeds 4 MiB".into(),
163            },
164        ));
165    }
166    let source = String::from_utf8(bytes).map_err(|error| ApiError::Io {
167        path: file.clone(),
168        error: std::io::Error::new(std::io::ErrorKind::InvalidData, error),
169    })?;
170    Ok(original_ast_source(&file, &source, request))
171}