-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiagnostic.rs
More file actions
403 lines (358 loc) · 12.1 KB
/
Copy pathdiagnostic.rs
File metadata and controls
403 lines (358 loc) · 12.1 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
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
use std::fmt;
use std::str::FromStr;
use crate::Span;
/// Stable identifier for a class of compiler diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagnosticCode {
Lexical,
Syntax,
Type,
Semantic,
MustUse,
UnusedBinding,
UnusedDeclaration,
UnusedMember,
ValueBlockSemicolon,
AmbiguousRetryFallback,
StaticSettingLookup,
SuspiciousInterpolation,
DebugOnlyUse,
StructFieldShorthand,
EmptyFutureRace,
AlwaysMatchesPattern,
}
impl DiagnosticCode {
pub const WARNINGS: [Self; 12] = [
Self::MustUse,
Self::UnusedBinding,
Self::UnusedDeclaration,
Self::UnusedMember,
Self::ValueBlockSemicolon,
Self::AmbiguousRetryFallback,
Self::StaticSettingLookup,
Self::SuspiciousInterpolation,
Self::DebugOnlyUse,
Self::StructFieldShorthand,
Self::EmptyFutureRace,
Self::AlwaysMatchesPattern,
];
pub const fn as_str(self) -> &'static str {
match self {
Self::Lexical => "SS0001",
Self::Syntax => "SS0002",
Self::Type => "SS0003",
Self::Semantic => "SS0004",
Self::MustUse => "SS1001",
Self::UnusedBinding => "SS1002",
Self::UnusedDeclaration => "SS1003",
Self::UnusedMember => "SS1004",
Self::ValueBlockSemicolon => "SS1005",
Self::AmbiguousRetryFallback => "SS1006",
Self::StaticSettingLookup => "SS1007",
Self::SuspiciousInterpolation => "SS1008",
Self::DebugOnlyUse => "SS1009",
Self::StructFieldShorthand => "SS1010",
Self::EmptyFutureRace => "SS1011",
Self::AlwaysMatchesPattern => "SS1012",
}
}
pub const fn is_warning(self) -> bool {
matches!(
self,
Self::MustUse
| Self::UnusedBinding
| Self::UnusedDeclaration
| Self::UnusedMember
| Self::ValueBlockSemicolon
| Self::AmbiguousRetryFallback
| Self::StaticSettingLookup
| Self::SuspiciousInterpolation
| Self::DebugOnlyUse
| Self::StructFieldShorthand
| Self::EmptyFutureRace
| Self::AlwaysMatchesPattern
)
}
}
impl FromStr for DiagnosticCode {
type Err = ();
fn from_str(code: &str) -> Result<Self, Self::Err> {
match code.to_ascii_uppercase().as_str() {
"SS0001" => Ok(Self::Lexical),
"SS0002" => Ok(Self::Syntax),
"SS0003" => Ok(Self::Type),
"SS0004" => Ok(Self::Semantic),
"SS1001" => Ok(Self::MustUse),
"SS1002" => Ok(Self::UnusedBinding),
"SS1003" => Ok(Self::UnusedDeclaration),
"SS1004" => Ok(Self::UnusedMember),
"SS1005" => Ok(Self::ValueBlockSemicolon),
"SS1006" => Ok(Self::AmbiguousRetryFallback),
"SS1007" => Ok(Self::StaticSettingLookup),
"SS1008" => Ok(Self::SuspiciousInterpolation),
"SS1009" => Ok(Self::DebugOnlyUse),
"SS1010" => Ok(Self::StructFieldShorthand),
"SS1011" => Ok(Self::EmptyFutureRace),
"SS1012" => Ok(Self::AlwaysMatchesPattern),
_ => Err(()),
}
}
}
impl fmt::Display for DiagnosticCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagnosticSeverity {
Error,
Warning,
Information,
Hint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DiagnosticLabelStyle {
Primary,
Secondary,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticLabel {
pub style: DiagnosticLabelStyle,
pub span: Span,
pub message: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FixApplicability {
MachineApplicable,
MaybeIncorrect,
HasPlaceholders,
Unspecified,
}
impl fmt::Display for FixApplicability {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::MachineApplicable => "machine-applicable",
Self::MaybeIncorrect => "maybe-incorrect",
Self::HasPlaceholders => "has-placeholders",
Self::Unspecified => "unspecified",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextEdit {
pub span: Span,
pub replacement: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticFix {
pub title: String,
pub applicability: FixApplicability,
pub edits: Vec<TextEdit>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum DiagnosticDocumentation {
Page(String),
MigrationTopic(String),
}
/// Lazily allocated collection of machine-readable diagnostic fixes.
///
/// Diagnostics are the parser's error value, so keeping the empty case to one
/// pointer avoids inflating every small `Result` and does not allocate for the
/// common no-fix case. Slice behavior remains available through dereferencing.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DiagnosticFixes(Option<Box<DiagnosticFixStorage>>);
#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct DiagnosticFixStorage {
values: Vec<DiagnosticFix>,
}
impl DiagnosticFixes {
pub fn push(&mut self, fix: DiagnosticFix) {
self.0.get_or_insert_with(Box::default).values.push(fix);
}
pub fn as_slice(&self) -> &[DiagnosticFix] {
self
}
}
impl std::ops::Deref for DiagnosticFixes {
type Target = [DiagnosticFix];
fn deref(&self) -> &Self::Target {
self.0
.as_deref()
.map_or(&[], |storage| storage.values.as_slice())
}
}
impl IntoIterator for DiagnosticFixes {
type Item = DiagnosticFix;
type IntoIter = std::vec::IntoIter<DiagnosticFix>;
fn into_iter(self) -> Self::IntoIter {
self.0
.map_or_else(Vec::new, |storage| storage.values)
.into_iter()
}
}
impl fmt::Display for DiagnosticSeverity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Error => "error",
Self::Warning => "warning",
Self::Information => "information",
Self::Hint => "hint",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
pub code: DiagnosticCode,
pub severity: DiagnosticSeverity,
pub message: String,
/// The primary source span. Kept directly accessible for parser recovery
/// and simple clients; `labels[0]` describes the same location.
pub span: Span,
pub labels: Vec<DiagnosticLabel>,
pub notes: Vec<String>,
pub fixes: DiagnosticFixes,
/// Compiler-owned documentation identity stored behind one pointer so the
/// parser's frequently returned error value remains compact.
documentation: Option<Box<DiagnosticDocumentation>>,
}
impl Diagnostic {
/// Constructs a syntax error. Parser call sites use this concise default;
/// other compiler stages use their category-specific constructors.
pub fn new(message: impl Into<String>, span: Span) -> Self {
Self::error(DiagnosticCode::Syntax, message, span)
}
pub fn lexical(message: impl Into<String>, span: Span) -> Self {
Self::error(DiagnosticCode::Lexical, message, span)
}
pub fn type_error(message: impl Into<String>, span: Span) -> Self {
Self::error(DiagnosticCode::Type, message, span)
}
pub fn semantic(message: impl Into<String>, span: Span) -> Self {
Self::error(DiagnosticCode::Semantic, message, span)
}
pub fn warning(code: DiagnosticCode, message: impl Into<String>, span: Span) -> Self {
let mut diagnostic = Self::error(code, message, span);
diagnostic.severity = DiagnosticSeverity::Warning;
diagnostic
}
pub fn error(code: DiagnosticCode, message: impl Into<String>, span: Span) -> Self {
Self {
code,
severity: DiagnosticSeverity::Error,
message: message.into(),
span,
labels: vec![DiagnosticLabel {
style: DiagnosticLabelStyle::Primary,
span,
message: None,
}],
notes: Vec::new(),
fixes: DiagnosticFixes::default(),
documentation: None,
}
}
pub fn with_primary_label(mut self, message: impl Into<String>) -> Self {
self.labels[0].message = Some(message.into());
self
}
pub fn with_secondary_label(mut self, span: Span, message: impl Into<String>) -> Self {
self.labels.push(DiagnosticLabel {
style: DiagnosticLabelStyle::Secondary,
span,
message: Some(message.into()),
});
self
}
pub fn with_note(mut self, note: impl Into<String>) -> Self {
self.notes.push(note.into());
self
}
pub fn with_fix(mut self, fix: DiagnosticFix) -> Self {
self.fixes.push(fix);
self
}
pub fn with_migration_topic(mut self, topic: impl Into<String>) -> Self {
self.documentation = Some(Box::new(DiagnosticDocumentation::MigrationTopic(
topic.into(),
)));
self
}
pub fn with_documentation_uri(mut self, uri: impl Into<String>) -> Self {
self.documentation = Some(Box::new(DiagnosticDocumentation::Page(uri.into())));
self
}
pub fn migration_topic(&self) -> Option<&str> {
match self.documentation.as_deref() {
Some(DiagnosticDocumentation::MigrationTopic(topic)) => Some(topic),
Some(DiagnosticDocumentation::Page(_)) | None => None,
}
}
pub fn documentation_uri(&self) -> Option<&str> {
match self.documentation.as_deref() {
Some(DiagnosticDocumentation::Page(uri)) => Some(uri),
Some(DiagnosticDocumentation::MigrationTopic(_)) | None => None,
}
}
pub fn with_machine_applicable_fix(
self,
title: impl Into<String>,
span: Span,
replacement: impl Into<String>,
) -> Self {
self.with_fix(DiagnosticFix {
title: title.into(),
applicability: FixApplicability::MachineApplicable,
edits: vec![TextEdit {
span,
replacement: replacement.into(),
}],
})
}
pub fn render(&self, source_name: &str, source: &str) -> String {
let (line, column) = line_column(source, self.span.start);
let mut rendered = format!(
"{source_name}:{line}:{column}: {}[{}]: {}",
self.severity, self.code, self.message
);
for label in &self.labels {
let Some(message) = &label.message else {
continue;
};
match label.style {
DiagnosticLabelStyle::Primary => {
rendered.push_str(&format!("\n = primary: {message}"));
}
DiagnosticLabelStyle::Secondary => {
let (line, column) = line_column(source, label.span.start);
rendered.push_str(&format!(
"\n = secondary {source_name}:{line}:{column}: {message}"
));
}
}
}
for note in &self.notes {
rendered.push_str(&format!("\n = note: {note}"));
}
for fix in self.fixes.iter() {
rendered.push_str(&format!(
"\n = help: {} ({})",
fix.title, fix.applicability
));
}
rendered
}
}
fn line_column(source: &str, offset: usize) -> (usize, usize) {
let before = &source[..offset.min(source.len())];
let line = before.bytes().filter(|byte| *byte == b'\n').count() + 1;
let column = before
.rsplit_once('\n')
.map_or(before.len() + 1, |(_, tail)| tail.len() + 1);
(line, column)
}
impl fmt::Display for Diagnostic {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for Diagnostic {}