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
//! Import errors and diagnostic-oriented source categories.
use std::{error::Error, fmt, io, path::PathBuf};
use facet::Facet;
#[cfg(feature = "json-import")]
use crate::source::PackageRelativePath;
use crate::source::{InvalidPackagePathReason, SourceId};
/// Diagnostic severity.
#[derive(Debug, Clone, Copy, Facet, PartialEq, Eq)]
#[repr(u8)]
pub enum Severity {
/// The operation cannot continue.
Error,
/// The operation can continue, but a capability or compatibility fact changed.
Warning,
}
/// Stable diagnostic code.
#[derive(Debug, Clone, Copy, Facet, PartialEq, Eq)]
#[repr(u8)]
pub enum DiagnosticCode {
/// Reading a source file failed.
ReadFile,
/// Reading a source directory failed.
ReadDir,
/// Validating a package-relative path failed.
InvalidPackagePath,
/// Canonicalizing or validating a package root failed.
InvalidPackageRoot,
/// A discovered filesystem path was outside the package root.
PathOutsidePackage,
/// A Tree-sitter external-token ordinal could not fit in Snark's ordinal type.
ExternalTokenOrdinalOverflow,
/// A `tree-sitter.json` manifest did not declare any grammars.
NoGrammars,
/// Decoding JSON into a raw compatibility model failed.
JsonDecode,
}
/// Byte span inside an imported source, when a source id is known.
#[derive(Debug, Clone, Copy, Facet, PartialEq, Eq)]
pub struct SourceSpan {
/// Imported source id.
pub source_id: SourceId,
/// Byte offset from the start of the source.
pub start: u32,
/// Span length in bytes.
pub len: u32,
}
/// Labeled diagnostic span.
#[derive(Debug, Clone, Facet, PartialEq, Eq)]
pub struct DiagnosticLabel {
/// Span being labeled.
pub span: SourceSpan,
/// Label message.
pub message: String,
}
/// Structured diagnostic emitted by import, validation, and later lowering phases.
#[derive(Debug, Clone, Facet, PartialEq, Eq)]
pub struct Diagnostic {
/// Diagnostic severity.
pub severity: Severity,
/// Stable diagnostic code.
pub code: DiagnosticCode,
/// Main diagnostic message.
pub message: String,
/// Primary source span, when available.
pub primary_span: Option<SourceSpan>,
/// Additional labeled spans.
pub labels: Vec<DiagnosticLabel>,
/// Supplemental notes.
pub notes: Vec<String>,
}
impl Diagnostic {
fn error(code: DiagnosticCode, message: impl Into<String>) -> Self {
Self {
severity: Severity::Error,
code,
message: message.into(),
primary_span: None,
labels: Vec::new(),
notes: Vec::new(),
}
}
#[cfg(feature = "json-import")]
fn with_primary_span(mut self, span: SourceSpan) -> Self {
self.primary_span = Some(span);
self
}
fn with_note(mut self, note: impl Into<String>) -> Self {
self.notes.push(note.into());
self
}
}
/// JSON document kind being imported.
#[derive(Debug, Clone, Copy, Facet, PartialEq, Eq)]
#[repr(u8)]
pub enum JsonDocumentKind {
/// `src/grammar.json`.
Grammar,
/// `tree-sitter.json`.
TreeSitterConfig,
/// `src/node-types.json`.
NodeTypes,
}
impl fmt::Display for JsonDocumentKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Grammar => f.write_str("grammar.json"),
Self::TreeSitterConfig => f.write_str("tree-sitter.json"),
Self::NodeTypes => f.write_str("node-types.json"),
}
}
}
/// Error raised while importing a Tree-sitter package or grammar.
#[derive(Debug)]
pub enum ImportError {
/// Could not validate the package root.
PackageRoot {
/// Root path requested by the caller.
path: PathBuf,
/// I/O error raised while validating the root.
source: io::Error,
},
/// Package root did not point to a directory.
PackageRootNotDirectory {
/// Root path requested by the caller.
path: PathBuf,
},
/// Could not read a file.
ReadFile {
/// Package root used for this import.
package_root: PathBuf,
/// File path.
path: PathBuf,
/// I/O error.
source: io::Error,
},
/// Could not read a directory.
ReadDir {
/// Package root used for this import.
package_root: PathBuf,
/// Directory path.
path: PathBuf,
/// I/O error.
source: io::Error,
},
/// A package-relative path was invalid.
InvalidPackagePath {
/// Invalid path.
path: PathBuf,
/// Validation failure.
reason: InvalidPackagePathReason,
},
/// A discovered package file did not live under the package root.
PathOutsidePackage {
/// Package root used for this import.
package_root: PathBuf,
/// Discovered path.
path: PathBuf,
},
/// Too many external tokens were declared for the ordinal type.
ExternalTokenOrdinalOverflow {
/// Source-order index that did not fit.
index: usize,
},
/// `tree-sitter.json` did not declare any grammar entries.
NoGrammarsInManifest {
/// Package root used for this import.
package_root: PathBuf,
},
/// Facet JSON deserialization failed.
#[cfg(feature = "json-import")]
Json {
/// Package root used for this import, when known.
package_root: Option<PathBuf>,
/// JSON document path, when known.
path: Option<PathBuf>,
/// Source id for this JSON document, when known.
source_id: Option<SourceId>,
/// Package-relative JSON document path, when known.
package_path: Option<PackageRelativePath>,
/// Document kind.
document: JsonDocumentKind,
/// Import phase.
phase: &'static str,
/// Facet JSON error.
source: facet_json::DeserializeError,
},
}
impl ImportError {
/// Convert this import error into Snark's structured diagnostic contract.
pub fn diagnostic(&self) -> Diagnostic {
match self {
Self::PackageRoot { path, source } => Diagnostic::error(
DiagnosticCode::InvalidPackageRoot,
format!("could not validate package root {}", path.display()),
)
.with_note(source.to_string()),
Self::PackageRootNotDirectory { path } => Diagnostic::error(
DiagnosticCode::InvalidPackageRoot,
format!("package root {} is not a directory", path.display()),
),
Self::ReadFile {
package_root,
path,
source,
} => Diagnostic::error(
DiagnosticCode::ReadFile,
format!("could not read {}", path.display()),
)
.with_note(format!("package root: {}", package_root.display()))
.with_note(source.to_string()),
Self::ReadDir {
package_root,
path,
source,
} => Diagnostic::error(
DiagnosticCode::ReadDir,
format!("could not read directory {}", path.display()),
)
.with_note(format!("package root: {}", package_root.display()))
.with_note(source.to_string()),
Self::InvalidPackagePath { path, reason } => Diagnostic::error(
DiagnosticCode::InvalidPackagePath,
format!("invalid package-relative path {}", path.display()),
)
.with_note(reason.to_string()),
Self::PathOutsidePackage { package_root, path } => Diagnostic::error(
DiagnosticCode::PathOutsidePackage,
format!(
"package path {} is outside the package root",
path.display()
),
)
.with_note(format!("package root: {}", package_root.display())),
Self::ExternalTokenOrdinalOverflow { index } => Diagnostic::error(
DiagnosticCode::ExternalTokenOrdinalOverflow,
format!("external token index {index} does not fit in u32"),
),
Self::NoGrammarsInManifest { package_root } => Diagnostic::error(
DiagnosticCode::NoGrammars,
"tree-sitter.json did not declare any grammars",
)
.with_note(format!("package root: {}", package_root.display())),
#[cfg(feature = "json-import")]
Self::Json {
source_id,
package_path,
document,
phase,
source,
..
} => {
let mut diagnostic = Diagnostic::error(
DiagnosticCode::JsonDecode,
format!("could not deserialize {document} during {phase}"),
);
if let (Some(source_id), Some(span)) = (*source_id, source.span) {
diagnostic = diagnostic.with_primary_span(SourceSpan {
source_id,
start: span.offset,
len: span.len,
});
}
if let Some(package_path) = package_path {
diagnostic = diagnostic.with_note(format!("package path: {package_path}"));
}
if let Some(path) = &source.path {
diagnostic = diagnostic.with_note(format!("facet path: {path}"));
}
diagnostic.with_note(source.kind.to_string())
}
}
}
}
impl fmt::Display for ImportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PackageRoot { path, source } => {
write!(
f,
"could not validate package root {}: {}",
path.display(),
source
)
}
Self::PackageRootNotDirectory { path } => {
write!(f, "package root {} is not a directory", path.display())
}
Self::ReadFile {
package_root,
path,
source,
} => {
write!(
f,
"could not read {} under package {}: {}",
path.display(),
package_root.display(),
source
)
}
Self::ReadDir {
package_root,
path,
source,
} => {
write!(
f,
"could not read directory {} under package {}: {}",
path.display(),
package_root.display(),
source
)
}
Self::InvalidPackagePath { path, reason } => {
write!(
f,
"invalid package-relative path {}: {}",
path.display(),
reason
)
}
Self::PathOutsidePackage { package_root, path } => {
write!(
f,
"path {} is not under package root {}",
path.display(),
package_root.display()
)
}
Self::ExternalTokenOrdinalOverflow { index } => {
write!(f, "external token index {index} does not fit in u32")
}
Self::NoGrammarsInManifest { package_root } => write!(
f,
"tree-sitter.json under package {} did not declare any grammars",
package_root.display()
),
#[cfg(feature = "json-import")]
Self::Json {
path,
document,
phase,
source,
..
} => match path {
Some(path) => write!(
f,
"could not deserialize {document} at {} during {phase}: {source}",
path.display()
),
None => write!(
f,
"could not deserialize {document} during {phase}: {source}"
),
},
}
}
}
impl Error for ImportError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::PackageRoot { source, .. }
| Self::ReadFile { source, .. }
| Self::ReadDir { source, .. } => Some(source),
#[cfg(feature = "json-import")]
Self::Json { source, .. } => Some(source),
Self::InvalidPackagePath { .. }
| Self::PathOutsidePackage { .. }
| Self::PackageRootNotDirectory { .. }
| Self::ExternalTokenOrdinalOverflow { .. }
| Self::NoGrammarsInManifest { .. } => None,
}
}
}