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
// Copyright 2020 the Deno authors. All rights reserved. MIT license.
use super::Context;
use super::LintRule;
use crate::globals::GLOBALS;
use swc_atoms::js_word;
use swc_common::SyntaxContext;
use swc_ecmascript::{
  ast::*,
  utils::ident::IdentLike,
  visit::Node,
  visit::{noop_visit_type, Visit, VisitWith},
};
use swc_ecmascript::{utils::find_ids, utils::Id};

use std::collections::HashSet;

pub struct NoUndef;

impl LintRule for NoUndef {
  fn new() -> Box<Self> {
    Box::new(NoUndef)
  }

  fn tags(&self) -> &[&'static str] {
    &["recommended"]
  }

  fn code(&self) -> &'static str {
    "no-undef"
  }

  fn lint_module(&self, context: &mut Context, module: &Module) {
    let mut collector = BindingCollector {
      top_level_ctxt: context.top_level_ctxt,
      declared: Default::default(),
    };
    module.visit_with(module, &mut collector);

    let mut visitor = NoUndefVisitor::new(context, collector.declared);
    module.visit_with(module, &mut visitor);
  }
}

/// Collects top level bindings, which have top level syntax
/// context passed to the resolver.
struct BindingCollector {
  /// Optimization. Unresolved references and top
  /// level bindings will have this context.
  top_level_ctxt: SyntaxContext,

  /// If there exists a binding with such id, it's not global.
  declared: HashSet<Id>,
}

impl BindingCollector {
  fn declare(&mut self, i: Id) {
    if i.1 != self.top_level_ctxt {
      return;
    }
    self.declared.insert(i);
  }
}

impl Visit for BindingCollector {
  fn visit_fn_decl(&mut self, f: &FnDecl, _: &dyn Node) {
    self.declare(f.ident.to_id());
  }

  fn visit_class_decl(&mut self, f: &ClassDecl, _: &dyn Node) {
    self.declare(f.ident.to_id());
  }

  fn visit_class_expr(&mut self, n: &ClassExpr, _: &dyn Node) {
    if let Some(i) = &n.ident {
      self.declare(i.to_id());
    }
  }

  fn visit_import_named_specifier(
    &mut self,
    i: &ImportNamedSpecifier,
    _: &dyn Node,
  ) {
    self.declare(i.local.to_id());
  }

  fn visit_import_default_specifier(
    &mut self,
    i: &ImportDefaultSpecifier,
    _: &dyn Node,
  ) {
    self.declare(i.local.to_id());
  }

  fn visit_import_star_as_specifier(
    &mut self,
    i: &ImportStarAsSpecifier,
    _: &dyn Node,
  ) {
    self.declare(i.local.to_id());
  }

  fn visit_var_declarator(&mut self, v: &VarDeclarator, _: &dyn Node) {
    let ids: Vec<Id> = find_ids(&v.name);
    for id in ids {
      self.declare(id);
    }
  }

  fn visit_ts_enum_decl(&mut self, e: &TsEnumDecl, _: &dyn Node) {
    self.declare(e.id.to_id());
  }

  fn visit_ts_param_prop_param(&mut self, p: &TsParamPropParam, _: &dyn Node) {
    match p {
      TsParamPropParam::Ident(i) => {
        self.declare(i.to_id());
      }
      TsParamPropParam::Assign(i) => {
        let ids: Vec<Id> = find_ids(&i.left);
        for id in ids {
          self.declare(id);
        }
      }
    }
  }

  fn visit_param(&mut self, p: &Param, _: &dyn Node) {
    let ids: Vec<Id> = find_ids(&p.pat);
    for id in ids {
      self.declare(id);
    }
  }
  fn visit_catch_clause(&mut self, c: &CatchClause, _: &dyn Node) {
    if let Some(pat) = &c.param {
      let ids: Vec<Id> = find_ids(pat);
      for id in ids {
        self.declare(id);
      }
    }

    c.body.visit_with(c, self);
  }
}

struct NoUndefVisitor<'c> {
  context: &'c mut Context,
  declared: HashSet<Id>,
}

impl<'c> NoUndefVisitor<'c> {
  fn new(context: &'c mut Context, declared: HashSet<Id>) -> Self {
    Self { context, declared }
  }

  fn check(&mut self, ident: &Ident) {
    // Thanks to this if statement, we can check for Map in
    //
    // function foo(Map) { ... }
    //
    if ident.span.ctxt != self.context.top_level_ctxt {
      return;
    }

    // Implicitly defined
    // See: https://github.com/denoland/deno_lint/issues/317
    if ident.sym == *"arguments" {
      return;
    }

    // Ignore top level bindings declared in the file.
    if self.declared.contains(&ident.to_id()) {
      return;
    }

    // Globals
    if GLOBALS.contains(&&*ident.sym) {
      return;
    }

    self.context.add_diagnostic(
      ident.span,
      "no-undef",
      format!("{} is not defined", ident.sym),
    )
  }
}

impl<'c> Visit for NoUndefVisitor<'c> {
  noop_visit_type!();

  fn visit_member_expr(&mut self, e: &MemberExpr, _: &dyn Node) {
    e.obj.visit_with(e, self);
    if e.computed {
      e.prop.visit_with(e, self);
    }
  }

  fn visit_unary_expr(&mut self, e: &UnaryExpr, _: &dyn Node) {
    if e.op == UnaryOp::TypeOf {
      return;
    }

    e.visit_children_with(self);
  }

  fn visit_expr(&mut self, e: &Expr, _: &dyn Node) {
    e.visit_children_with(self);

    if let Expr::Ident(ident) = e {
      self.check(ident)
    }
  }

  fn visit_class_prop(&mut self, p: &ClassProp, _: &dyn Node) {
    p.value.visit_with(p, self)
  }

  fn visit_prop(&mut self, p: &Prop, _: &dyn Node) {
    p.visit_children_with(self);

    if let Prop::Shorthand(i) = &p {
      self.check(i);
    }
  }

  fn visit_pat(&mut self, p: &Pat, _: &dyn Node) {
    if let Pat::Ident(i) = p {
      self.check(i);
    } else {
      p.visit_children_with(self);
    }
  }

  fn visit_assign_pat_prop(&mut self, p: &AssignPatProp, _: &dyn Node) {
    self.check(&p.key);
    p.value.visit_with(p, self);
  }

  fn visit_call_expr(&mut self, e: &CallExpr, _: &dyn Node) {
    if let ExprOrSuper::Expr(callee) = &e.callee {
      if let Expr::Ident(i) = &**callee {
        if i.sym == js_word!("import") {
          return;
        }
      }
    }

    e.visit_children_with(self)
  }
}

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

  #[test]
  fn ok_1() {
    assert_lint_ok::<NoUndef>("var a = 1, b = 2; a;");

    assert_lint_ok::<NoUndef>("function a(){}  a();");

    assert_lint_ok::<NoUndef>("function f(b) { b; }");
  }

  #[test]
  fn ok_2() {
    assert_lint_ok::<NoUndef>("var a; a = 1; a++;");

    assert_lint_ok::<NoUndef>("var a; function f() { a = 1; }");

    assert_lint_ok::<NoUndef>("Object; isNaN();");
  }

  #[test]
  fn ok_3() {
    assert_lint_ok::<NoUndef>("toString()");

    assert_lint_ok::<NoUndef>("hasOwnProperty()");

    assert_lint_ok::<NoUndef>("function evilEval(stuffToEval) { var ultimateAnswer; ultimateAnswer = 42; eval(stuffToEval); }");
  }

  #[test]
  fn ok_4() {
    assert_lint_ok::<NoUndef>("typeof a");

    assert_lint_ok::<NoUndef>("typeof (a)");

    assert_lint_ok::<NoUndef>("var b = typeof a");
  }

  #[test]
  fn ok_5() {
    assert_lint_ok::<NoUndef>("typeof a === 'undefined'");

    assert_lint_ok::<NoUndef>("if (typeof a === 'undefined') {}");

    assert_lint_ok::<NoUndef>(
      "function foo() { var [a, b=4] = [1, 2]; return {a, b}; }",
    );
  }

  #[test]
  fn ok_6() {
    assert_lint_ok::<NoUndef>("var toString = 1;");

    assert_lint_ok::<NoUndef>("function myFunc(...foo) {  return foo;}");

    assert_lint_ok::<NoUndef>("function myFunc() { console.log(arguments); }");

    // TODO(kdy1): Parse as jsx
    // assert_lint_ok::<NoUndef>(
    //   "var React, App, a=1; React.render(<App attr={a} />);",
    // );
  }

  #[test]
  fn ok_7() {
    assert_lint_ok::<NoUndef>(
      "var console; [1,2,3].forEach(obj => {\n  console.log(obj);\n});",
    );

    assert_lint_ok::<NoUndef>(
      "var Foo; class Bar extends Foo { constructor() { super();  }}",
    );

    assert_lint_ok::<NoUndef>(
      "import Warning from '../lib/warning'; var warn = new Warning('text');",
    );
  }

  #[test]
  fn ok_8() {
    assert_lint_ok::<NoUndef>("import * as Warning from '../lib/warning'; var warn = new Warning('text');");

    assert_lint_ok::<NoUndef>("var a; [a] = [0];");

    assert_lint_ok::<NoUndef>("var a; ({a} = {});");
  }

  #[test]
  fn ok_9() {
    assert_lint_ok::<NoUndef>("var a; ({b: a} = {});");

    assert_lint_ok::<NoUndef>("var obj; [obj.a, obj.b] = [0, 1];");

    assert_lint_ok::<NoUndef>(
      "(foo, bar) => { foo ||= WeakRef; bar ??= FinalizationRegistry; }",
    );
  }

  #[test]
  fn ok_10() {
    assert_lint_ok::<NoUndef>("Array = 1;");

    assert_lint_ok::<NoUndef>("class A { constructor() { new.target; } }");

    assert_lint_ok::<NoUndef>(r#"export * as ns from "source""#);
  }

  #[test]
  fn ok_11() {
    assert_lint_ok::<NoUndef>("import.meta");

    assert_lint_ok::<NoUndef>(
      "
      await new Promise((resolve: () => void, _) => {
        setTimeout(resolve, 100);
      });
      ",
    );
  }

  #[test]
  fn ok_12() {
    assert_lint_ok::<NoUndef>(
      "
      const importPath = \"./foo.ts\";
      const dataProcessor = await import(importPath);
      ",
    );
  }

  #[test]
  fn err_1() {
    assert_lint_err::<NoUndef>("a = 1;", 0);

    assert_lint_err::<NoUndef>("var a = b;", 8);

    assert_lint_err::<NoUndef>("function f() { b; }", 15);
  }

  #[test]
  fn err_2() {
    // assert_lint_err::<NoUndef>("var React; React.render(<img attr={a} />);", 0);
  }

  #[test]
  fn err_3() {
    // assert_lint_err::<NoUndef>(
    //   "var React, App; React.render(<App attr={a} />);",
    //   0,
    // );

    assert_lint_err::<NoUndef>("[a] = [0];", 1);

    assert_lint_err::<NoUndef>("({a} = {});", 2);
  }

  #[test]
  fn err_4() {
    assert_lint_err::<NoUndef>("({b: a} = {});", 5);

    assert_lint_err_n::<NoUndef>("[obj.a, obj.b] = [0, 1];", vec![1, 8]);

    assert_lint_err::<NoUndef>("const c = 0; const a = {...b, c};", 27);
  }

  #[test]
  fn deno_ok_1() {
    assert_lint_ok::<NoUndef>(
      r#"
    class PartWriter implements Deno.Writer {
      closed = false;
      private readonly partHeader: string;
      private headersWritten = false;

      constructor(
        private writer: Deno.Writer,
        readonly boundary: string,
        public headers: Headers,
        isFirstBoundary: boolean,
      ) {
        let buf = "";
        if (isFirstBoundary) {
          buf += `--${boundary}\r\n`;
        } else {
          buf += `\r\n--${boundary}\r\n`;
        }
        for (const [key, value] of headers.entries()) {
          buf += `${key}: ${value}\r\n`;
        }
        buf += `\r\n`;
        this.partHeader = buf;
      }

      close(): void {
        this.closed = true;
      }

      async write(p: Uint8Array): Promise<number> {
        if (this.closed) {
          throw new Error("part is closed");
        }
        if (!this.headersWritten) {
          this.headersWritten = true;
        }
        return this.writer.write(p);
      }
    }

    "#,
    );
  }

  #[test]
  fn deno_ok_2() {
    assert_lint_ok::<NoUndef>(
      r#"
    const listeners = [];
    for (const listener of listeners) {
      try {
      } catch (err) {
        this.emit("error", err);
      }
    }
    "#,
    );
  }
}