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
//! `trailing-comma` rule: multiline comma-separated lists (argument
//! lists, list literals, dict/struct literals) must end with a trailing
//! comma on the last item, and single-line lists must not. Autofix inserts
//! or removes the comma at the canonical boundary.
use harn_lexer::{FixEdit, Span, TokenKind};
use crate::diagnostic::{LintDiagnostic, LintSeverity};
/// Emit `trailing-comma` diagnostics by scanning the source's tokens for
/// comma-separated lists whose trailing comma does not match layout.
pub(crate) fn check_trailing_comma(source: &str, diagnostics: &mut Vec<LintDiagnostic>) {
let mut lexer = harn_lexer::Lexer::new(source);
let Ok(tokens) = lexer.tokenize_with_comments() else {
return;
};
#[derive(Clone, Copy)]
enum Opener {
Paren,
Bracket,
Brace,
}
struct Frame {
opener: Opener,
open_line: usize,
saw_item: bool,
/// True when `{ ... }` has been identified as a dict/struct literal.
/// Paren/Bracket are eligible when they are list-like delimiters.
eligible: bool,
/// For `{ ... }` we look at the first "meaningful" token to decide
/// eligibility. This tracks whether that decision has been made.
decision_made: bool,
/// First identifier/string token inside `{ ... }`, kept so a
/// subsequent `:` can confirm the dict/struct decision.
pending_key_token: bool,
trailing_comma: Option<Span>,
}
let mut stack: Vec<Frame> = Vec::new();
let mut previous_meaningful_kind: Option<TokenKind> = None;
fn last_meaningful_byte_before(source: &str, pos: usize) -> Option<usize> {
let bytes = source.as_bytes();
if pos == 0 {
return None;
}
let mut i = pos;
while i > 0 {
i -= 1;
let b = bytes[i];
if matches!(b, b' ' | b'\t' | b'\n' | b'\r') {
continue;
}
// Comments are intentionally not skipped — the FixEdit lands
// after a trailing comment sitting above the close.
return Some(i);
}
None
}
fn span_at_offset(source: &str, start: usize, end: usize) -> Span {
let line = source[..start].bytes().filter(|b| *b == b'\n').count() + 1;
let line_start = source[..start].rfind('\n').map(|idx| idx + 1).unwrap_or(0);
Span::with_offsets(start, end, line, start - line_start + 1)
}
fn paren_can_be_comma_list(prev: Option<&TokenKind>) -> bool {
matches!(
prev,
Some(
TokenKind::Identifier(_)
| TokenKind::RParen
| TokenKind::RBracket
| TokenKind::RBrace
| TokenKind::Fn
| TokenKind::At
)
)
}
fn token_can_start_brace_key(kind: &TokenKind) -> bool {
matches!(
kind,
TokenKind::Identifier(_)
| TokenKind::StringLiteral(_)
| TokenKind::RawStringLiteral(_)
| TokenKind::IntLiteral(_)
| TokenKind::FloatLiteral(_)
| TokenKind::True
| TokenKind::False
| TokenKind::Nil
| TokenKind::LBracket
)
}
for tok in &tokens {
match &tok.kind {
harn_lexer::TokenKind::LineComment { .. }
| harn_lexer::TokenKind::BlockComment { .. }
| harn_lexer::TokenKind::Newline => continue,
_ => {}
}
match &tok.kind {
harn_lexer::TokenKind::LParen => {
stack.push(Frame {
opener: Opener::Paren,
open_line: tok.span.line,
saw_item: false,
eligible: paren_can_be_comma_list(previous_meaningful_kind.as_ref()),
decision_made: true,
pending_key_token: false,
trailing_comma: None,
});
}
harn_lexer::TokenKind::LBracket => {
stack.push(Frame {
opener: Opener::Bracket,
open_line: tok.span.line,
saw_item: false,
eligible: true,
decision_made: true,
pending_key_token: false,
trailing_comma: None,
});
}
harn_lexer::TokenKind::LBrace => {
stack.push(Frame {
opener: Opener::Brace,
open_line: tok.span.line,
saw_item: false,
eligible: false,
decision_made: false,
pending_key_token: false,
trailing_comma: None,
});
}
harn_lexer::TokenKind::RParen
| harn_lexer::TokenKind::RBracket
| harn_lexer::TokenKind::RBrace => {
let Some(frame) = stack.pop() else { continue };
let matching = matches!(
(&frame.opener, &tok.kind),
(Opener::Paren, harn_lexer::TokenKind::RParen)
| (Opener::Bracket, harn_lexer::TokenKind::RBracket)
| (Opener::Brace, harn_lexer::TokenKind::RBrace)
);
if !matching {
continue;
}
if !frame.eligible || !frame.saw_item {
continue;
}
let close_pos = tok.span.start;
let Some(last_byte) = last_meaningful_byte_before(source, close_pos) else {
continue;
};
let has_trailing_comma = source.as_bytes()[last_byte] == b',';
if tok.span.line > frame.open_line {
if has_trailing_comma {
continue;
}
let insert_pos = last_byte + 1;
let span = span_at_offset(source, insert_pos, insert_pos);
diagnostics.push(LintDiagnostic {
rule: "trailing-comma",
message: "multiline comma-separated list is missing a trailing comma"
.to_string(),
span,
severity: LintSeverity::Warning,
suggestion: Some("add a trailing comma after the last item".to_string()),
fix: Some(vec![FixEdit {
span,
replacement: ",".to_string(),
}]),
});
} else if has_trailing_comma {
let Some(comma_span) = frame.trailing_comma else {
continue;
};
let mut delete_end = comma_span.end;
while delete_end < close_pos {
match source.as_bytes()[delete_end] {
b' ' | b'\t' => delete_end += 1,
_ => break,
}
}
let span = Span::with_offsets(
comma_span.start,
delete_end,
comma_span.line,
comma_span.column,
);
diagnostics.push(LintDiagnostic {
rule: "trailing-comma",
message: "single-line comma-separated list has a trailing comma"
.to_string(),
span,
severity: LintSeverity::Warning,
suggestion: Some("remove the trailing comma".to_string()),
fix: Some(vec![FixEdit {
span,
replacement: String::new(),
}]),
});
}
}
harn_lexer::TokenKind::Comma => {
if let Some(top) = stack.last_mut() {
top.trailing_comma = Some(tok.span);
}
}
harn_lexer::TokenKind::Colon => {
if let Some(top) = stack.last_mut() {
if matches!(top.opener, Opener::Brace)
&& !top.decision_made
&& top.pending_key_token
{
top.eligible = true;
top.decision_made = true;
}
}
}
harn_lexer::TokenKind::Identifier(_) | harn_lexer::TokenKind::StringLiteral(_) => {
if let Some(top) = stack.last_mut() {
if matches!(top.opener, Opener::Brace) && !top.decision_made {
top.pending_key_token = true;
}
}
}
_ => {
// Any other token inside `{ ... }` before a decision means
// this is a block, not a dict/struct literal.
if let Some(top) = stack.last_mut() {
if matches!(top.opener, Opener::Brace)
&& !top.decision_made
&& token_can_start_brace_key(&tok.kind)
{
top.pending_key_token = true;
} else if matches!(top.opener, Opener::Brace) && !top.decision_made {
top.decision_made = true;
top.eligible = false;
}
}
}
}
if let Some(top) = stack.last_mut() {
if !matches!(
tok.kind,
TokenKind::Comma
| TokenKind::Colon
| TokenKind::LParen
| TokenKind::LBracket
| TokenKind::LBrace
) {
top.saw_item = true;
top.trailing_comma = None;
if matches!(top.opener, Opener::Brace)
&& !top.decision_made
&& matches!(tok.kind, TokenKind::RBracket)
{
top.pending_key_token = true;
}
}
}
previous_meaningful_kind = Some(tok.kind.clone());
}
}