necessist-backends 1.0.1

necessist-backends
Documentation
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use crate::{
    AbstractTypes, GenericVisitor, MaybeNamed, Named, OutputAccessors, OutputStrippedOfAnsiScapes,
    ParseLow, Spanned, WalkDirResult,
};
use anyhow::{anyhow, Result};
use if_chain::if_chain;
use log::debug;
use necessist_core::{
    framework::{Postprocess, SpanTestMaps, TestSet},
    source_warn, util, LightContext, LineColumn, SourceFile, Span, WarnFlags, Warning,
};
use once_cell::sync::Lazy;
use regex::Regex;
use std::{
    cell::RefCell,
    collections::BTreeMap,
    convert::Infallible,
    ffi::OsStr,
    path::{Path, PathBuf},
    process::Command,
    rc::Rc,
};
use subprocess::{Exec, NullFile};
use swc_core::{
    common::{BytePos, Loc, SourceMap, Span as SwcSpan, Spanned as SwcSpanned},
    ecma::{
        ast::{
            ArrowExpr, AwaitExpr, BlockStmtOrExpr, CallExpr, Callee, EsVersion, Expr, ExprStmt,
            FnDecl, Invalid, Lit, MemberExpr, MemberProp, Module, Stmt, Str,
        },
        atoms::JsWord,
        parser::{lexer::Lexer, Parser, StringInput, Syntax, TsSyntax},
    },
};

mod storage;
use storage::Storage;

mod visitor;
use visitor::{collect_local_functions, visit};

static INVALID: Expr = Expr::Invalid(Invalid {
    span: SwcSpan {
        lo: BytePos(0),
        hi: BytePos(0),
    },
});

#[derive(Debug, Eq, PartialEq)]
enum ItMessageState {
    NotFound,
    Found,
    WarningEmitted,
}

impl Default for ItMessageState {
    fn default() -> Self {
        Self::NotFound
    }
}

static LINE_WITH_TIME_RE: Lazy<Regex> = Lazy::new(|| {
    // smoelius: The initial `.` is the check mark.
    #[allow(clippy::unwrap_used)]
    Regex::new(r"^\s*. (.*) \([0-9]+ms\)$").unwrap()
});

static LINE_WITHOUT_TIME_RE: Lazy<Regex> = Lazy::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r"^\s*. (.*)$").unwrap()
});

pub struct Mocha {
    subdir: PathBuf,
    source_map: Rc<SourceMap>,
    source_file_it_message_state_map: RefCell<BTreeMap<PathBuf, BTreeMap<String, ItMessageState>>>,
}

impl Mocha {
    pub fn new(subdir: impl AsRef<Path>) -> Self {
        Self {
            subdir: subdir.as_ref().to_path_buf(),
            source_map: Rc::default(),
            source_file_it_message_state_map: RefCell::new(BTreeMap::new()),
        }
    }

    pub fn dry_run(
        &self,
        _context: &LightContext,
        source_file: &Path,
        mut command: Command,
    ) -> Result<()> {
        debug!("{:?}", command);

        let output = command.output_stripped_of_ansi_escapes()?;
        if !output.status().success() {
            return Err(output.into());
        }

        let mut source_file_it_message_state_map =
            self.source_file_it_message_state_map.borrow_mut();
        let it_message_state_map = source_file_it_message_state_map
            .entry(source_file.to_path_buf())
            .or_default();

        let stdout = std::str::from_utf8(output.stdout())?;
        for line in stdout.lines() {
            if let Some(captures) = LINE_WITH_TIME_RE
                .captures(line)
                .or_else(|| LINE_WITHOUT_TIME_RE.captures(line))
            {
                assert_eq!(2, captures.len());
                it_message_state_map.insert(captures[1].to_string(), ItMessageState::Found);
            }
        }

        Ok(())
    }

    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    pub fn statement_prefix_and_suffix(&self, span: &Span) -> Result<(String, String)> {
        Ok((
            format!(
                r#"if (process.env.NECESSIST_REMOVAL != "{}") {{ "#,
                span.id()
            ),
            " }".to_owned(),
        ))
    }

    pub fn exec(
        &self,
        context: &LightContext,
        test_name: &str,
        span: &Span,
        command: &Command,
    ) -> Result<Option<(Exec, Option<Box<Postprocess>>)>> {
        let mut source_file_it_message_state_map =
            self.source_file_it_message_state_map.borrow_mut();
        #[allow(clippy::expect_used)]
        let it_message_state_map = source_file_it_message_state_map
            .get_mut(span.source_file.as_ref())
            .expect("Source file is not in map");

        // smoelius: For Mocha-based frameworks, `test_name` is the `it` message.
        let state = it_message_state_map
            .entry(test_name.to_owned())
            .or_default();
        if *state != ItMessageState::Found {
            if *state == ItMessageState::NotFound {
                source_warn(
                    context,
                    Warning::ItMessageNotFound,
                    span,
                    &format!("`it` message {test_name:?} was not found during dry run"),
                    WarnFlags::empty(),
                )?;
                *state = ItMessageState::WarningEmitted;
            }
            // smoelius: Returning `None` here causes Necessist to associate `Outcome::Nonbuildable`
            // with this span. This is not ideal, but there is no ideal choice for this situation
            // currently.
            return Ok(None);
        }

        let mut exec = util::exec_from_command(command);
        exec = exec.stdout(NullFile);
        exec = exec.stderr(NullFile);

        debug!("{:?}", exec);

        Ok(Some((exec, None)))
    }
}

#[derive(Clone, Copy)]
pub struct Test<'ast> {
    it_message: &'ast JsWord,
    stmts: &'ast Vec<Stmt>,
}

pub struct SourceMapped<'ast, T> {
    source_map: &'ast Rc<SourceMap>,
    node: &'ast T,
}

impl<T> Clone for SourceMapped<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for SourceMapped<'_, T> {}

impl<T: PartialEq> PartialEq for SourceMapped<'_, T> {
    // smoelius: Remove this `#[allow(..)]` once the following pull request appears in nightly:
    // https://github.com/rust-lang/rust-clippy/pull/12137
    #[allow(clippy::unconditional_recursion)]
    fn eq(&self, other: &Self) -> bool {
        self.node.eq(other.node)
    }
}

impl<T: Eq> Eq for SourceMapped<'_, T> {}

impl<T: SwcSpanned> Spanned for SourceMapped<'_, T> {
    fn span(&self, source_file: &SourceFile) -> Span {
        SwcSpanned::span(self.node).to_internal_span(self.source_map, source_file)
    }
}

pub struct Types;

impl AbstractTypes for Types {
    type Storage<'ast> = Storage<'ast>;
    type File = (Rc<SourceMap>, Module);
    type Test<'ast> = Test<'ast>;
    type LocalFunction<'ast> = &'ast FnDecl;
    type Statement<'ast> = SourceMapped<'ast, Stmt>;
    type Expression<'ast> = SourceMapped<'ast, Expr>;
    type Await<'ast> = &'ast AwaitExpr;
    type Field<'ast> = SourceMapped<'ast, MemberExpr>;
    type Call<'ast> = SourceMapped<'ast, CallExpr>;
    type MacroCall<'ast> = Infallible;
}

impl Named for Test<'_> {
    fn name(&self) -> String {
        self.it_message.to_string()
    }
}

impl MaybeNamed for <Types as AbstractTypes>::Expression<'_> {
    fn name(&self) -> Option<String> {
        if let Expr::Ident(ident) = self.node {
            Some(ident.as_ref().to_owned())
        } else {
            None
        }
    }
}

impl MaybeNamed for <Types as AbstractTypes>::Field<'_> {
    fn name(&self) -> Option<String> {
        if let MemberProp::Ident(ident) = &self.node.prop {
            Some(ident.as_ref().to_owned())
        } else {
            None
        }
    }
}

impl MaybeNamed for <Types as AbstractTypes>::Call<'_> {
    fn name(&self) -> Option<String> {
        if_chain! {
            if let Callee::Expr(callee) = &self.node.callee;
            if let Expr::Ident(ident) = &**callee;
            then {
                Some(ident.as_ref().to_owned())
            } else {
                None
            }
        }
    }
}

impl ParseLow for Mocha {
    type Types = Types;

    const IGNORED_FUNCTIONS: Option<&'static [&'static str]> =
        Some(&["assert", "assert.*", "console.*", "expect"]);

    const IGNORED_MACROS: Option<&'static [&'static str]> = None;

    const IGNORED_METHODS: Option<&'static [&'static str]> = Some(&["toNumber", "toString"]);

    fn walk_dir(&self, root: &Path) -> Box<dyn Iterator<Item = WalkDirResult>> {
        Box::new(
            walkdir::WalkDir::new(root.join(&self.subdir))
                .into_iter()
                .filter_entry(|entry| {
                    let path = entry.path();
                    !path.is_file()
                        || path.extension() == Some(OsStr::new("js"))
                        || path.extension() == Some(OsStr::new("ts"))
                }),
        )
    }

    fn parse_source_file(
        &self,
        source_file: &Path,
    ) -> Result<<Self::Types as AbstractTypes>::File> {
        let source_file = self.source_map.load_file(source_file)?;
        let lexer = Lexer::new(
            Syntax::Typescript(TsSyntax::default()),
            EsVersion::default(),
            StringInput::from(&*source_file),
            None,
        );
        let mut parser = Parser::new_from(lexer);
        parser
            .parse_typescript_module()
            .map(|module| (self.source_map.clone(), module))
            .map_err(|error| anyhow!(format!("{error:?}")))
    }

    fn storage_from_file<'ast>(
        &self,
        file: &'ast <Self::Types as AbstractTypes>::File,
    ) -> <Self::Types as AbstractTypes>::Storage<'ast> {
        Storage::new(file)
    }

    fn local_functions<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        file: &'ast <Self::Types as AbstractTypes>::File,
    ) -> Result<BTreeMap<String, Vec<<Self::Types as AbstractTypes>::LocalFunction<'ast>>>> {
        Ok(collect_local_functions(&file.1))
    }

    fn visit_file<'ast>(
        generic_visitor: GenericVisitor<'_, '_, '_, 'ast, Self>,
        storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        file: &'ast <Self::Types as AbstractTypes>::File,
    ) -> Result<(TestSet, SpanTestMaps)> {
        visit(generic_visitor, storage, &file.1)
    }

    fn test_statements<'ast>(
        &self,
        storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        test: <Self::Types as AbstractTypes>::Test<'ast>,
    ) -> Vec<<Self::Types as AbstractTypes>::Statement<'ast>> {
        test.stmts
            .iter()
            .map(|stmt| SourceMapped {
                source_map: storage.borrow().source_map,
                node: stmt,
            })
            .collect()
    }

    fn statement_is_removable(
        &self,
        _statement: <Self::Types as AbstractTypes>::Statement<'_>,
    ) -> bool {
        true
    }

    fn statement_is_expression<'ast>(
        &self,
        storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        statement: <Self::Types as AbstractTypes>::Statement<'ast>,
    ) -> Option<<Self::Types as AbstractTypes>::Expression<'ast>> {
        if let Stmt::Expr(ExprStmt { expr, .. }) = statement.node {
            Some(SourceMapped {
                source_map: storage.borrow().source_map,
                node: expr,
            })
        } else {
            None
        }
    }

    fn statement_is_control<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        statement: <Self::Types as AbstractTypes>::Statement<'ast>,
    ) -> bool {
        matches!(
            statement.node,
            Stmt::Break(_) | Stmt::Continue(_) | Stmt::Return(_)
        )
    }

    fn statement_is_declaration<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        statement: <Self::Types as AbstractTypes>::Statement<'ast>,
    ) -> bool {
        matches!(statement.node, Stmt::Decl(_))
    }

    fn expression_is_await<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        expression: <Self::Types as AbstractTypes>::Expression<'ast>,
    ) -> Option<<Self::Types as AbstractTypes>::Await<'ast>> {
        if let Expr::Await(await_) = expression.node {
            Some(await_)
        } else {
            None
        }
    }

    fn expression_is_field<'ast>(
        &self,
        storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        expression: <Self::Types as AbstractTypes>::Expression<'ast>,
    ) -> Option<<Self::Types as AbstractTypes>::Field<'ast>> {
        if let Expr::Member(member) = expression.node {
            Some(SourceMapped {
                source_map: storage.borrow().source_map,
                node: member,
            })
        } else {
            None
        }
    }

    fn expression_is_call<'ast>(
        &self,
        storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        expression: <Self::Types as AbstractTypes>::Expression<'ast>,
    ) -> Option<<Self::Types as AbstractTypes>::Call<'ast>> {
        if let Expr::Call(call) = expression.node {
            Some(SourceMapped {
                source_map: storage.borrow().source_map,
                node: call,
            })
        } else {
            None
        }
    }

    fn expression_is_macro_call<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        _expression: <Self::Types as AbstractTypes>::Expression<'ast>,
    ) -> Option<<Self::Types as AbstractTypes>::MacroCall<'ast>> {
        None
    }

    fn await_arg<'ast>(
        &self,
        storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        await_: <Self::Types as AbstractTypes>::Await<'ast>,
    ) -> <Self::Types as AbstractTypes>::Expression<'ast> {
        SourceMapped {
            source_map: storage.borrow().source_map,
            node: &*await_.arg,
        }
    }

    fn field_base<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        field: <Self::Types as AbstractTypes>::Field<'ast>,
    ) -> <Self::Types as AbstractTypes>::Expression<'ast> {
        SourceMapped {
            source_map: field.source_map,
            node: &*field.node.obj,
        }
    }

    fn call_callee<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        call: <Self::Types as AbstractTypes>::Call<'ast>,
    ) -> <Self::Types as AbstractTypes>::Expression<'ast> {
        if let Callee::Expr(expr) = &call.node.callee {
            SourceMapped {
                source_map: call.source_map,
                node: expr,
            }
        } else {
            SourceMapped {
                source_map: call.source_map,
                node: &INVALID,
            }
        }
    }

    fn macro_call_callee<'ast>(
        &self,
        _storage: &RefCell<<Self::Types as AbstractTypes>::Storage<'ast>>,
        _macro_call: <Self::Types as AbstractTypes>::MacroCall<'ast>,
    ) -> <Self::Types as AbstractTypes>::Expression<'ast> {
        unreachable!()
    }
}

fn is_it_call_stmt(stmt: &Stmt) -> Option<Test<'_>> {
    if let Stmt::Expr(ExprStmt { expr, .. }) = stmt {
        is_it_call_expr(expr)
    } else {
        None
    }
}

fn is_it_call_expr(expr: &Expr) -> Option<Test<'_>> {
    if_chain! {
        if let Expr::Call(CallExpr {
            callee: Callee::Expr(callee),
            args,
            ..
        }) = expr;
        if let Expr::Ident(ident) = &**callee;
        if ident.as_ref() == "it";
        if let [arg0, arg1] = args.as_slice();
        if let Expr::Lit(Lit::Str(Str { value, .. })) = &*arg0.expr;
        if let Expr::Arrow(ArrowExpr { body, .. }) = &*arg1.expr;
        if let BlockStmtOrExpr::BlockStmt(block) = &**body;
        then {
            Some(Test {
                it_message: value,
                stmts: &block.stmts,
            })
        } else {
            None
        }
    }
}

trait ToInternalSpan {
    fn to_internal_span(&self, source_map: &SourceMap, source_file: &SourceFile) -> Span;
}

impl ToInternalSpan for SwcSpan {
    fn to_internal_span(&self, source_map: &SourceMap, source_file: &SourceFile) -> Span {
        Span {
            source_file: source_file.clone(),
            start: self.lo.to_line_column(source_map),
            end: self.hi.to_line_column(source_map),
        }
    }
}

trait ToLineColumn {
    fn to_line_column(&self, source_map: &SourceMap) -> LineColumn;
}

impl ToLineColumn for BytePos {
    fn to_line_column(&self, source_map: &SourceMap) -> LineColumn {
        let Loc {
            line, col_display, ..
        } = source_map.lookup_char_pos(*self);
        LineColumn {
            line,
            column: col_display,
        }
    }
}