1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use std::{num::NonZeroU16, ops::RangeBounds};
use context_error::*;
use crate::{
chemistry::{ELEMENT_PARSE_LIST, Element, MolecularFormula},
helper_functions::{RangeExtension, explain_number_error},
};
impl MolecularFormula {
/// # ProForma v2 molecular formula specification (copied)
/// As no widely accepted specification exists for expressing elemental formulas, we have
/// adapted a standard with the following rules (taken from <https://github.com/rfellers/chemForma>):
/// ## Formula Rule 1
/// A formula will be composed of pairs of atoms and their corresponding cardinality (two Carbon
/// atoms: C2). Pairs SHOULD be separated by spaces but are not required to be. Atoms and
/// cardinality SHOULD NOT be. Also, the Hill system for ordering
/// (<https://en.wikipedia.org/wiki/Chemical_formula#Hill_system>) is preferred, but not
/// required.
/// ```text
/// Example: C12H20O2 or C12 H20 O2
/// ```
/// ## Formula Rule 2
/// Cardinalities must be positive or negative integer values. Zero is not supported. If a
/// cardinality is not included with an atom, it is assumed to be +1.
/// ```text
/// Example: HN-1O2
/// ```
/// ## Formula Rule 3
/// Isotopes will be handled by prefixing the atom with its isotopic number in square brackets.
/// If no isotopes are specified, previous rules apply. If no isotope is specified, then it is
/// assumed the natural isotopic distribution for a given element applies.
/// ```text
/// Example: [13C2][12C-2]H2N
/// Example: [13C2]C-2H2N
/// ```
/// ## Allow charge
/// Allows `:z{x}` to define the charge of a formula, eg `:z+1`, `:z-3`. As defined in ProForma
/// 2.1.
/// ## Allow empty
/// Allows an empty string, `(empty)`, or a definition that leads to an empty formula (eg `H0`
/// or `H4H-4`) to be used to denote an empty formula
/// # Errors
/// If the formula is not valid according to the above specification, with some help on what is
/// going wrong.
///
/// ```rust
/// use mzcore::prelude::*;
/// // Examples from the spec
/// assert!(
/// MolecularFormula::pro_forma::<false, false>(
/// "C12H20O2"
/// )
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, false>(
/// "C12 H20 O2"
/// )
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, false>(
/// "HN-1O2"
/// )
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, false>(
/// "[13C2][12C-2]H2N"
/// )
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, false>(
/// "[13C2]C-2H2N"
/// )
/// .is_ok()
/// );
/// // ProForma 2.1 style charges
/// assert!(
/// MolecularFormula::pro_forma::<true, false>(
/// "N1H4:z+1"
/// )
/// .is_ok()
/// );
/// // Empty formulas only accepted if `ALLOW_EMPTY` is true
/// assert!(
/// MolecularFormula::pro_forma::<false, false>("H0")
/// .is_err()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, true>("H0")
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, true>(
/// "(empty)"
/// )
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, true>("")
/// .is_ok()
/// );
/// assert!(
/// MolecularFormula::pro_forma::<false, true>("H4H-4")
/// .is_ok()
/// );
/// ```
pub fn pro_forma<const ALLOW_CHARGE: bool, const ALLOW_EMPTY: bool>(
value: &str,
) -> Result<Self, BoxedError<'_, BasicKind>> {
Self::pro_forma_inner::<ALLOW_CHARGE, ALLOW_EMPTY>(
&Context::default().lines(0, value),
value,
0..value.len(),
)
}
/// This parses a substring of the given string as a ProForma molecular formula definition.
/// Additionally, this allows passing a base context to allow to set the line index and source
/// and other properties. Note that the base context is assumed to contain the full line at
/// line index 0.
///
/// # Errors
/// It fails when the string is not a valid ProForma molecular formula string.
pub fn pro_forma_inner<'a, const ALLOW_CHARGE: bool, const ALLOW_EMPTY: bool>(
base_context: &Context<'a>,
value: &'a str,
range: impl RangeBounds<usize>,
) -> Result<Self, BoxedError<'a, BasicKind>> {
let mut index = range.start_index();
let end = range.end_index_exclusive(value.len());
if (index..end).is_empty() || index >= end || &value[index..end] == "(empty)" {
return if ALLOW_EMPTY {
Ok(Self::default())
} else {
Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
"The formula is empty",
base_context.clone().add_highlight((0, range)),
))
};
}
let mut element = None;
let bytes = value.as_bytes();
let mut result = Self::default();
'main_parse_loop: while index < end {
match (bytes[index], element) {
(b'[', _) => {
// Skip the open square bracket and leading spaces
index += 1 + bytes[index + 1..].iter().take_while(|b| **b == b' ').count();
let len =
bytes.iter().skip(index).position(|c| *c == b']').ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
"No closing square bracket found",
base_context.clone().add_highlight((0, index, 1)),
)
})?;
let isotope =
bytes.iter().skip(index).take_while(|c| c.is_ascii_digit()).count();
let ws1 = bytes[index + isotope..].iter().take_while(|b| **b == b' ').count();
let ele = bytes
.iter()
.skip(index + isotope + ws1)
.take_while(|c| c.is_ascii_alphabetic())
.count();
for possible in ELEMENT_PARSE_LIST {
if &value[index + isotope + ws1..index + isotope + ws1 + ele] == possible.0
{
element = Some(possible.1);
break;
}
}
if let Some(parsed_element) = element {
let ws2 = bytes[index + isotope + ws1 + ele..]
.iter()
.take_while(|c| **c == b' ')
.count();
let num_len = bytes[index + isotope + ws1 + ele + ws2..]
.iter()
.take_while(|c| **c == b'-' || **c == b'+' || c.is_ascii_digit())
.count();
let num = value[index + isotope + ws1 + ele + ws2
..index + isotope + ws1 + ele + ws2 + num_len]
.parse::<i32>()
.map_err(|err| {
BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
format!("The element number {}", explain_number_error(&err)),
base_context.clone().add_highlight((
0,
index + isotope + ws1 + ele + ws2,
num_len,
)),
)
})?;
let isotope =
value[index..index + isotope].parse::<NonZeroU16>().map_err(|err| {
BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
format!("The isotope number {}", explain_number_error(&err)),
base_context.clone().add_highlight((0, index, isotope)),
)
})?;
if let Err(err) =
Self::add(&mut result, (parsed_element, Some(isotope), num))
{
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
err.reason(),
base_context.clone().add_highlight((0, index, len)),
));
}
element = None;
index += len + 1;
} else {
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
"Invalid element",
base_context.clone().add_highlight((0, index + isotope, ele)),
));
}
}
(b'-' | b'0'..=b'9', Some(ele)) => {
let length = value[index..end]
.char_indices()
.take_while(|(_, c)| c.is_ascii_digit() || *c == '-')
.last()
.map_or(0, |(i, c)| i + c.len_utf8());
let num = value[index..index + length].parse::<i32>().map_err(|err| {
BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
format!("The element number {}", explain_number_error(&err)),
base_context.clone().add_highlight((0, index, length)),
)
})?;
if num != 0
&& let Err(err) = Self::add(&mut result, (ele, None, num))
{
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
err.reason(),
base_context.clone().add_highlight((
0,
index - ele.symbol().len(),
ele.symbol().len(),
)),
));
}
element = None;
index += length;
}
(b' ' | b'\t', _) => index += 1,
(b':', _) if ALLOW_CHARGE => {
if Some(&b'z') == bytes.get(index + 1) {
index += 2;
let num = value[index..end].parse::<i32>().map_err(|err| {
BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
format!("The charge number is {}", explain_number_error(&err)),
base_context.clone().add_highlight((
0,
index,
end.saturating_sub(index),
)),
)
})?;
let _ = result.add((Element::Electron, None, -num));
break 'main_parse_loop;
}
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
"A charge tag was not set up properly, a charge tag should be formed as ':z<sign><number>'",
base_context.clone().add_highlight((
0,
index.saturating_sub(1),
if bytes.len() < index { 1 } else { 2 },
)),
));
}
_ => {
if let Some(element) = element
&& let Err(err) = Self::add(&mut result, (element, None, 1))
{
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
err.reason(),
base_context.clone().add_highlight((
0,
index - element.symbol().len(),
element.symbol().len(),
)),
));
}
let element_text: String = value[index..].chars().take(2).collect::<String>();
for possible in ELEMENT_PARSE_LIST {
if element_text.starts_with(possible.0) {
element = Some(possible.1);
index += possible.0.len();
continue 'main_parse_loop;
}
}
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
"Not a valid character in formula",
base_context.clone().add_highlight((
0,
index,
value[index..].chars().next().map(char::len_utf8).unwrap_or_default(),
)),
));
}
}
}
if let Some(element) = element
&& let Err(err) = Self::add(&mut result, (element, None, 1))
{
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
err.reason(),
base_context.clone().add_highlight((
0,
index - element.symbol().len(),
element.symbol().len(),
)),
));
}
// Simplify
result.elements.retain(|el| el.2 != 0);
if !ALLOW_EMPTY && result.is_empty() {
Err(BoxedError::new(
BasicKind::Error,
"Invalid ProForma molecular formula",
"The formula is empty",
base_context.clone().add_highlight((0, range)),
))
} else {
Ok(result)
}
}
}
#[test]
#[allow(clippy::missing_panics_doc)]
fn fuzz() {
let _a = MolecularFormula::pro_forma::<true, true>(":");
let _a = MolecularFormula::pro_forma::<true, true>(":1002\\[d2C-2]H2N");
let _a = MolecularFormula::pro_forma::<true, true>("+Wv:z-,33U");
assert!(MolecularFormula::pro_forma::<true, false>("").is_err());
assert!(MolecularFormula::pro_forma::<true, false>("f{}").is_err());
}