Skip to main content

dive_pluscal/
lib.rs

1//! Native source-mapped PlusCal grammar parsing and translation.
2//!
3//! [`parse`] produces a source AST, not a translated TLA+ specification.
4//! [`translate`] follows the pinned translator's normalization, scoped renaming,
5//! expression substitution, process/fairness and procedure semantics. Calls use
6//! runtime stack frames, including recursion. Resource limits and generated-name
7//! collisions remain explicit refusals. Expression slices retain counted nesting;
8//! generation checks TLA+ syntax, and the whole-module API separately checks names
9//! and levels. The original source AST is preserved.
10//! No Java runtime is used by this crate.
11//!
12//! ```
13//! let source = "--algorithm A begin L: skip; end algorithm";
14//! let parsed = dive_pluscal::parse(source, &dive_pluscal::Options::default())?;
15//! assert_eq!(parsed.algorithm.name.text, "A");
16//! assert_eq!(parsed.text(parsed.algorithm.span), Some(source));
17//! # Ok::<(), dive_pluscal::Diagnostic>(())
18//! ```
19#![forbid(unsafe_code)]
20
21pub mod ast;
22mod lexer;
23mod parser;
24/// Bounded source editing and translation-body checksum interoperability.
25pub mod rewrite;
26#[path = "translate/mod.rs"]
27mod translation;
28pub use parser::{Options, parse, parse_at};
29use serde::{Deserialize, Serialize};
30pub use translation::{
31    AlgorithmChecksum, FairnessOption, InsertedLabel, OriginalAstArtifact, ProcessTranslation,
32    SourceOptionArgument, SourceOptionDeclaration, Translation, TranslationContext,
33    TranslationError, TranslationMap, TranslationOptions, TranslationStage, TranslationWarning,
34    algorithm_checksum_at, original_ast_at, resolve_translation_options,
35    source_option_declaration_span, source_options_span, translate, translate_at,
36};
37
38/// Stable native PlusCal diagnostic categories.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub enum Code {
41    /// Invalid lexical token, string or comment.
42    Lexical,
43    /// Missing or unexpected grammar token.
44    Syntax,
45    /// Missing expression or unmatched delimiter.
46    Expression,
47    /// Illegal source label.
48    Label,
49    /// Parser resource bound reached.
50    Resource,
51    /// A parser worker failed unexpectedly; report as an implementation bug.
52    Internal,
53    /// Explicitly unimplemented mode.
54    Unsupported,
55}
56impl Code {
57    /// Stable machine-readable code.
58    #[must_use]
59    pub const fn as_str(self) -> &'static str {
60        match self {
61            Self::Lexical => "DIVE-P0001",
62            Self::Syntax => "DIVE-P0002",
63            Self::Expression => "DIVE-P0003",
64            Self::Label => "DIVE-P0004",
65            Self::Resource => "DIVE-P0040",
66            Self::Internal => "DIVE-P0050",
67            Self::Unsupported => "DIVE-P0090",
68        }
69    }
70}
71/// Deterministic diagnostic over original source bytes.
72#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
73pub struct Diagnostic {
74    /// Stable category.
75    pub code: Code,
76    /// Original bytes, never tab-expanded.
77    pub span: ast::Span,
78    /// Human-readable detail.
79    pub message: String,
80}
81impl std::fmt::Display for Diagnostic {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        write!(
84            f,
85            "{} at {}..{}: {}",
86            self.code.as_str(),
87            self.span.start,
88            self.span.end,
89            self.message
90        )
91    }
92}
93impl std::error::Error for Diagnostic {}
94
95/// Complete source grammar result; translation acceptance is not implied.
96#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
97pub struct Parsed {
98    /// Complete original source retained verbatim.
99    pub source: String,
100    /// Algorithm structure and ranges.
101    pub algorithm: ast::Algorithm,
102    /// Statement arena, indexed by child blocks.
103    pub statements: Vec<ast::Statement>,
104    /// Significant tokens; trivia remains in `source`.
105    pub tokens: Vec<ast::Token>,
106}
107impl Parsed {
108    /// Original text, or `None` for an invalid caller range.
109    #[must_use]
110    pub fn text(&self, span: ast::Span) -> Option<&str> {
111        self.source.get(span.start..span.end)
112    }
113    /// Gets a statement without trusting a caller-provided id.
114    #[must_use]
115    pub fn statement(&self, id: ast::StmtId) -> Option<&ast::Statement> {
116        self.statements.get(id.0)
117    }
118    /// Converts a valid original byte boundary to a display position.
119    /// Tabs advance to the next eight-column stop. Expression spans remain
120    /// original bytes regardless of this optional display conversion.
121    #[must_use]
122    pub fn position(&self, offset: usize) -> Option<ast::Position> {
123        let prefix = self.source.get(..offset)?;
124        let mut line = 1;
125        let mut column = 1;
126        for (index, character) in prefix.char_indices() {
127            match character {
128                '\n' => {
129                    line += 1;
130                    column = 1;
131                }
132                '\t' => column += 8 - (column - 1) % 8,
133                '\r' if self.source.as_bytes().get(index + 1) == Some(&b'\n') => {}
134                _ => column += 1,
135            }
136        }
137        Some(ast::Position { line, column })
138    }
139}