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
//! Utilities.

use crate::parser::*;
use nom::{IResult, Offset, Parser, Slice};
use nom_locate::position;

// pub type JsParseError<'a> = nom::error::VerboseError<Span<'a>>;
pub type JsParseError<'a> = nom::error::Error<Span<'a>>;
pub type Span<'a> = nom_locate::LocatedSpan<&'a str>;
pub type ParseResult<'a, T> = IResult<Span<'a>, T, JsParseError<'a>>;

fn is_whitespace(c: &char) -> bool {
    matches!(
        c,
        '\t'
        // vertical tab
        | '\x0b'
        // form feed
        | '\x0c'
        | ' '
        // no break space
        | '\u{00a0}'
        // byte order mark
        | '\u{feff}'
        // unicode space separators
        | '\u{2000}'..='\u{200a}' | '\u{3000}'
    )
}

/// Parses one character if it is whitespace (not including newline and comments).
pub fn whitespace(s: Span) -> ParseResult<()> {
    value((), verify(anychar, is_whitespace))(s)
}

/// # Grammar
/// ```ebnf
/// lineTerminator = "\n" | "\r" | "\u2028" | "\u2029"
/// ```
pub fn line_terminator(s: Span) -> ParseResult<()> {
    let (s, _) = one_of("\n\r\u{2028}\u{2029}")(s)?;
    Ok((s, ()))
}

pub fn is_line_terminator(c: char) -> bool {
    matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}

/// # Grammar
/// ```ebnf
/// lineTerminatorSequence = "\n" | "\r" ~"\n" | "\u2028" | "\u2029" | "\r\n"
/// ```
pub fn line_terminator_sequence(s: Span) -> ParseResult<()> {
    fn parse_carriage_return(s: Span) -> ParseResult<()> {
        let (s, _) = tag("\r\n")(s)?;
        Ok((s, ()))
    }
    alt((parse_carriage_return, line_terminator))(s)?;
    Ok((s, ()))
}

fn single_line_comment(s: Span) -> ParseResult<Span> {
    let (s, _) = tag("//")(s)?;
    let (s, comment) = take_while(|c| !is_line_terminator(c))(s)?;
    let (s, _) = alt((line_terminator, value((), eof)))(s)?;
    Ok((s, comment))
}

fn multi_line_comment(s: Span) -> ParseResult<Span> {
    delimited(tag("/*"), take_until("*/"), tag("*/"))(s)
}

fn multi_line_comment_no_nl(s: Span) -> ParseResult<Span> {
    verify(
        delimited(tag("/*"), take_until("*/"), tag("*/")),
        |s: &Span| !s.contains(is_line_terminator),
    )(s)
}

pub fn comment(s: Span) -> ParseResult<()> {
    value((), alt((single_line_comment, multi_line_comment)))(s)
}

pub fn sp(s: Span) -> ParseResult<()> {
    alt((whitespace, line_terminator, comment))(s)
}

pub fn sp_no_nl(s: Span) -> ParseResult<()> {
    alt((whitespace, value((), multi_line_comment_no_nl)))(s)
}

pub fn sp0(s: Span) -> ParseResult<()> {
    if eof::<Span, ()>(s).is_ok() {
        return Ok((s, ()));
    }
    value((), many0(sp))(s)
}

pub fn sp1(s: Span) -> ParseResult<()> {
    if eof::<Span, ()>(s).is_ok() {
        return Ok((s, ()));
    }
    value((), many1(sp))(s)
}

pub fn sp_no_nl0(s: Span) -> ParseResult<()> {
    if eof::<Span, ()>(s).is_ok() {
        return Ok((s, ()));
    }
    value((), many0(sp_no_nl))(s)
}

pub fn sp_no_nl1(s: Span) -> ParseResult<()> {
    if eof::<Span, ()>(s).is_ok() {
        return Ok((s, ()));
    }
    value((), many1(sp_no_nl))(s)
}

/// Alias for `terminated(f, sp0)`.
pub fn ws0<'a, O1, F>(mut f: F) -> impl FnMut(Span<'a>) -> ParseResult<O1>
where
    F: Parser<Span<'a>, O1, JsParseError<'a>>,
{
    move |s: Span<'a>| {
        let (s, o1) = f.parse(s)?;
        sp0.parse(s).map(|(i, _)| (i, o1))
    }
}

/// Alias for `terminated(f, sp1)`.
pub fn ws1<'a, O1, F>(mut f: F) -> impl FnMut(Span<'a>) -> ParseResult<O1>
where
    F: Parser<Span<'a>, O1, JsParseError<'a>>,
{
    move |s: Span<'a>| {
        let (s, o1) = f.parse(s)?;
        sp1.parse(s).map(|(i, _)| (i, o1))
    }
}

/// Alias for `terminated(f, sp_no_nl0)`.
pub fn ws_no_nl0<'a, O1, F>(mut f: F) -> impl FnMut(Span<'a>) -> ParseResult<O1>
where
    F: Parser<Span<'a>, O1, JsParseError<'a>>,
{
    move |s: Span<'a>| {
        let (s, o1) = f.parse(s)?;
        sp_no_nl0.parse(s).map(|(i, _)| (i, o1))
    }
}

/// Alias for `terminated(f, sp_no_nl1)`.
pub fn ws_no_nl1<'a, O1, F>(mut f: F) -> impl FnMut(Span<'a>) -> ParseResult<O1>
where
    F: Parser<Span<'a>, O1, JsParseError<'a>>,
{
    move |s: Span<'a>| {
        let (s, o1) = f.parse(s)?;
        sp_no_nl1.parse(s).map(|(i, _)| (i, o1))
    }
}

/// Applies a parser and records start and end position. Ignores whitespace by trimming the end of the matched str.
pub fn spanned<'a, O1, F>(mut f: F) -> impl FnMut(Span<'a>) -> ParseResult<(O1, Span, Span)>
where
    F: Parser<Span<'a>, O1, JsParseError<'a>>,
{
    move |s: Span<'a>| {
        let (matched_s, o1) = f.parse(s)?;
        let index = s.offset(&matched_s);
        let slice = s.slice(..index).trim_end();
        let (_, end) = preceded(take(slice.chars().count()), position)(s)?;

        Ok((
            matched_s,
            (
                o1,
                /* start */ position(s)?.1,
                /* end */ position(end)?.1,
            ),
        ))
    }
}

/// A semicolon is "automatically inserted" if a newline or the end of the input stream is reached, or the offending token is `"}"`.
/// See https://es5.github.io/#x7.9 for more information.
pub fn semi(s: Span) -> ParseResult<()> {
    value((), char(';'))(s)
}

/// Prints the stack trace of a `VerboseError` as a `String` to stderr. DOes nothing if `err` is not an instance of `VerboseError`.
pub fn verbose_trace_dbg(input: &str, err: &dyn std::any::Any) {
    if let Some(err) = err.downcast_ref::<nom::error::VerboseError<Span>>() {
        let err = nom::error::VerboseError {
            errors: err
                .errors
                .iter()
                .map(|e| (*e.0.fragment(), e.1.clone()))
                .collect(),
        };
        eprintln!("{}", nom::error::convert_error(input, err));
    }
}

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

    #[test]
    fn smoke_test_comment() {
        all_consuming(comment)("// abc".into()).unwrap();
        all_consuming(comment)("/* abc */".into()).unwrap();
        all_consuming(comment)("/* abc\n123 */".into()).unwrap();
        all_consuming(comment)("/* abc\n123 */ foo".into()).unwrap_err();
    }

    #[test]
    fn test_comment() {
        assert_eq!(*comment("// abc\ndef".into()).unwrap().0.fragment(), "def");
        assert_eq!(*comment("// abc\rdef".into()).unwrap().0.fragment(), "def");
        assert_eq!(*comment("// abc-\ndef".into()).unwrap().0.fragment(), "def");
        assert_eq!(
            *comment("// abc\u{2028}def".into()).unwrap().0.fragment(),
            "def"
        );
        assert_eq!(
            *comment("// abc\u{2029}def".into()).unwrap().0.fragment(),
            "def"
        );
        assert_eq!(
            *comment("// abc\r\ndef".into()).unwrap().0.fragment(),
            "\ndef"
        );
        assert_eq!(
            *comment("// abc-\r\ndef".into()).unwrap().0.fragment(),
            "\ndef"
        );
        assert_eq!(
            *comment("// abc👍\nabc".into()).unwrap().0.fragment(),
            "abc"
        );
    }
}