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
// [[file:../parser.note::*docs][docs:1]]
//! Selected and extra winnow parser combinators
// docs:1 ends here

// [[file:../parser.note::273abf0b][273abf0b]]
use crate::common::*;

use winnow::error::StrContext;
use winnow::error::{ContextError, ParserError};
use winnow::stream::Stream;
// 273abf0b ends here

// [[file:../parser.note::0512156a][0512156a]]
pub use winnow::ascii::{alpha0, alpha1, digit0, digit1, line_ending, space0, space1};
pub use winnow::combinator::cut_err;
pub use winnow::combinator::rest;
pub use winnow::combinator::seq;
pub use winnow::combinator::{delimited, preceded, repeat, repeat_till, separated, terminated};
pub use winnow::prelude::*;
pub use winnow::Parser;

pub use line_ending as eol;
pub use rest_line as read_until_eol;
// 0512156a ends here

// [[file:../parser.note::fb1326ab][fb1326ab]]
/// Create context label
pub fn label(s: &'static str) -> StrContext {
    StrContext::Label(s)
}

/// Convert winnow error to anyhow Error with `input` context
pub fn parse_error(e: winnow::error::ParseError<&str, winnow::error::ContextError>, input: &str) -> Error {
    anyhow!("found parse error:\n{:}\ninput={input:?}", e.to_string())
}

/// Anything except whitespace, this parser will not consume "\n" character
pub fn not_space<'a>(input: &mut &'a str) -> PResult<&'a str> {
    winnow::token::take_till(1.., |c| " \t\r\n".contains(c))
        .context(label("not_space"))
        .parse_next(input)
}

/// Read a new line including eol (\n) or consume the rest if there is no eol
/// char.
pub fn read_line<'a>(s: &mut &'a str) -> PResult<&'a str> {
    use winnow::ascii::till_line_ending;
    use winnow::combinator::opt;

    // if there is no newline in `s`, take the whole str
    let o = (till_line_ending, opt(line_ending))
        .recognize()
        .context(label("read_line"))
        .parse_next(s)?;
    Ok(o)
}

/// Take the rest line. The line ending is not included.
pub fn rest_line<'a>(input: &mut &'a str) -> PResult<&'a str> {
    use winnow::ascii::till_line_ending;
    terminated(till_line_ending, line_ending).context(label("rest_line")).parse_next(input)
}

/// Take and consuming to `literal`.
pub fn jump_to<'a>(literal: &str) -> impl FnMut(&mut &str) -> PResult<()> + '_ {
    use winnow::token::take_until;
    move |input: &mut &str| {
        let _: (&str, &str) = (take_until(0.., literal), literal).context(label("jump_to")).parse_next(input)?;
        Ok(())
    }
}

/// Take until found `literal`. The `literal` will not be consumed.
pub fn jump_until<'a>(literal: &str) -> impl FnMut(&mut &str) -> PResult<()> + '_ {
    use winnow::token::take_until;
    move |input: &mut &str| {
        let _: &str = take_until(0.., literal).context(label("jump_until")).parse_next(input)?;
        Ok(())
    }
}

/// A combinator that takes a parser `inner` and produces a parser
/// that also consumes both leading and trailing whitespace, returning
/// the output of `inner`.
pub fn ws<'a, ParseInner, Output, Error>(inner: ParseInner) -> impl Parser<&'a str, Output, Error>
where
    ParseInner: Parser<&'a str, Output, Error>,
    Error: ParserError<&'a str>,
{
    delimited(space0, inner, space0)
}

/// Keep reading lines until the innner parser produces a result
pub fn skip_line_till<'a, O>(inner: impl Parser<&'a str, O, ContextError>) -> impl Parser<&'a str, (), ContextError> {
    repeat_till(0.., rest_line, inner).map(|_: (Vec<_>, _)| ())
}
// fb1326ab ends here

// [[file:../parser.note::3d14b516][3d14b516]]
/// Recognize one or more decimal digits, optionally preceded by sign
pub fn recognize_integer<'i>(input: &mut &'i str) -> PResult<&'i str> {
    use winnow::combinator::opt;
    use winnow::token::one_of;

    let r = (opt(one_of(['+', '-'])), cut_err(digit1)).recognize().parse_next(input)?;
    Ok(r)
}

/// Match one unsigned integer: 123
pub fn unsigned_integer<'a>(input: &mut &'a str) -> PResult<usize> {
    digit1.try_map(|x: &str| x.parse()).context(label("usize")).parse_next(input)
}

/// Match one signed integer: -123 or +123
pub fn signed_integer(s: &mut &str) -> PResult<isize> {
    recognize_integer.try_map(|x: &str| x.parse::<isize>()).parse_next(s)
}

/// Parse a line containing an unsigned integer number.
pub fn read_usize(s: &mut &str) -> PResult<usize> {
    // allow white spaces
    let p = delimited(space0, unsigned_integer, space0);
    terminated(p, line_ending).parse_next(s)
}

/// Parse a line containing many unsigned numbers
pub fn read_usize_many(s: &mut &str) -> PResult<Vec<usize>> {
    let x = seq! {
        _: space0,
        separated(1.., unsigned_integer, space1),
        _: space0,
        _: line_ending,
    }
    .parse_next(s)?;
    Ok(x.0)
}

pub use self::signed_integer as signed_digit;
pub use self::unsigned_integer as unsigned_digit;
// 3d14b516 ends here

// [[file:../parser.note::4ef79da3][4ef79da3]]
/// Parse a f64 float number
pub fn double(input: &mut &str) -> PResult<f64> {
    use winnow::ascii::float;
    float(input)
}

/// Parse a normal float number. The D format code for scientific
/// (exponential) notation is also supported.
pub fn sci_double<'i>(input: &mut &'i str) -> PResult<f64> {
    use winnow::combinator::alt;
    use winnow::combinator::opt;
    use winnow::stream::Located;
    use winnow::token::one_of;

    // e.g. -1.34D+8
    let pre_exponent = (
        opt(one_of(['+', '-'])),
        alt(((digit1, opt(('.', opt(digit1)))).map(|_| ()), ('.', digit1).map(|_| ()))),
    )
        .recognize()
        .parse_next(input)?;

    let f = if let Some(exponent) = opt(preceded(one_of(['e', 'E', 'D', 'd']), recognize_integer)).parse_next(input)? {
        format!("{pre_exponent}E{exponent}")
    } else {
        format!("{pre_exponent}")
    }
    .parse()
    .unwrap();
    Ok(f)
}

/// Consume three float numbers separated by one or more spaces. Return xyz array.
pub fn xyz_array(s: &mut &str) -> PResult<[f64; 3]> {
    let x = seq! {double, _: space1, double, _: space1, double}.parse_next(s)?;
    Ok([x.0, x.1, x.2])
}

/// Parse a line containing a float number possibly surrounded by spaces
pub fn read_double(s: &mut &str) -> PResult<f64> {
    // allow white spaces
    let p = delimited(space0, double, space0);
    terminated(p, line_ending).parse_next(s)
}

/// Parse a line containing many float numbers
pub fn read_double_many(s: &mut &str) -> PResult<Vec<f64>> {
    let x = seq! {
        _: space0,
        separated(1.., double, space1),
        _: space0,
        _: line_ending,
    }
    .parse_next(s)?;
    Ok(x.0)
}
// 4ef79da3 ends here

// [[file:../parser.note::838e8dea][838e8dea]]
/// Convert a string to a float.
///
/// This method performs certain checks, that are specific to quantum
/// chemistry output, including avoiding the problem with Ds instead
/// of Es in scientific notation. Another point is converting string
/// signifying numerical problems (*****) to something we can manage
/// (NaN).
pub fn parse_float(s: &str) -> Option<f64> {
    if s.chars().all(|x| x == '*') {
        std::f64::NAN.into()
    } else {
        s.parse().ok().or_else(|| s.replacen("D", "E", 1).parse().ok())
    }
}

#[test]
fn test_fortran_float() {
    let x = parse_float("14");
    assert_eq!(x, Some(14.0));

    let x = parse_float("14.12E4");
    assert_eq!(x, Some(14.12E4));

    let x = parse_float("14.12D4");
    assert_eq!(x, Some(14.12E4));

    let x = parse_float("****");
    assert!(x.unwrap().is_nan());
}
// 838e8dea ends here

// [[file:../parser.note::10e5dba2][10e5dba2]]
#[test]
fn test_sci_double() -> PResult<()> {
    let s = "-12.34d-1";
    let (_, v) = sci_double.parse_peek(s)?;
    assert_eq!(v, -1.234);

    let s = "-12";
    let (_, v) = sci_double.parse_peek(s)?;
    assert_eq!(v, -12.0);

    let s = "-12.3E-1";
    let (_, v) = sci_double.parse_peek(s)?;
    assert_eq!(v, -1.23);

    Ok(())
}

#[test]
fn test_ws() -> PResult<()> {
    let s = " 123 ";
    let (_, x) = ws(digit1).parse_peek(s)?;
    assert_eq!(x, "123");

    let s = "123 ";
    let (_, x) = ws(digit1).parse_peek(s)?;
    assert_eq!(x, "123");

    let s = "123\n";
    let (_, x) = ws(digit1).parse_peek(s)?;
    assert_eq!(x, "123");

    Ok(())
}

#[test]
fn test_jump() {
    let x = "xxbcc aa cc";
    let (r, _) = jump_to("aa").parse_peek(x).unwrap();
    assert_eq!(r, " cc");

    let input = " Leave Link  103 at Fri Apr 19 13:58:11 2019, MaxMem=    33554432 cpu:         0.0
 (Enter /home/ybyygu/gaussian/g09/l202.exe)
                          Input orientation:";
    let input_orientation = (space1, "Input orientation:");
    let (r, _) = skip_line_till(input_orientation).parse_peek(input).unwrap();
    assert!(r.is_empty());
}

#[test]
fn test_read_line() {
    let txt = "first line\nsecond line\r\nthird line\n";
    let (rest, line) = read_line.parse_peek(txt).unwrap();
    assert_eq!(line, "first line\n");
    let (rest, line) = read_line.parse_peek(rest).unwrap();
    assert_eq!(line, "second line\r\n");
    let (rest, line) = read_line.parse_peek(rest).unwrap();
    assert_eq!(line, "third line\n");
    assert_eq!(rest, "");

    // when there is no newline
    let txt = "no newline at the end";
    let (rest, line) = read_line.parse_peek(txt).unwrap();
    assert_eq!(line, txt);
    assert_eq!(rest, "");

    let txt = "no";
    let (_, line) = not_space.parse_peek(txt).unwrap();
    assert_eq!(line, "no");

    let txt = "no ";
    let (_, line) = not_space.parse_peek(txt).unwrap();
    assert_eq!(line, "no");

    let txt = "no-a\n";
    let (_, line) = not_space.parse_peek(txt).unwrap();
    assert_eq!(line, "no-a");

    let txt = "no+b\t";
    let (_, line) = not_space.parse_peek(txt).unwrap();
    assert_eq!(line, "no+b");

    let txt = " no-a\n";
    let x = not_space.parse_peek(txt);
    assert!(x.is_err());
}

#[test]
fn test_read_many() {
    let (_, ns) = read_usize_many.parse_peek("11 2 3 4 5\r\n\n").expect("usize parser");
    assert_eq!(5, ns.len());
    let _ = read_usize_many.parse_peek(" 11 2 3 4 5 \n").expect("usize parser");
    let _ = read_usize_many.parse_peek("11 2 3 4 5 \r\n").expect("usize parser");

    let line = " 1.2  3.4 -5.7 0.2 \n";
    let (_, fs) = read_double_many.parse_peek(line).expect("f64 parser");
    assert_eq!(4, fs.len());
}

#[test]
fn test_signed_digit() {
    let (_, x) = signed_digit.parse_peek("-123").expect("signed digit, minus");
    assert_eq!(x, -123);

    let (_, x) = signed_digit.parse_peek("123").expect("signed digit, normal");
    assert_eq!(x, 123);

    let (_, x) = signed_digit.parse_peek("+123").expect("signed digit, plus");
    assert_eq!(x, 123);

    let s = "12x";
    let (r, n) = unsigned_digit.parse_peek(s).unwrap();
    assert_eq!(n, 12);
    assert_eq!(r, "x");

    let (r, n) = read_usize.parse_peek(" 12 \n").unwrap();
    assert_eq!(n, 12);
    assert_eq!(r, "");
}
// 10e5dba2 ends here