-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathfirst.rs
More file actions
237 lines (218 loc) · 7.02 KB
/
Copy pathfirst.rs
File metadata and controls
237 lines (218 loc) · 7.02 KB
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
use std::convert::From;
use oxc_ast::{
ast::{Statement, TSModuleReference},
AstKind,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use crate::{context::LintContext, rule::Rule};
fn first_diagnostic(span: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("Import statements must come first")
.with_help("Move import statement to the top of the file")
.with_label(span)
}
fn absolute_first_diagnostic(span: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("Relative imports before absolute imports are prohibited")
.with_help("Move absolute import above relative import")
.with_label(span)
}
#[derive(Debug, Default, Clone)]
pub struct First {
absolute_first: AbsoluteFirst,
}
#[derive(Debug, Default, Clone)]
enum AbsoluteFirst {
AbsoluteFirst,
#[default]
DisableAbsoluteFirst,
}
impl From<&str> for AbsoluteFirst {
fn from(raw: &str) -> Self {
match raw {
"absolute-first" => Self::AbsoluteFirst,
_ => Self::DisableAbsoluteFirst,
}
}
}
declare_oxc_lint!(
/// ### What it does
///
/// Forbids any non-import statements before imports except directives.
///
/// ### Why is this bad?
///
/// Notably, imports are hoisted, which means the imported modules will be evaluated
/// before any of the statements interspersed between them.
/// Keeping all imports together at the top of the file may prevent surprises
/// resulting from this part of the spec
///
/// ### Examples
///
/// Examples of **incorrect** code for this rule:
/// ```js
/// import { x } from './foo';
/// export { x };
/// import { y } from './bar';
/// ```
///
/// Examples of **correct** code for this rule:
/// ```js
/// import { x } from './foo';
/// import { y } from './bar';
/// export { x, y }
/// ```
///
/// ### Options
///
/// with `"absolute-first"`:
///
/// Examples of **incorrect** code for this rule:
/// ```js
/// import { x } from './foo';
/// import { y } from 'bar'
/// ```
///
/// Examples of **correct** code for this rule:
/// ```js
/// import { y } from 'bar';
/// import { x } from './foo'
/// ```
///
First,
import,
style,
pending // TODO: fixer
);
fn is_relative_path(path: &str) -> bool {
path.starts_with("./")
}
/// <https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/first.md>
impl Rule for First {
fn from_configuration(value: serde_json::Value) -> Self {
let obj = value.get(0);
Self {
absolute_first: obj
.and_then(serde_json::Value::as_str)
.map(AbsoluteFirst::from)
.unwrap_or_default(),
}
}
fn run_once(&self, ctx: &LintContext<'_>) {
let mut non_import_count = 0;
let mut any_relative = false;
let Some(root) = ctx.nodes().root_node() else {
return;
};
let AstKind::Program(program) = root.kind() else { unreachable!() };
for statement in &program.body {
match statement {
Statement::TSImportEqualsDeclaration(decl) => match &decl.module_reference {
TSModuleReference::ExternalModuleReference(mod_ref) => {
if matches!(self.absolute_first, AbsoluteFirst::AbsoluteFirst) {
if is_relative_path(mod_ref.expression.value.as_str()) {
any_relative = true;
} else if any_relative {
ctx.diagnostic(absolute_first_diagnostic(mod_ref.expression.span));
}
}
if non_import_count > 0 {
ctx.diagnostic(first_diagnostic(decl.span));
}
}
TSModuleReference::IdentifierReference(_)
| TSModuleReference::QualifiedName(_) => {}
},
Statement::ImportDeclaration(decl) => {
if matches!(self.absolute_first, AbsoluteFirst::AbsoluteFirst) {
if is_relative_path(decl.source.value.as_str()) {
any_relative = true;
} else if any_relative {
ctx.diagnostic(absolute_first_diagnostic(decl.source.span));
}
}
if non_import_count > 0 {
ctx.diagnostic(first_diagnostic(decl.span));
}
}
_ => {
non_import_count += 1;
}
}
}
}
}
#[test]
fn test() {
use serde_json::json;
use crate::tester::Tester;
let pass = vec![
(
r"import { x } from './foo'; import { y } from './bar';
export { x, y }",
None,
),
(r"import { x } from 'foo'; import { y } from './bar'", None),
(r"import { x } from './foo'; import { y } from 'bar'", None),
(
r"import { x } from './foo'; import { y } from 'bar'",
Some(json!(["disable-absolute-first"])),
),
// Note: original rule contains test case below for `angular-eslint` parser
// which is not implemented in oxc
(
r"'use directive';
import { x } from 'foo';",
None,
),
// covers TSImportEqualsDeclaration (original rule support it, but with no test cases)
(
r"import { x } from './foo';
import F3 = require('mod');
export { x, y }",
None,
),
];
let fail = vec![
(
r"import { x } from './foo';
export { x };
import { y } from './bar';",
None,
),
(
r"import { x } from './foo';
export { x };
import { y } from './bar';
import { z } from './baz';",
None,
),
(r"import { x } from './foo'; import { y } from 'bar'", Some(json!(["absolute-first"]))),
(
r"import { x } from 'foo';
'use directive';
import { y } from 'bar';",
None,
),
(
r"var a = 1;
import { y } from './bar';
if (true) { x() };
import { x } from './foo';
import { z } from './baz';",
None,
),
(r"if (true) { console.log(1) }import a from 'b'", None),
// covers TSImportEqualsDeclaration (original rule support it, but with no test cases)
(
r"import { x } from './foo';
export { x };
import F3 = require('mod');",
None,
),
];
Tester::new(First::NAME, First::PLUGIN, pass, fail)
.change_rule_path("index.ts")
.with_import_plugin(true)
.test_and_snapshot();
}