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
use std::{fmt, sync::Arc};
use crate::database::hir::{DirectiveLocation, HirNodeLocation};
use crate::database::{InputDatabase, SourceCache};
use crate::FileId;
use thiserror::Error;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DiagnosticLocation {
file_id: FileId,
offset: usize,
length: usize,
}
impl ariadne::Span for DiagnosticLocation {
type SourceId = FileId;
fn source(&self) -> &FileId {
&self.file_id
}
fn start(&self) -> usize {
self.offset
}
fn end(&self) -> usize {
self.offset + self.length
}
}
impl DiagnosticLocation {
pub fn file_id(&self) -> FileId {
self.file_id
}
pub fn offset(&self) -> usize {
self.offset
}
pub fn node_len(&self) -> usize {
self.length
}
}
impl From<(FileId, rowan::TextRange)> for DiagnosticLocation {
fn from((file_id, range): (FileId, rowan::TextRange)) -> Self {
Self {
file_id,
offset: range.start().into(),
length: range.len().into(),
}
}
}
impl From<(FileId, usize, usize)> for DiagnosticLocation {
fn from((file_id, offset, length): (FileId, usize, usize)) -> Self {
Self {
file_id,
offset,
length,
}
}
}
impl From<HirNodeLocation> for DiagnosticLocation {
fn from(location: HirNodeLocation) -> Self {
Self {
file_id: location.file_id(),
offset: location.offset(),
length: location.node_len(),
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Label {
pub location: DiagnosticLocation,
pub text: String,
}
impl Label {
pub fn new(location: impl Into<DiagnosticLocation>, text: impl Into<String>) -> Self {
Self {
location: location.into(),
text: text.into(),
}
}
}
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub struct ApolloDiagnostic {
cache: Arc<SourceCache>,
pub location: DiagnosticLocation,
pub labels: Vec<Label>,
pub help: Option<String>,
pub data: Box<DiagnosticData>,
}
impl ApolloDiagnostic {
pub fn new<DB: InputDatabase + ?Sized>(
db: &DB,
location: DiagnosticLocation,
data: DiagnosticData,
) -> Self {
Self {
cache: db.source_cache(),
location,
labels: vec![],
help: None,
data: Box::new(data),
}
}
pub fn help(self, help: impl Into<String>) -> Self {
Self {
help: Some(help.into()),
..self
}
}
pub fn labels(self, labels: impl Into<Vec<Label>>) -> Self {
Self {
labels: labels.into(),
..self
}
}
pub fn label(mut self, label: Label) -> Self {
self.labels.push(label);
self
}
}
impl fmt::Display for ApolloDiagnostic {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut buf = std::io::Cursor::new(Vec::<u8>::new());
self.to_report()
.write(self.cache.as_ref(), &mut buf)
.unwrap();
writeln!(f, "{}", std::str::from_utf8(&buf.into_inner()).unwrap())
}
}
#[derive(Debug, Error, Clone, Hash, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticData {
#[error("syntax error: {message}")]
SyntaxError { message: String },
#[error("expected identifier")]
MissingIdent,
#[error("the {ty} `{name}` is defined multiple times in the document")]
UniqueDefinition {
ty: &'static str,
name: String,
original_definition: DiagnosticLocation,
redefined_definition: DiagnosticLocation,
},
#[error("the argument `{name}` is defined multiple times")]
UniqueArgument {
name: String,
original_definition: DiagnosticLocation,
redefined_definition: DiagnosticLocation,
},
#[error("the value `{name}` is defined multiple times")]
UniqueInputValue {
name: String,
original_value: DiagnosticLocation,
redefined_value: DiagnosticLocation,
},
#[error("subscription operations can only have one root field")]
SingleRootField {
fields: usize,
subscription: DiagnosticLocation,
},
#[error("{ty} root operation type is not defined")]
UnsupportedOperation {
ty: &'static str,
},
#[error("cannot query `{field}` field")]
UndefinedField {
field: String,
},
#[error("the argument `{name}` is not supported")]
UndefinedArgument { name: String },
#[error("cannot find type `{name}` in this document")]
UndefinedDefinition {
name: String,
},
#[error("type extension for `{name}` is the wrong kind")]
WrongTypeExtension {
name: String,
definition: DiagnosticLocation,
extension: DiagnosticLocation,
},
#[error("{name} directive definition cannot reference itself")]
RecursiveDefinition { name: String },
#[error("interface {name} cannot implement itself")]
RecursiveInterfaceDefinition { name: String },
#[error("values in an Enum Definition should be capitalized")]
CapitalizedValue { value: String },
#[error("fields must be unique in a definition")]
UniqueField {
field: String,
original_definition: DiagnosticLocation,
redefined_definition: DiagnosticLocation,
},
#[error("missing `{field}` field")]
MissingField {
field: String,
},
#[error("the required argument `{name}` is not provided")]
RequiredArgument { name: String },
#[error(
"Transitively implemented interfaces must also be defined on an implementing interface or object"
)]
TransitiveImplementedInterfaces {
missing_interface: String,
},
#[error("`{name}` field must return an output type")]
OutputType {
name: String,
ty: &'static str,
},
#[error("`${name}` variable must be of an input type")]
InputType {
name: String,
ty: &'static str,
},
#[error(
"custom scalars should provide a scalar specification URL via the @specifiedBy directive"
)]
ScalarSpecificationURL,
#[error("missing query root operation type in schema definition")]
QueryRootOperationType,
#[error("built-in scalars must be omitted for brevity")]
BuiltInScalarDefinition,
#[error("unused variable: `{name}`")]
UnusedVariable { name: String },
#[error("`{name}` field must return an object type")]
ObjectType {
name: String,
ty: &'static str,
},
#[error("{name} directive is not supported for {dir_loc} location")]
UnsupportedLocation {
name: String,
dir_loc: DirectiveLocation,
directive_def: DiagnosticLocation,
},
#[error("non-repeatable directive {name} can only be used once per location")]
UniqueDirective {
name: String,
original_call: DiagnosticLocation,
conflicting_call: DiagnosticLocation,
},
#[error("subscription operations can not have an introspection field as a root field")]
IntrospectionField {
field: String,
},
#[error("subselection set for scalar and enum types must be empty")]
DisallowedSubselection,
#[error("interface, union and object types must have a subselection set")]
MissingSubselection,
#[error("operation must not select different types using the same field name `{field}`")]
ConflictingField {
field: String,
original_selection: DiagnosticLocation,
redefined_selection: DiagnosticLocation,
},
}
impl DiagnosticData {
pub fn is_error(&self) -> bool {
!self.is_warning() && !self.is_advice()
}
pub fn is_warning(&self) -> bool {
matches!(self, Self::CapitalizedValue { .. })
}
pub fn is_advice(&self) -> bool {
matches!(self, Self::ScalarSpecificationURL)
}
}
impl From<Label> for ariadne::Label<DiagnosticLocation> {
fn from(label: Label) -> Self {
Self::new(label.location).with_message(label.text)
}
}
impl ApolloDiagnostic {
pub fn to_report(&self) -> ariadne::Report<'static, DiagnosticLocation> {
use ariadne::{ColorGenerator, Report, ReportKind};
let severity = if self.data.is_advice() {
ReportKind::Advice
} else if self.data.is_warning() {
ReportKind::Warning
} else {
ReportKind::Error
};
let mut colors = ColorGenerator::new();
let mut builder = Report::build(severity, self.location.file_id(), self.location.offset())
.with_message(&self.data);
builder.add_labels(
self.labels
.iter()
.map(|label| ariadne::Label::from(label.clone()).with_color(colors.next())),
);
if let Some(help) = &self.help {
builder = builder.with_help(help);
}
builder.finish()
}
}