1pub use rt::picture::Sym;
2use syntax::ast::{CurrencySign, Environment};
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum Category {
6 Alphanumeric,
7 Numeric,
8 National,
9 NumericEdited,
10 AlphanumericEdited,
11}
12
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Picture {
15 pub category: Category,
16 pub size: u32,
18 pub digits: u32,
19 pub scale: u32,
20 pub signed: bool,
21 pub edit: Option<Vec<Sym>>,
22 pub scaling: u32,
25 pub currency: Option<String>,
27}
28
29#[derive(Clone, Copy, Debug, Default)]
32pub struct Notation<'a> {
33 pub decimal_comma: bool,
34 pub currency: &'a [CurrencySign],
35}
36
37impl<'a> Notation<'a> {
38 pub fn of(environment: &'a Environment) -> Self {
39 Self { decimal_comma: environment.decimal_point_comma, currency: &environment.currency }
40 }
41
42 pub fn currency_value(&self, symbol: char) -> Option<&'a str> {
45 match self.currency {
46 [] => (symbol == '$').then_some("$"),
47 signs => signs.iter().find(|c| c.symbol == symbol).map(|c| c.value.as_str()),
48 }
49 }
50}
51
52const MAX_EDITED: u64 = 4096;
54
55pub const MAX_POSITIONS: u64 = 134_217_727;
57
58pub fn analyse(text: &str) -> Result<Picture, String> {
59 analyse_with(text, Notation::default())
60}
61
62pub fn analyse_with(text: &str, notation: Notation) -> Result<Picture, String> {
66 let (runs, currency) = runs(text, notation)?;
67 if runs.iter().any(|&(c, _)| matches!(c, 'Z' | '*' | '+' | '-' | '.' | ',' | 'B' | '0' | '/' | '$' | 'C' | 'R' | 'D')) {
68 return edited(text, &runs, notation.decimal_comma, currency);
69 }
70 let (mut digits, mut scale, mut signed, mut after_point) = (0u64, 0u64, false, false);
71 let (mut alnum, mut national) = (0u64, 0u64);
72 let (mut left, mut right) = (0u64, 0u64);
73 let misplaced = || Err(format!("PICTURE {text}: P must be one string of scaling positions at the left or right end of the digits"));
74 for (i, &(c, n)) in runs.iter().enumerate() {
75 match c {
76 '9' if right > 0 => return misplaced(),
77 '9' => {
78 digits += n;
79 if after_point {
80 scale += n;
81 }
82 }
83 'S' if i == 0 && n == 1 => signed = true,
84 'V' if left > 0 => return misplaced(),
85 'V' if !after_point && n == 1 => after_point = true,
86 'X' | 'A' => alnum += n,
87 'N' => national += n,
88 'P' if digits == 0 && runs.get(i + 1).is_some_and(|&(c, _)| matches!(c, 'P' | '9')) => left += n,
89 'P' if digits > 0 && left == 0 && !after_point => right += n,
90 'P' => return misplaced(),
91 _ => return Err(format!("PICTURE {text}: {c:?} is not a PICTURE symbol")),
92 }
93 }
94 if alnum + digits > MAX_POSITIONS || national > MAX_POSITIONS {
95 return Err(format!("PICTURE {text}: more than {MAX_POSITIONS} character positions"));
96 }
97 let positions = digits + left + right;
98 if left > 0 {
99 scale = left + digits;
100 }
101 let (digits, scale, alnum, national) = (digits as u32, scale as u32, alnum as u32, national as u32);
102 let scaled = left + right > 0;
103 match (digits > 0, alnum > 0, national > 0) {
104 (true, false, false) if positions <= 31 => Ok(Picture { category: Category::Numeric, size: digits, digits, scale, signed, edit: None, scaling: right as u32, currency: None }),
105 (true, false, false) => Err(format!("PICTURE {text}: more than 31 digits")),
106 (_, true, false) if !signed && !after_point && !scaled => Ok(Picture { category: Category::Alphanumeric, size: alnum + digits, digits: 0, scale: 0, signed, edit: None, scaling: 0, currency: None }),
107 (false, false, true) if !signed && !after_point && !scaled => Ok(Picture { category: Category::National, size: national, digits: 0, scale: 0, signed, edit: None, scaling: 0, currency: None }),
108 _ => Err(format!("PICTURE {text}: mixes symbols of different categories")),
109 }
110}
111
112pub fn blank_when_zero(p: &Picture) -> Result<Picture, String> {
115 if p.signed {
116 return Err("BLANK WHEN ZERO cannot be given for a PICTURE with S".into());
117 }
118 let int = p.digits.saturating_sub(p.scale) as usize;
119 let mut syms = vec![Sym::Nine; int];
120 if p.scale > 0 {
121 syms.push(Sym::Implied);
122 }
123 syms.extend(std::iter::repeat_n(Sym::Nine, p.digits as usize - int));
124 Ok(Picture { category: Category::NumericEdited, edit: Some(syms), ..p.clone() })
125}
126
127fn edited(text: &str, runs: &[(char, u64)], decimal_comma: bool, currency: Option<&str>) -> Result<Picture, String> {
128 let total: u64 = runs.iter().map(|&(_, n)| n).sum();
129 if total > MAX_EDITED {
130 return Err(format!("PICTURE {text}: an edited PICTURE longer than {MAX_EDITED} positions"));
131 }
132 let chars: Vec<char> = runs.iter().flat_map(|&(c, n)| std::iter::repeat_n(c, n as usize)).collect();
133 let bad = |why: &str| Err(format!("PICTURE {text}: {why}"));
134 if chars.iter().any(|c| matches!(c, 'S' | 'N')) {
135 return bad("S and N are not allowed in an edited PICTURE");
136 }
137 if chars.iter().any(|c| matches!(c, 'X' | 'A')) {
138 let mut syms = Vec::new();
139 for &c in &chars {
140 syms.push(match c {
141 'X' | 'A' | '9' => Sym::Char,
142 'B' => Sym::Insert(' '),
143 '0' | '/' => Sym::Insert(c),
144 _ => return bad("an alphanumeric-edited PICTURE takes only X, A, 9, B, 0 and /"),
145 });
146 }
147 let size = syms.len() as u32;
148 return Ok(Picture { category: Category::AlphanumericEdited, size, digits: 0, scale: 0, signed: false, edit: Some(syms), scaling: 0, currency: None });
149 }
150 let (point, comma) = if decimal_comma { (',', '.') } else { ('.', ',') };
151 let floating: Vec<char> = ['+', '-', '$'].into_iter().filter(|f| chars.iter().filter(|c| *c == f).count() >= 2).collect();
152 if floating.len() > 1 {
153 return bad("two floating insertion strings");
154 }
155 let float = floating.first().copied();
156 let (mut syms, mut led, mut i) = (Vec::new(), false, 0);
157 let misplaced = "P must be one string of scaling positions at the left or right end of the digits";
158 let mut scaling: Option<(usize, u32, usize)> = None;
159 while i < chars.len() {
160 let c = chars[i];
161 let next = chars.get(i + 1).copied();
162 if c == 'P' {
163 match &mut scaling {
164 Some((at, n, _)) if *at + *n as usize == i => *n += 1,
165 Some(_) => return bad(misplaced),
166 None => scaling = Some((i, 1, syms.len())),
167 }
168 i += 1;
169 continue;
170 }
171 let sym = match c {
172 'C' if next == Some('R') => {
173 i += 1;
174 Sym::Cr
175 }
176 'D' if next == Some('B') => {
177 i += 1;
178 Sym::Db
179 }
180 c if Some(c) == float && !led => {
181 led = true;
182 Sym::FloatLead(c)
183 }
184 c if Some(c) == float => Sym::Float(c),
185 '+' | '-' => Sym::Sign(c),
186 '$' => Sym::Currency,
187 '9' => Sym::Nine,
188 'Z' => Sym::Z,
189 '*' => Sym::Star,
190 c if c == point => Sym::Point,
191 'V' => Sym::Implied,
192 'B' => Sym::Insert(' '),
193 '0' | '/' => Sym::Insert(c),
194 c if c == comma => Sym::Insert(c),
195 _ => return bad(&format!("{c:?} is not a numeric-edited symbol")),
196 };
197 syms.push(sym);
198 i += 1;
199 }
200 let points = syms.iter().filter(|s| matches!(s, Sym::Point | Sym::Implied)).count();
201 if points > 1 {
202 return bad("more than one decimal point");
203 }
204 let digits = syms.iter().filter(|s| s.is_digit()).count() as u32;
205 let mut scale = syms.iter().skip_while(|s| !matches!(s, Sym::Point | Sym::Implied)).filter(|s| s.is_digit()).count() as u32;
206 let mut right = 0;
207 if let Some((_, n, at)) = scaling {
208 let before = syms[..at].iter().filter(|s| s.is_digit()).count() as u32;
209 match (points, before) {
210 (0, 0) => scale = n + digits,
211 (0, b) if b == digits => right = n,
212 _ => return bad(misplaced),
213 }
214 }
215 if digits == 0 || digits + scaling.map_or(0, |(_, n, _)| n) > 31 {
216 return bad("a numeric-edited PICTURE needs 1 to 31 digit positions");
217 }
218 let widths: u32 = syms.iter().map(|s| s.width() as u32).sum();
219 let size = widths + currency.map_or(0, |v| v.chars().count() as u32 - 1);
220 Ok(Picture { category: Category::NumericEdited, size, digits, scale, signed: false, edit: Some(syms), scaling: right, currency: currency.map(str::to_owned) })
221}
222
223type Runs<'a> = (Vec<(char, u64)>, Option<&'a str>);
225
226fn runs<'a>(text: &str, notation: Notation<'a>) -> Result<Runs<'a>, String> {
229 let mut out: Vec<(char, u64)> = Vec::new();
230 let (mut chars, mut currency) = (text.chars(), None);
231 while let Some(c) = chars.next() {
232 if c == '(' {
233 let count: String = chars.by_ref().take_while(|&d| d != ')').collect();
234 let n: u64 = count.parse().ok().filter(|&n| (1..=MAX_POSITIONS).contains(&n)).ok_or_else(|| format!("PICTURE {text}: bad repetition ({count})"))?;
235 let last = out.last_mut().ok_or_else(|| format!("PICTURE {text}: a repetition with nothing to repeat"))?;
236 last.1 += n - 1;
237 } else if let Some(value) = notation.currency_value(c) {
238 match currency {
239 Some((symbol, _)) if symbol != c => return Err(format!("PICTURE {text}: two different currency symbols")),
240 _ => currency = Some((c, value)),
241 }
242 out.push(('$', 1));
243 } else if c == '$' {
244 return Err(format!("PICTURE {text}: '$' is not a currency symbol of this program, whose CURRENCY SIGN clauses or CURRENCY option name others"));
245 } else {
246 out.push((c.to_ascii_uppercase(), 1));
247 }
248 }
249 Ok((out, currency.map(|(_, value)| value)))
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 const COMMA: Notation = Notation { decimal_comma: true, currency: &[] };
257
258 #[test]
259 fn numeric_pictures() {
260 assert_eq!(analyse("S9(3)V99").unwrap(), Picture { category: Category::Numeric, size: 5, digits: 5, scale: 2, signed: true, edit: None, scaling: 0, currency: None });
261 assert_eq!(analyse("9(18)").unwrap().digits, 18);
262 assert_eq!(analyse("SV9").unwrap().scale, 1);
263 }
264
265 #[test]
266 fn edited_pictures() {
267 let p = analyse("$$,$$9.99CR").unwrap();
268 assert_eq!((p.category, p.size, p.digits, p.scale), (Category::NumericEdited, 11, 6, 2));
269 assert_eq!(p.edit.as_ref().unwrap()[0], Sym::FloatLead('$'));
270 let z = analyse("-ZZ,ZZ9").unwrap();
271 assert_eq!(z.edit.unwrap()[0], Sym::Sign('-'));
272 assert_eq!(analyse("XXBXX/99").unwrap().category, Category::AlphanumericEdited);
273 }
274
275 #[test]
276 fn alphanumeric_and_national() {
277 assert_eq!(analyse("X(512)").unwrap().size, 512);
278 assert_eq!(analyse("N(256)").unwrap().category, Category::National);
279 }
280
281 #[test]
282 fn unsupported_and_invalid_pictures_say_why() {
283 assert!(analyse("ZZ9.99.9").unwrap_err().contains("decimal point"));
284 assert!(analyse("9(32)").unwrap_err().contains("31 digits"));
285 assert!(analyse("XN").unwrap_err().contains("categories"));
286 assert!(analyse("X(999999999)").unwrap_err().contains("repetition"));
287 assert!(analyse("X(134217727)X").unwrap_err().contains("character positions"));
288 assert_eq!(analyse("XX99").unwrap(), Picture { category: Category::Alphanumeric, size: 4, digits: 0, scale: 0, signed: false, edit: None, scaling: 0, currency: None });
289 }
290
291 #[test]
292 fn scaling_positions_left_of_the_digits_raise_the_scale_and_right_of_them_scale_the_value() {
293 let shape = |pic: &str| analyse(pic).map(|p| (p.category, p.size, p.digits, p.scale, p.scaling));
294 assert_eq!(shape("SP(8)9"), Ok((Category::Numeric, 1, 1, 9, 0)));
295 assert_eq!(shape("VPP99"), Ok((Category::Numeric, 2, 2, 4, 0)));
296 assert_eq!(shape("S999PP"), Ok((Category::Numeric, 3, 3, 0, 2)));
297 assert_eq!(shape("99P(6)V"), Ok((Category::Numeric, 2, 2, 0, 6)));
298 assert_eq!(shape("ZZZPP"), Ok((Category::NumericEdited, 3, 3, 0, 2)));
299 for bad in ["P9P", "9P9", "PPV9", "9V9P", "99VPP", "Z.ZPP", "P(31)9"] {
300 assert!(analyse(bad).is_err(), "{bad}");
301 }
302 assert!(analyse("P(30)9").is_ok());
303 }
304
305 #[test]
306 fn under_decimal_point_is_comma_the_comma_is_the_point_and_the_period_an_insertion() {
307 let p = analyse_with("Z.ZZ9,99", COMMA).unwrap();
308 assert_eq!((p.category, p.size, p.digits, p.scale), (Category::NumericEdited, 8, 6, 2));
309 assert_eq!(p.edit.as_ref().unwrap()[1], Sym::Insert('.'));
310 assert_eq!(p.edit.as_ref().unwrap()[5], Sym::Point);
311 assert_eq!(analyse_with("ZZ9.99", Notation::default()).unwrap().scale, 2);
312 assert_eq!(analyse_with("ZZ9.99", COMMA).unwrap().scale, 0);
313 assert!(analyse_with("9,99,9", COMMA).unwrap_err().contains("decimal point"));
314 }
315
316 #[test]
317 fn a_picture_can_end_in_an_insertion_comma_or_the_decimal_point() {
318 let edit = |pic: &str, notation: Notation, value: u128| {
319 let p = analyse_with(pic, notation).unwrap();
320 let point = if notation.decimal_comma { ',' } else { '.' };
321 ((p.category, p.size, p.digits, p.scale), rt::edit::numeric(p.edit.as_ref().unwrap(), p.digits, false, value, false, point, ""))
322 };
323 assert_eq!(edit("9,9,9,", Notation::default(), 123), ((Category::NumericEdited, 6, 3, 0), "1,2,3,".into()));
324 assert_eq!(edit("999.", Notation::default(), 7), ((Category::NumericEdited, 4, 3, 0), "007.".into()));
325 assert_eq!(edit("9.9.9,", COMMA, 123), ((Category::NumericEdited, 6, 3, 0), "1.2.3,".into()));
326 assert_eq!(edit("999.", COMMA, 7), ((Category::NumericEdited, 4, 3, 0), "007.".into()));
327 assert_eq!(analyse_with("999.", COMMA).unwrap().edit.unwrap()[3], Sym::Insert('.'));
328 }
329
330 #[test]
331 fn a_currency_sign_clause_names_the_symbol_and_the_value_it_stands_for() {
332 let signs = [CurrencySign { value: "W".into(), symbol: 'W', hex: None }, CurrencySign { value: "EUR ".into(), symbol: 'e', hex: None }];
333 let notation = Notation { decimal_comma: true, currency: &signs };
334 let w = analyse_with("W9.999,99", notation).unwrap();
335 assert_eq!((w.category, w.size, w.digits, w.scale, w.currency.as_deref()), (Category::NumericEdited, 9, 6, 2, Some("W")));
336 assert_eq!(w.edit.as_ref().unwrap()[0], Sym::Currency);
337 let floating = analyse_with("eeee9,99", notation).unwrap();
338 assert_eq!((floating.size, floating.digits, floating.currency.as_deref()), (11, 6, Some("EUR ")));
339 assert_eq!(floating.edit.as_ref().unwrap()[0], Sym::FloatLead('$'));
340 assert!(analyse_with("$$9", notation).unwrap_err().contains("'$'"));
341 assert!(analyse_with("We9", notation).unwrap_err().contains("two different currency symbols"));
342 assert!(analyse_with("E9", notation).unwrap_err().contains("not a PICTURE symbol"));
343 assert_eq!(analyse("$9").unwrap().currency.as_deref(), Some("$"));
344 }
345
346 #[test]
347 fn blank_when_zero_makes_a_numeric_picture_numeric_edited() {
348 let p = blank_when_zero(&analyse("99V9").unwrap()).unwrap();
349 assert_eq!((p.category, p.size, p.digits, p.scale), (Category::NumericEdited, 3, 3, 1));
350 assert_eq!(p.edit.unwrap(), [Sym::Nine, Sym::Nine, Sym::Implied, Sym::Nine]);
351 assert_eq!(blank_when_zero(&analyse("VPP99").unwrap()).unwrap().edit.unwrap(), [Sym::Implied, Sym::Nine, Sym::Nine]);
352 assert!(blank_when_zero(&analyse("S99").unwrap()).unwrap_err().contains("with S"));
353 }
354}