1use super::{FairnessOption, TranslationError, TranslationOptions, TranslationStage, error};
3use crate::{Code, ast::Span};
4use serde::{Deserialize, Serialize};
5
6#[derive(Clone, Debug, Serialize, Deserialize)]
8pub struct SourceOptionArgument {
9 pub text: String,
11 pub span: Span,
13}
14#[derive(Clone, Debug, Serialize, Deserialize)]
16pub struct SourceOptionDeclaration {
17 pub span: Span,
19 pub arguments: Vec<SourceOptionArgument>,
21}
22#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct TranslationContext {
25 pub requested: TranslationOptions,
27 pub effective: TranslationOptions,
29 pub source_declaration: Option<SourceOptionDeclaration>,
31}
32impl TranslationContext {
33 pub(super) fn explicit(options: &TranslationOptions) -> Self {
34 Self {
35 requested: options.clone(),
36 effective: options.clone(),
37 source_declaration: None,
38 }
39 }
40}
41fn whitespace(byte: u8) -> bool {
42 matches!(byte, b' ' | b'\t' | b'\r' | b'\n')
43}
44fn skip_space(bytes: &[u8], mut cursor: usize) -> usize {
45 while bytes.get(cursor).is_some_and(|b| whitespace(*b)) {
46 cursor += 1;
47 }
48 cursor
49}
50fn word_end(bytes: &[u8], mut cursor: usize) -> usize {
51 while bytes.get(cursor).is_some_and(|b| !whitespace(*b)) {
52 cursor += 1;
53 }
54 cursor
55}
56#[must_use]
60pub fn source_options_span(source: &str) -> Option<Span> {
61 let bytes = source.as_bytes();
62 let mut cursor = skip_space(bytes, 0);
63 while cursor < bytes.len() {
64 let end = word_end(bytes, cursor);
65 if source[cursor..].starts_with("PlusCal") {
66 let suffix = source[cursor + 7..].chars().next();
67 if !suffix.is_some_and(|c| c.is_alphabetic() || c == '_') {
68 let next = skip_space(bytes, end);
69 if source[next..].starts_with("options")
70 && !source[next + 7..]
71 .chars()
72 .next()
73 .is_some_and(|c| c.is_alphanumeric() || c == '_')
74 {
75 return Some(Span {
76 start: cursor,
77 end: next + 7,
78 });
79 }
80 }
81 }
82 cursor = skip_space(bytes, end);
83 }
84 None
85}
86fn refused(span: Span, message: &str) -> TranslationError {
87 error(
88 TranslationStage::Normalization,
89 Code::Unsupported,
90 span,
91 format!("unsupported PlusCal source options: {message}"),
92 )
93}
94#[allow(
101 clippy::too_many_lines,
102 reason = "reference ordering and fail-closed partial-option admission remain explicit"
103)]
104pub fn resolve_translation_options(
105 source: &str,
106 requested: &TranslationOptions,
107) -> Result<TranslationContext, TranslationError> {
108 if source.len() > 4_194_304 {
109 return Err(error(
110 TranslationStage::Normalization,
111 Code::Resource,
112 Span::default(),
113 "PlusCal source-option scan exceeds 4 MiB",
114 ));
115 }
116 for (start, word) in source.char_indices().filter(|(start, _)| {
120 *start == 0
121 || source
122 .as_bytes()
123 .get(start - 1)
124 .is_some_and(|b| whitespace(*b))
125 }) {
126 let _ = word;
127 for keyword in ["PlusCal", "options"] {
128 if let Some(tail) = source[start..].strip_prefix(keyword)
129 && tail
130 .chars()
131 .next()
132 .is_some_and(|character| !character.is_ascii())
133 {
134 return Err(refused(
135 Span {
136 start,
137 end: start + keyword.len(),
138 },
139 "unproved Unicode keyword boundary",
140 ));
141 }
142 }
143 }
144 let mut context = TranslationContext::explicit(requested);
145 finish_options(&mut context.effective)?;
146 let Some(header) = source_options_span(source) else {
147 return Ok(context);
148 };
149 let bytes = source.as_bytes();
150 let mut cursor = skip_space(bytes, header.end);
151 if bytes.get(cursor) != Some(&b'(') {
152 return Err(refused(header, "declaration missing opening parenthesis"));
153 }
154 cursor += 1;
155 let mut arguments = Vec::new();
156 loop {
157 cursor = skip_space(bytes, cursor);
158 match bytes.get(cursor) {
159 Some(b')') => {
160 cursor += 1;
161 break;
162 }
163 Some(b',') => {
164 cursor += 1;
165 continue;
166 }
167 None => return Err(refused(header, "declaration missing closing parenthesis")),
168 Some(_) => {}
169 }
170 let start = cursor;
171 while bytes
172 .get(cursor)
173 .is_some_and(|b| !whitespace(*b) && !matches!(*b, b',' | b')'))
174 {
175 cursor += 1;
176 }
177 let span = Span { start, end: cursor };
178 if arguments.len() >= 128 || span.end - span.start > 256 {
179 return Err(error(
180 TranslationStage::Normalization,
181 Code::Resource,
182 span,
183 "PlusCal source-option argument budget reached",
184 ));
185 }
186 arguments.push(SourceOptionArgument {
187 text: source[start..cursor].to_owned(),
188 span,
189 });
190 }
191 let mut fairness = None;
192 let mut index = 0;
193 while let Some(argument) = arguments.get(index) {
194 let setting = match argument.text.as_str() {
195 "-nof" | "nof" => Some(FairnessOption::None),
196 "-wf" | "wf" => Some(FairnessOption::Weak),
197 "-sf" | "sf" => Some(FairnessOption::Strong),
198 "-wfNext" | "wfNext" => Some(FairnessOption::Next),
199 "-label" | "label" => {
200 context.effective.insert_missing_labels = true;
201 None
202 }
203 "-termination" | "termination" => {
204 context.effective.check_termination = true;
205 None
206 }
207 "-noDoneDisjunct" | "noDoneDisjunct" => {
208 context.effective.no_done_disjunct = true;
209 None
210 }
211 "-noold" => {
212 context.effective.no_old = true;
213 None
214 }
215 "-nocfg" => {
216 context.effective.no_configuration = true;
217 None
218 }
219 "-lineWidth" => {
220 index += 1;
221 let width = arguments
222 .get(index)
223 .ok_or_else(|| refused(argument.span, "lineWidth argument missing"))?;
224 context.effective.line_width = width
225 .text
226 .parse::<i32>()
227 .ok()
228 .filter(|n| *n >= 60)
229 .ok_or_else(|| {
230 refused(width.span, "lineWidth expects an i32 value at least 60")
231 })?;
232 None
233 }
234 "-version" | "version" => {
235 index += 1;
236 let version = arguments
237 .get(index)
238 .ok_or_else(|| refused(argument.span, "version argument missing"))?;
239 version_weight(Some(&version.text)).map_err(|mut e| {
240 e.diagnostic.span = version.span;
241 e
242 })?;
243 context.effective.version = Some(version.text.clone());
244 None
245 }
246 "-spec" | "spec" | "-myspec" | "myspec" => {
247 return Err(refused(
248 argument.span,
249 &format!("{} specification-backed translator backend", argument.text),
250 ));
251 }
252 "-labelRoot" | "labelRoot" => {
253 index += 1;
254 let root = arguments
255 .get(index)
256 .ok_or_else(|| refused(argument.span, "label root argument missing"))?;
257 if !root
258 .text
259 .as_bytes()
260 .first()
261 .is_some_and(u8::is_ascii_alphabetic)
262 || !root
263 .text
264 .bytes()
265 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
266 {
267 return Err(refused(root.span, "unproved or invalid label root"));
268 }
269 context.effective.label_root.clone_from(&root.text);
270 None
271 }
272 _ => {
273 return Err(refused(
274 argument.span,
275 &format!("unknown or unproved option argument {}", argument.text),
276 ));
277 }
278 };
279 if let Some(setting) = setting {
280 if fairness.replace(setting).is_some() {
281 return Err(refused(
282 argument.span,
283 "repeated/conflicting fairness has partial reference application",
284 ));
285 }
286 context.effective.fairness = setting;
287 }
288 index += 1;
289 }
290 finish_options(&mut context.effective)?;
291 context.source_declaration = Some(SourceOptionDeclaration {
292 span: Span {
293 start: header.start,
294 end: cursor,
295 },
296 arguments,
297 });
298 Ok(context)
299}
300
301pub(super) fn version_weight(version: Option<&str>) -> Result<i32, TranslationError> {
304 let Some(version) = version else {
305 return Ok(1903);
306 };
307 if version.len() > 256 {
308 return Err(error(
309 TranslationStage::Normalization,
310 Code::Resource,
311 Span::default(),
312 "PlusCal version argument exceeds 256 bytes",
313 ));
314 }
315 let mut value = 0_i32;
316 let mut decimal = false;
317 let mut digits = 0;
318 for byte in version.bytes() {
319 match byte {
320 b'0'..=b'9' => {
321 value = value.wrapping_mul(10).wrapping_add(i32::from(byte - b'0'));
322 if decimal {
323 digits += 1;
324 }
325 if digits > 3 {
326 return Err(refused(Span::default(), "illegal version number"));
327 }
328 }
329 b'.' => decimal = true,
330 _ => return Err(refused(Span::default(), "illegal version number")),
331 }
332 }
333 for _ in digits..3 {
334 value = value.wrapping_mul(10);
335 }
336 if !(0..=1903).contains(&value) {
337 return Err(refused(
338 Span::default(),
339 "illegal or later-than-current version number",
340 ));
341 }
342 Ok(value)
343}
344
345fn finish_options(options: &mut TranslationOptions) -> Result<(), TranslationError> {
346 if options.line_width < 60 {
347 return Err(refused(
348 Span::default(),
349 "lineWidth expects an i32 value at least 60",
350 ));
351 }
352 options.parser.input_version = version_weight(options.version.as_deref())?;
353 if let Some((mode, _)) = &options.specification_backend {
354 return Err(refused(
355 Span::default(),
356 &format!("{mode} specification-backed translator backend"),
357 ));
358 }
359 if options.write_ast {
360 return Err(refused(
361 Span::default(),
362 "writeAST filesystem operation; use --ast or original_ast_at for in-memory original bytes",
363 ));
364 }
365 if options.report_labels {
366 options.insert_missing_labels = true;
367 }
368 if options.check_termination && options.fairness == FairnessOption::Declared {
369 options.fairness = FairnessOption::Weak;
370 }
371 Ok(())
372}
373
374pub(super) fn admit_version_shape(
376 parsed: &crate::Parsed,
377 weight: i32,
378) -> Result<(), TranslationError> {
379 if weight < 1500
380 && (!parsed.algorithm.procedures.is_empty()
381 || matches!(parsed.algorithm.body, crate::ast::Body::Processes(_)))
382 {
383 return Err(refused(
384 parsed.algorithm.span,
385 "pre-1.5 process/procedure AST and translation",
386 ));
387 }
388 Ok(())
389}