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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
//! Reading `.hltas` files.

use std::{
    fmt::{self, Display, Formatter},
    num::NonZeroU32,
    str::FromStr,
};

use nom::{
    self,
    bytes::complete::tag,
    character::complete::{digit0, line_ending, multispace0, one_of, space1},
    combinator::{all_consuming, map_res, opt, recognize, verify},
    error::{FromExternalError, ParseError},
    multi::{many1, separated_list0},
    sequence::{delimited, pair, preceded},
    Offset,
};

use crate::types::{Line, HLTAS};

mod line;
pub use line::{frame_bulk, line};

pub(crate) mod properties;
use properties::properties;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum ErrorKind {
    ExpectedChar(char),
    Other(nom::error::ErrorKind),
}

/// Enumeration of possible semantic errors.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Context {
    /// Failed to read the version.
    ErrorReadingVersion,
    /// The version is too high.
    VersionTooHigh,
    /// Both autojump and ducktap are enabled at once.
    BothAutoJumpAndDuckTap,
    /// LGAGST is enabled without autojump or ducktap.
    NoLeaveGroundAction,
    /// Times is specified on the LGAGST action.
    TimesOnLeaveGroundAction,
    /// Save name is not specified.
    NoSaveName,
    /// Seed is not specified.
    NoSeed,
    /// Yaw is required but not specified.
    NoYaw,
    /// Buttons are not specified.
    NoButtons,
    /// The LGAGST min speed valueis not specified.
    NoLGAGSTMinSpeed,
    /// The reset seed is not specified.
    NoResetSeed,
    /// Failed to parse a frames entry.
    ErrorParsingLine,
    /// Invalid strafing algorithm.
    InvalidStrafingAlgorithm,
    /// Vectorial strafing constraints are not specified.
    NoConstraints,
    /// The +- in the vectorial strafing constraints is missing.
    NoPlusMinusBeforeTolerance,
    /// The parameters in the yaw range vectorial strafing constraints are not specified.
    NoFromToParameters,
    /// The yaw range vectorial strafing constraint is missing the "to" word.
    NoTo,
    /// Yawspeed is required for constant yawspeed but not specified.
    NoYawspeed,
    /// Only side strafe works with constant yawspeed now.
    UnsupportedConstantYawspeedDir,
    /// Negative yawspeed value.
    NegativeYawspeed,
}

/// `.hltas` parsing error.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Error<'a> {
    /// Remaining input at the point of failure.
    pub input: &'a str,
    pub(crate) whole_input: &'a str,
    kind: ErrorKind,
    /// Semantic meaning of the parsing error.
    pub context: Option<Context>,
}

type IResult<'a, T> = Result<(&'a str, T), nom::Err<Error<'a>>>;

impl Error<'_> {
    fn add_context(&mut self, context: Context) {
        if self.context.is_some() {
            return;
        }

        self.context = Some(context);
    }
}

impl Display for Context {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        use Context::*;
        match self {
            ErrorReadingVersion => write!(f, "failed to read version"),
            VersionTooHigh => write!(f, "this version is not supported"),
            BothAutoJumpAndDuckTap => write!(
                f,
                "both autojump and ducktap are specified at the same time"
            ),
            NoLeaveGroundAction => write!(
                f,
                "no LGAGST action specified (either autojump or ducktap is required)"
            ),
            TimesOnLeaveGroundAction => write!(
                f,
                "times on autojump or ducktap with LGAGST enabled (put times on LGAGST instead)"
            ),
            NoSaveName => write!(f, "missing save name"),
            NoSeed => write!(f, "missing seed value"),
            NoButtons => write!(f, "missing button values"),
            NoLGAGSTMinSpeed => write!(f, "missing lgagstminspeed value"),
            NoResetSeed => write!(f, "missing reset seed"),
            NoYaw => write!(f, "missing yaw value"),
            ErrorParsingLine => write!(f, "failed to parse the line"),
            InvalidStrafingAlgorithm => write!(
                f,
                "invalid strafing algorithm (only \"yaw\" and \"vectorial\" allowed)"
            ),
            NoConstraints => write!(f, "missing constraints"),
            NoPlusMinusBeforeTolerance => write!(f, "missing +- before tolerance"),
            NoFromToParameters => write!(f, "missing from/to parameters"),
            NoTo => write!(f, "missing \"to\" in the from/to constraint"),
            NoYawspeed => write!(f, "missing yawspeed value"),
            UnsupportedConstantYawspeedDir => {
                write!(f, "cannot pair constant yawspeed with current strafe dir")
            }
            NegativeYawspeed => {
                write!(f, "yawspeed value is negative")
            }
        }
    }
}

impl Display for Error<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let mut line = 0;
        let mut column = 0;
        let mut offset = self.whole_input.offset(self.input);
        let mut just_error_line = None;

        for (j, l) in self.whole_input.lines().enumerate() {
            if offset <= l.len() {
                line = j;
                column = offset;
                just_error_line = Some(l);
                break;
            } else {
                offset = offset - l.len() - 1;
            }
        }

        if let Some(context) = self.context {
            context.fmt(f)?;
        } else {
            match self.kind {
                ErrorKind::ExpectedChar(c) => {
                    if let Some(next_char) = self.input.chars().next() {
                        write!(f, "expected '{}', got '{}'", c, next_char)?;
                    } else {
                        write!(f, "expected '{}', got EOF", c)?;
                    }
                }
                ErrorKind::Other(nom_kind) => {
                    write!(f, "error applying {}", nom_kind.description())?
                }
            }
        }

        // Can happen if whole_input is some unrelated &str.
        if just_error_line.is_none() {
            return Ok(());
        }
        let just_error_line = just_error_line.unwrap();

        let line_number = format!("{} | ", line);

        write!(f, "\n{}{}\n", line_number, just_error_line)?;
        write!(f, "{:1$}^", ' ', line_number.len() + column)?;

        if let ErrorKind::ExpectedChar(c) = self.kind {
            write!(f, " expected '{}'", c)?;
        }

        Ok(())
    }
}

impl std::error::Error for Error<'_> {}

impl<'a> ParseError<&'a str> for Error<'a> {
    fn from_error_kind(input: &'a str, kind: nom::error::ErrorKind) -> Self {
        Self {
            input,
            whole_input: input,
            kind: ErrorKind::Other(kind),
            context: None,
        }
    }

    fn append(_input: &'a str, _kind: nom::error::ErrorKind, other: Self) -> Self {
        other
    }

    fn from_char(input: &'a str, c: char) -> Self {
        Self {
            input,
            whole_input: input,
            kind: ErrorKind::ExpectedChar(c),
            context: None,
        }
    }
}

impl<'a, E> FromExternalError<&'a str, E> for Error<'a> {
    fn from_external_error(input: &'a str, kind: nom::error::ErrorKind, _e: E) -> Self {
        Self::from_error_kind(input, kind)
    }
}

impl Error<'_> {
    /// Returns the line number on which the error has occurred.
    pub fn line(&self) -> usize {
        let mut line = 0;
        let mut offset = self.whole_input.offset(self.input);

        for (j, l) in self.whole_input.lines().enumerate() {
            if offset <= l.len() {
                line = j;
                break;
            } else {
                offset = offset - l.len() - 1;
            }
        }

        line
    }
}

/// Adds context to the potential parser error.
///
/// If the error already has context stored, does nothing.
fn context<'a, T>(
    context: Context,
    mut f: impl FnMut(&'a str) -> IResult<'a, T>,
) -> impl FnMut(&'a str) -> IResult<T> {
    move |i: &str| {
        f(i).map_err(move |error| match error {
            nom::Err::Incomplete(needed) => nom::Err::Incomplete(needed),
            nom::Err::Error(mut e) => {
                e.add_context(context);
                nom::Err::Error(e)
            }
            nom::Err::Failure(mut e) => {
                e.add_context(context);
                nom::Err::Failure(e)
            }
        })
    }
}

fn non_zero_u32(i: &str) -> IResult<NonZeroU32> {
    map_res(
        recognize(pair(one_of("123456789"), digit0)),
        NonZeroU32::from_str,
    )(i)
}

fn version(i: &str) -> IResult<()> {
    // This is a little involved to report the correct HLTAS error.
    // When we can't parse the version as a number at all, we should report ErrorReadingVersion.
    // When we can parse it as a number and it's above 1, we should report VersionTooHigh.
    let version_number = context(
        Context::VersionTooHigh,
        verify(
            context(Context::ErrorReadingVersion, one_of("123456789")),
            |&c| c == '1',
        ),
    );
    let (i, _) = preceded(tag("version"), preceded(space1, version_number))(i)?;
    Ok((i, ()))
}

/// Parses a line ending character, followed by any additional whitespace.
fn whitespace(i: &str) -> IResult<()> {
    let (i, _) = preceded(line_ending, multispace0)(i)?;
    Ok((i, ()))
}

/// Parses [`Line`]s, ensuring nother is left in the input.
///
/// # Examples
///
/// ```
/// # extern crate hltas;
///
/// let lines = "\
/// ------b---|------|------|0.001|-|-|5
/// ------b---|------|------|0.001|-|-|10
/// ";
///
/// assert!(hltas::read::all_consuming_lines(lines).is_ok());
///
/// let lines = "\
/// ------b---|------|------|0.001|-|-|5
/// ------b---|------|------|0.001|-|-|10
/// something extra in the end";
///
/// assert!(hltas::read::all_consuming_lines(lines).is_err());
/// ```
pub fn all_consuming_lines(i: &str) -> IResult<Vec<Line>> {
    let many_lines = separated_list0(whitespace, line);
    all_consuming(delimited(opt(multispace0), many_lines, opt(multispace0)))(i)
}

/// Parses an entire HLTAS script, ensuring nothing is left in the input.
///
/// This is a lower-level function. You might be looking for [`HLTAS::from_str`] instead.
///
/// # Examples
///
/// ```
/// # extern crate hltas;
///
/// let contents = "\
/// version 1
/// demo test
/// frames
/// ------b---|------|------|0.001|-|-|5";
///
/// assert!(hltas::read::hltas(contents).is_ok());
///
/// let contents = "\
/// version 1
/// demo test
/// frames
/// ------b---|------|------|0.001|-|-|5
/// something extra in the end";
///
/// assert!(hltas::read::hltas(contents).is_err());
/// ```
pub fn hltas(i: &str) -> IResult<HLTAS> {
    let (i, _) = context(Context::ErrorReadingVersion, version)(i)?;
    let (i, properties) = properties(i)?;
    let (i, _) = preceded(many1(line_ending), tag("frames"))(i)?;
    let (i, lines) = context(
        Context::ErrorParsingLine,
        preceded(whitespace, all_consuming_lines),
    )(i)?;

    Ok((i, HLTAS { properties, lines }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn version_0() {
        let input = "version 0";
        let err = version(input).unwrap_err();
        if let nom::Err::Error(err) = err {
            assert_eq!(err.context, Some(Context::ErrorReadingVersion));
        } else {
            unreachable!()
        }
    }

    #[test]
    fn version_too_high() {
        let input = "version 9";
        let err = version(input).unwrap_err();
        if let nom::Err::Error(err) = err {
            assert_eq!(err.context, Some(Context::VersionTooHigh));
        } else {
            unreachable!()
        }
    }

    #[test]
    fn no_newline_after_frames() {
        let input = "version 1\nframesbuttons";
        assert!(hltas(input).is_err());
    }

    #[test]
    fn no_newline_after_frames_only_space() {
        let input = "version 1\nframes buttons";
        assert!(hltas(input).is_err());
    }
}