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
|
use std::ops::Range;
use cargo_metadata::diagnostic::{
DiagnosticCodeBuilder, DiagnosticLevel as CargoLevel, DiagnosticSpanBuilder,
DiagnosticSpanLineBuilder,
};
use cargo_metadata::{Message, PackageId};
use annotate_snippets::level::{ERROR, HELP, NOTE, WARNING};
use annotate_snippets::{AnnotationKind, Group, Patch, Renderer, Snippet};
use mingling::macros::{buffer, chain, pack, r_append, r_eprintln, renderer};
use mingling::{AnyOutput, ProgramCollect, Routable};
use crate::Next;
use crate::metadata::setup::ResUsingJson;
/// Complete structure of a Lint report, containing inspection results and associated metadata.
#[derive(Default)]
pub struct MlintReport {
/// Source file name
pub file_name: String,
/// Full source text of the file, used to extract line content and compute byte offsets
pub source_code: String,
/// Severity level of the report
pub level: MlintLevel,
/// Name of the Lint
pub lint_code: String,
/// Content of the report
pub message: String,
/// Source code locations
pub spans: Vec<LintSpan>,
/// Attached sub-reports for this report
pub attached_reports: Vec<MlintReport>,
/// Package ID that this report belongs to
pub package_id: Option<String>,
/// Compilation target name that this report belongs to
pub target_name: Option<String>,
/// Compilation target type that this report belongs to
pub target_kind: Option<String>,
/// Compilation target source file path that this report belongs to
pub target_src_path: Option<String>,
/// Suggestions for automatic fix (shown as diff in annotated output)
pub suggestions: Vec<LintSuggestion>,
}
/// Report severity level, indicating the seriousness of the Lint result.
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub enum MlintLevel {
#[default]
Note,
Error,
Warning,
Help,
}
/// Source code location span, representing a range of source code and its associated text information.
pub struct LintSpan {
/// Starting line number (1-based)
pub line_start: usize,
/// Ending line number (1-based)
pub line_end: usize,
/// Starting column (1-based char offset)
pub column_start: usize,
/// Ending column (1-based char offset)
pub column_end: usize,
/// Source lines at this location
pub text: Vec<LintSpanLine>,
/// Optional label description
pub label: Option<String>,
}
/// A single line of text in a source location with highlight range.
pub struct LintSpanLine {
/// Full source line text (no trailing `\n`)
pub text: String,
/// Highlight start (1-based char offset)
pub highlight_start: usize,
/// Highlight end (1-based char offset)
pub highlight_end: usize,
}
/// A suggestion shown as a diff in the output (e.g. `- old code` / `+ new code`).
#[derive(Clone, Debug, Default)]
pub struct LintSuggestion {
/// Source text that the suggestion applies to (a single line or snippet)
pub source: String,
/// Line number where the suggestion applies
pub line_start: usize,
/// Byte range within `source` to replace
pub byte_range: Range<usize>,
/// Replacement text
pub replacement: String,
}
impl MlintReport {
/// Build a `LintSpan` from a syn spanned item and the source text.
pub fn span_from_syn<T: syn::spanned::Spanned>(value: &T, source: &str) -> LintSpan {
let span = value.span();
let start = span.start();
let end = span.end();
// Extract line content from source
let lines: Vec<&str> = source.lines().collect();
let text = if start.line == end.line && start.line <= lines.len() {
let line_text = lines[start.line.saturating_sub(1)];
let hl_start = proc_macro2_byte_col_to_char_1based(line_text, start.column);
let hl_end = proc_macro2_byte_col_to_char_1based(line_text, end.column);
vec![LintSpanLine {
text: line_text.to_string(),
highlight_start: hl_start,
highlight_end: hl_end,
}]
} else {
// Multi-line: generate line by line
(start.line..=end.line.min(lines.len()))
.map(|i| {
let line_text = lines[i.saturating_sub(1)];
let (hl_start, hl_end) = if i == start.line {
(
proc_macro2_byte_col_to_char_1based(line_text, start.column),
line_text.chars().count(),
)
} else if i == end.line {
(
1,
proc_macro2_byte_col_to_char_1based(line_text, end.column),
)
} else {
(1, line_text.chars().count())
};
LintSpanLine {
text: line_text.to_string(),
highlight_start: hl_start,
highlight_end: hl_end,
}
})
.collect::<Vec<_>>()
};
LintSpan {
line_start: start.line,
line_end: end.line,
column_start: proc_macro2_byte_col_to_char_1based(
lines.get(start.line.saturating_sub(1)).unwrap_or(&""),
start.column,
),
column_end: proc_macro2_byte_col_to_char_1based(
lines.get(end.line.saturating_sub(1)).unwrap_or(&""),
end.column,
),
text,
label: None,
}
}
/// Compute byte offset from (line, column) within source.
/// line: 1-based, column: 1-based char offset.
pub fn line_col_to_byte_offset(&self, line: usize, col: usize) -> usize {
let mut byte_pos = 0usize;
for (i, line_str) in self.source_code.lines().enumerate() {
if i + 1 == line {
return byte_pos + char_1based_to_byte_offset(line_str, col);
}
byte_pos += line_str.len() + 1; // +1 for \n
}
self.source_code.len()
}
}
/// proc-macro2's LineColumn.column is **0-based byte offset**.
/// Convert to 1-based char offset.
fn proc_macro2_byte_col_to_char_1based(line: &str, byte_col: usize) -> usize {
line.char_indices()
.position(|(i, _)| i >= byte_col)
.map(|pos| pos + 1) // → 1-based
.unwrap_or(line.chars().count().max(1))
}
/// 1-based char offset → byte offset within a string
fn char_1based_to_byte_offset(s: &str, char_1based: usize) -> usize {
s.char_indices()
.nth(char_1based.saturating_sub(1))
.map(|(i, _)| i)
.unwrap_or(s.len())
}
impl MlintReport {
pub fn to_annotate_snippet_render(&self) -> String {
let level = mlinit_level_to_annotate(&self.level);
let title = level.clone().primary_title(&self.message);
// code 不放在 title 里,改放在 note 中
let mut group = Group::with_title(title);
for span in &self.spans {
let source = span
.text
.iter()
.map(|l| l.text.as_str())
.collect::<Vec<_>>()
.join("\n");
let byte_range = if span.text.len() == 1 {
let line = &span.text[0];
let start = char_1based_to_byte_offset(&line.text, line.highlight_start);
let end = char_1based_to_byte_offset(&line.text, line.highlight_end);
start..end
} else {
let first = &span.text[0];
let last = span.text.last().unwrap();
let start = char_1based_to_byte_offset(&first.text, first.highlight_start);
let prefix_len: usize = span.text[..span.text.len() - 1]
.iter()
.map(|l| l.text.len() + 1)
.sum();
let end = prefix_len + char_1based_to_byte_offset(&last.text, last.highlight_end);
start..end
};
let mut snippet = Snippet::source(source)
.line_start(span.line_start)
.path(&self.file_name);
let annotation = match &span.label {
Some(label) => AnnotationKind::Primary
.span(byte_range)
.label(label.as_str()),
None => AnnotationKind::Primary.span(byte_range),
};
snippet = snippet.annotation(annotation);
group = group.element(snippet);
}
for child in &self.attached_reports {
let child_level = mlinit_level_to_annotate(&child.level);
let msg = child_level.clone().message(&child.message);
group = group.element(msg);
}
// Render suggestions as diffs
for sugg in &self.suggestions {
let patch_snippet = Snippet::source(sugg.source.clone())
.line_start(sugg.line_start)
.path(&self.file_name)
.patch(Patch::new(
sugg.byte_range.clone(),
sugg.replacement.clone(),
));
group = group.element(patch_snippet);
}
if !self.lint_code.is_empty() {
let level_name = match self.level {
MlintLevel::Error => "deny",
MlintLevel::Warning => "warn",
MlintLevel::Note | MlintLevel::Help => "allow",
};
let note_text = format!("`#[mlint({level_name}({}))]` on by default", self.lint_code);
let note_msg = NOTE.clone().message(note_text);
group = group.element(note_msg);
}
let renderer = Renderer::styled();
renderer.render(&[group])
}
}
fn mlinit_level_to_annotate(level: &MlintLevel) -> &'static annotate_snippets::Level<'static> {
match level {
MlintLevel::Error => &ERROR,
MlintLevel::Warning => &WARNING,
MlintLevel::Note => &NOTE,
MlintLevel::Help => &HELP,
}
}
impl MlintReport {
pub fn to_compiler_message(&self) -> Message {
use cargo_metadata::{CompilerMessageBuilder, Edition, TargetBuilder};
let target_kind_str = self.target_kind.as_deref().unwrap_or("bin");
let target_kind_parsed: cargo_metadata::TargetKind = target_kind_str.into();
let crate_kind: cargo_metadata::CrateType = target_kind_str.into();
let target = TargetBuilder::default()
.name(self.target_name.as_deref().unwrap_or_default())
.kind(vec![target_kind_parsed])
.crate_types(vec![crate_kind])
.required_features(Vec::<String>::new())
.src_path(self.target_src_path.as_deref().unwrap_or_default())
.edition(Edition::E2021)
.doctest(false)
.test(false)
.doc(false)
.build()
.unwrap();
let diagnostic = self.build_diagnostic(
&self.message,
&self.lint_code,
&self.level,
&self.spans,
&self.attached_reports,
);
Message::CompilerMessage(
CompilerMessageBuilder::default()
.package_id(PackageId {
repr: self.package_id.clone().unwrap_or_else(|| "unknown".into()),
})
.target(target)
.message(diagnostic)
.build()
.unwrap(),
)
}
fn build_diagnostic(
&self,
message: &str,
code: &str,
level: &MlintLevel,
spans: &[LintSpan],
children: &[MlintReport],
) -> cargo_metadata::diagnostic::Diagnostic {
cargo_metadata::diagnostic::DiagnosticBuilder::default()
.message(message)
.code(
DiagnosticCodeBuilder::default()
.code(code)
.explanation(None)
.build()
.unwrap(),
)
.level(match level {
MlintLevel::Error => CargoLevel::Error,
MlintLevel::Warning => CargoLevel::Warning,
MlintLevel::Note => CargoLevel::Note,
MlintLevel::Help => CargoLevel::Help,
})
.spans(
spans
.iter()
.map(|s| self.lint_span_to_diagnostic_span(s))
.collect::<Vec<_>>(),
)
.children(
children
.iter()
.map(|c| {
self.build_diagnostic(
&c.message,
&c.lint_code,
&c.level,
&c.spans,
&c.attached_reports,
)
})
.collect::<Vec<_>>(),
)
.rendered(None)
.build()
.unwrap()
}
fn lint_span_to_diagnostic_span(
&self,
span: &LintSpan,
) -> cargo_metadata::diagnostic::DiagnosticSpan {
let byte_start = self.line_col_to_byte_offset(span.line_start, span.column_start);
let byte_end = self.line_col_to_byte_offset(span.line_end, span.column_end);
DiagnosticSpanBuilder::default()
.file_name(&self.file_name)
.byte_start(byte_start as u32)
.byte_end(byte_end as u32)
.line_start(span.line_start)
.line_end(span.line_end)
.column_start(span.column_start)
.column_end(span.column_end)
.is_primary(true)
.text(
span.text
.iter()
.map(|l| {
DiagnosticSpanLineBuilder::default()
.text(&l.text)
.highlight_start(l.highlight_start)
.highlight_end(l.highlight_end)
.build()
.unwrap()
})
.collect::<Vec<_>>(),
)
.label(span.label.clone())
.suggested_replacement(self.suggestions.first().map(|s| s.replacement.clone()))
.suggestion_applicability(if !self.suggestions.is_empty() {
Some(cargo_metadata::diagnostic::Applicability::MachineApplicable)
} else {
None
})
.expansion(None)
.build()
.unwrap()
}
}
pack!(StateLintReports = Vec<MlintReport>);
pack!(ResultLintReportsAnnotateSnippet = Vec<MlintReport>);
pack!(ResultLintReportsJson = Vec<MlintReport>);
#[chain]
pub fn handle_state_lint_reports(reports: StateLintReports, using_json: &ResUsingJson) -> Next {
if using_json.using {
ResultLintReportsJson::new(reports.inner).to_render()
} else {
ResultLintReportsAnnotateSnippet::new(reports.inner).to_render()
}
}
#[renderer(buffer)]
pub fn render_lint_reports(reports: ResultLintReportsAnnotateSnippet) {
for report in reports.inner {
r_eprintln!("{}", report.to_annotate_snippet_render());
}
}
#[renderer(buffer)]
pub fn render_lint_reports_json(reports: ResultLintReportsJson) {
for report in reports.inner {
// DIRTY: Dispatch to the Message renderer using AnyOutput to obtain the render result and append it to the Buffer
r_append!(|| { crate::ThisProgram::render(AnyOutput::new(report.to_compiler_message())) });
}
}
|