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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::{get_rule_suggestion, CstRuleStore, File};

use super::{
    commands::Command,
    get_command_descriptors,
    lexer::{format_kind, Lexer, Token},
    CommandDescriptor, Component, ComponentKind, Directive, Instruction,
};
use rslint_errors::{file::line_starts, Diagnostic};
use rslint_lexer::{SyntaxKind, T};
use rslint_parser::{
    ast::ModuleItem, util::Comment, JsNum, SyntaxNode, SyntaxNodeExt, SyntaxTokenExt, TextRange,
};
use std::ops::Range;

/// A string that denotes that start of a directive (`rslint-`).
pub const DECLARATOR: &str = "rslint-";

pub type Result<T, E = DirectiveError> = std::result::Result<T, E>;

/// The result of a parsed directive.
#[derive(Default)]
pub struct DirectiveResult {
    pub directives: Vec<Directive>,
    pub diagnostics: Vec<DirectiveError>,
}

impl DirectiveResult {
    fn concat(&mut self, other: Self) {
        self.diagnostics.extend(other.diagnostics);
        self.directives.extend(other.directives);
    }

    fn extend(&mut self, res: Result<Directive>) {
        match res {
            Ok(d) => self.directives.push(d),
            Err(d) => self.diagnostics.push(d),
        }
    }
}

#[derive(Debug, Clone)]
pub struct DirectiveError {
    pub diagnostic: Diagnostic,
    pub kind: DirectiveErrorKind,
}

impl DirectiveError {
    pub fn range(&self) -> Range<usize> {
        self.diagnostic.primary.as_ref().unwrap().span.range.clone()
    }

    pub fn new(diagnostic: Diagnostic, kind: DirectiveErrorKind) -> Self {
        Self { diagnostic, kind }
    }
}

#[derive(Debug, Clone)]
pub enum DirectiveErrorKind {
    ExpectedNotFound(Instruction),
    InvalidRule,
    InvalidCommandName,
    ExpectedCommand,
    Other,
}

pub struct DirectiveParser<'store, 'file> {
    /// The root node of a file, `SCRIPT` or `MODULE`.
    root: SyntaxNode,
    line_starts: Box<[usize]>,
    file: &'file File,
    store: Option<&'store CstRuleStore>,
    commands: Box<[CommandDescriptor]>,
    no_rewind: bool,
}

impl<'store, 'file> DirectiveParser<'store, 'file> {
    /// Create a new `DirectivesParser` with a root of a file which will
    /// use all default rules to check the rule names of a directive.
    ///
    /// # Panics
    ///
    /// If the given `root` is not `SCRIPT` or `MODULE`.
    pub fn new(root: SyntaxNode, file: &'file File) -> Self {
        Self::new_with_store(root, file, None)
    }

    /// Create a new `DirectivesParser` with a root of a file and a store of rules.
    ///
    /// # Panics
    ///
    /// If the given `root` is not `SCRIPT` or `MODULE`.
    pub fn new_with_store(
        root: SyntaxNode,
        file: &'file File,
        store: impl Into<Option<&'store CstRuleStore>>,
    ) -> Self {
        assert!(matches!(
            root.kind(),
            SyntaxKind::SCRIPT | SyntaxKind::MODULE
        ));

        Self {
            line_starts: line_starts(&root.to_string()).collect(),
            store: store.into(),
            root,
            file,
            no_rewind: false,
            commands: get_command_descriptors(),
        }
    }

    fn err(&self, msg: &str) -> Diagnostic {
        Diagnostic::error(self.file.id, "directives", msg)
    }

    fn line_of(&self, idx: usize) -> usize {
        self.line_starts
            .binary_search(&idx)
            .unwrap_or_else(|next_line| next_line - 1)
    }

    pub fn get_file_directives(&mut self) -> DirectiveResult {
        let top_level = self.top_level_directives();
        let mut result = DirectiveResult::default();

        for descendant in self.root.descendants().skip(1) {
            let comment = descendant
                .first_token()
                .and_then(|tok| tok.comment())
                .filter(|c| c.content.trim_start().starts_with(DECLARATOR));

            let comment = match comment {
                Some(comment) if comment.token.parent().is::<ModuleItem>() => comment,
                _ => continue,
            };

            let directive = self.parse_directive(comment, Some(descendant), false);
            result.extend(directive);
        }
        result.concat(top_level);
        result
    }

    pub fn top_level_directives(&mut self) -> DirectiveResult {
        let mut result = DirectiveResult::default();

        self.root
            .children_with_tokens()
            .flat_map(|item| item.into_token()?.comment())
            .filter(|comment| comment.content.trim_start().starts_with(DECLARATOR))
            .map(|comment| self.parse_directive(comment, None, true))
            .for_each(|res| result.extend(res));

        result
    }

    /// Parses a directive, based on all commands inside this `DirectivesParser`.
    fn parse_directive(
        &mut self,
        comment: Comment,
        node: Option<SyntaxNode>,
        top_level: bool,
    ) -> Result<Directive> {
        let text = comment
            .content
            .trim_start()
            .strip_prefix(DECLARATOR)
            .unwrap();

        let decl_offset = comment.content.len() - text.len();
        let offset = usize::from(comment.token.text_range().start()) + decl_offset + 1;

        let mut lexer = Lexer::new(text, self.file.id, offset);

        if matches!(
            lexer.peek(),
            Some(Token {
                kind: SyntaxKind::EOF,
                ..
            })
        ) {
            let range = lexer.next().unwrap().range;
            let d = self
                .err("expected command name, but the comment ends here")
                .primary(range, "");
            return Err(DirectiveError::new(d, DirectiveErrorKind::ExpectedCommand));
        }

        let cmd_tok = lexer.next().unwrap();
        let cmd_name = lexer.source_of(&cmd_tok);

        let cmd = self
            .commands
            .iter()
            .find(|cmd| cmd.name.eq_ignore_ascii_case(cmd_name))
            .map(|x| x.instructions.clone());

        let cmd = match cmd {
            Some(cmd) => cmd,
            None => {
                // TODO: Suggest name using `find_best_match_for_name`
                let d = self
                    .err(&format!("unknown directive command: `{}`", cmd_name))
                    .primary(cmd_tok.range, "");

                return Err(DirectiveError::new(
                    d,
                    DirectiveErrorKind::InvalidCommandName,
                ));
            }
        };

        let components = self.parse_command(
            &mut lexer,
            Component {
                kind: ComponentKind::CommandName(cmd_name.into()),
                range: cmd_tok.range,
            },
            &cmd,
        )?;

        let line = self.line_of(comment.token.text_range().start().into());
        Ok(Directive {
            // TODO: Report error for invalid command.
            command: Command::parse(&components, line, node, top_level, self.file),
            line,
            comment,
            components,
        })
    }

    fn parse_command(
        &mut self,
        lexer: &mut Lexer<'_>,
        first_component: Component,
        cmd: &[Instruction],
    ) -> Result<Vec<Component>> {
        self.no_rewind = false;
        let mut components = vec![first_component];

        for insn in &cmd[1..] {
            components.extend(self.parse_instruction(lexer, insn)?);
        }

        Ok(components)
    }

    fn parse_instruction(
        &mut self,
        lexer: &mut Lexer<'_>,
        insn: &Instruction,
    ) -> Result<Vec<Component>> {
        match insn {
            Instruction::CommandName(_) => {
                panic!("command name is only allowed as the first element")
            }
            Instruction::Number => {
                let tok = lexer.expect(SyntaxKind::NUMBER)?;
                let num = lexer.source_of(&tok);
                let num = match rslint_parser::parse_js_num(num.to_string()) {
                    Some(JsNum::Float(val)) => val as u64,
                    Some(JsNum::BigInt(_)) => {
                        let d = self
                            .err("bigints are not supported in directives")
                            .primary(tok.range, "");
                        self.no_rewind = true;
                        return Err(DirectiveError::new(d, DirectiveErrorKind::Other));
                    }
                    _ => {
                        let d = self.err("invalid number").primary(tok.range, "");
                        return Err(DirectiveError::new(d, DirectiveErrorKind::Other));
                    }
                };
                Ok(vec![Component {
                    kind: ComponentKind::Number(num),
                    range: tok.range,
                }])
            }
            Instruction::RuleName => {
                fn is_rule_name(kind: SyntaxKind) -> bool {
                    kind == T![-] || kind == T![ident] || kind.is_keyword()
                }

                let first = lexer
                    .next()
                    .filter(|tok| tok.kind != SyntaxKind::EOF)
                    .ok_or_else(|| {
                        let err = self
                            .err("expected rule name, but comment ends here")
                            .primary(lexer.abs_cur()..lexer.abs_cur() + 1, "");

                        DirectiveError::new(
                            err,
                            DirectiveErrorKind::ExpectedNotFound(Instruction::RuleName),
                        )
                    })?;
                if !is_rule_name(first.kind) {
                    let d = self
                        .err(&format!(
                            "expected `identifier`, `-` or `keyword`, but found `{}`",
                            format_kind(first.kind),
                        ))
                        .primary(first.range, "");
                    self.no_rewind = true;
                    return Err(DirectiveError::new(
                        d,
                        DirectiveErrorKind::ExpectedNotFound(Instruction::RuleName),
                    ));
                }
                let start = first.range.start();

                while lexer
                    .peek_with_spaces()
                    .map_or(false, |tok| is_rule_name(tok.kind))
                {
                    lexer.next();
                }

                let end = lexer.abs_cur() as u32;
                let name_range = TextRange::new(start, end.into());
                let name = lexer.source_range(name_range);

                let rule = self
                    .store
                    .map(|store| store.get(name))
                    .unwrap_or_else(|| crate::get_rule_by_name(name));
                if let Some(rule) = rule {
                    Ok(vec![Component {
                        kind: ComponentKind::Rule(rule),
                        range: name_range,
                    }])
                } else {
                    let mut d = self
                        .err(&format!("invalid rule: `{}`", name))
                        .primary(name_range, "");

                    if let Some(suggestion) = get_rule_suggestion(name) {
                        d = d.footer_help(format!("did you mean `{}`?", suggestion))
                    }
                    self.no_rewind = true;

                    Err(DirectiveError::new(d, DirectiveErrorKind::InvalidRule))
                }
            }
            Instruction::Literal(lit) => {
                let tok = lexer.expect(SyntaxKind::IDENT)?;
                let src = lexer.source_of(&tok);

                if !src.eq_ignore_ascii_case(lit) {
                    let d = self
                        .err(&format!(
                            "expected literal `{}`, but found literal `{}`",
                            lit, src
                        ))
                        .primary(tok.range, "");
                    self.no_rewind = true;
                    Err(DirectiveError::new(
                        d,
                        DirectiveErrorKind::ExpectedNotFound(Instruction::Literal(lit)),
                    ))
                } else {
                    Ok(vec![Component {
                        kind: ComponentKind::Literal(lit),
                        range: tok.range,
                    }])
                }
            }
            Instruction::Optional(insns) => {
                let first = insns
                    .first()
                    .expect("every `Optional` instruction needs at least one element");
                if let Ok(first) = self.parse_instruction(lexer, first) {
                    let mut components = vec![];
                    components.extend(first);

                    for insn in insns.iter().skip(1) {
                        components.extend(self.parse_instruction(lexer, insn)?);
                    }

                    Ok(components)
                } else {
                    Ok(vec![])
                }
            }
            Instruction::Repetition(insn, separator) => {
                let mut first = true;
                let mut components = vec![];

                lexer.mark(true);
                let start = lexer.abs_cur() as u32;
                while lexer.peek().map_or(false, |tok| tok.kind == *separator) || first {
                    if !first {
                        lexer.expect(*separator)?;
                    }
                    let res = match self.parse_instruction(lexer, insn) {
                        Ok(res) => res,
                        // The first element isn't valid, so we continute with next instruction.
                        Err(_) if first && !self.no_rewind => {
                            lexer.mark(false);
                            lexer.rewind();
                            return Ok(vec![]);
                        }
                        err @ Err(_) => return err,
                    };
                    components.extend(res);

                    if first {
                        first = false;
                    }
                }
                lexer.mark(false);
                let end = lexer.abs_cur() as u32;

                Ok(vec![Component {
                    kind: ComponentKind::Repetition(components),
                    range: TextRange::new(start.into(), end.into()),
                }])
            }
            Instruction::Either(left, right) => self
                .parse_instruction(lexer, left)
                .or_else(|_| self.parse_instruction(lexer, right)),
        }
    }
}