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
use std::{fmt, sync::Arc};
use rowan::GreenNode;
use crate::{Diagnostic, SemanticDocument, SyntaxNode, semantic, syntax};
/// The published TOML language specification used to parse and validate a snapshot.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum TomlVersion {
/// TOML 1.0.0.
V1_0,
/// TOML 1.1.0.
#[default]
V1_1,
}
/// An immutable TOML source snapshot and its derived syntax, semantics, diagnostics, and spans.
///
/// Clones share all snapshot data. Applying [`TextChange`] values creates another independently
/// queryable snapshot rather than mutating the original.
#[derive(Clone)]
pub struct Document {
inner: Arc<DocumentData>,
}
struct DocumentData {
text: Arc<str>,
version: TomlVersion,
revision: Revision,
#[allow(dead_code)]
green: GreenNode,
diagnostics: Arc<[Diagnostic]>,
semantic: SemanticDocument,
highlights: Arc<[crate::Highlight]>,
}
/// A monotonically increasing identifier for snapshots derived through [`Document::with_changes`].
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Revision(u64);
impl Revision {
/// The revision assigned to a freshly parsed snapshot.
pub const INITIAL: Self = Self(0);
/// Creates a revision from its numeric representation.
#[must_use]
pub const fn new(value: u64) -> Self {
Self(value)
}
/// Returns the numeric representation.
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
}
/// A source update applied to an immutable [`Document`] snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TextChange {
/// Replaces the complete document text.
Replace(Arc<str>),
/// Replaces a UTF-8 byte range with new text.
Edit {
/// The half-open byte range in the result of the preceding change.
range: crate::TextRange,
/// Text inserted in place of `range`.
insert: Arc<str>,
},
}
impl TextChange {
/// Creates a complete-document replacement.
#[must_use]
pub fn replace(text: impl Into<Arc<str>>) -> Self {
Self::Replace(text.into())
}
/// Creates a range edit whose offsets are UTF-8 bytes.
#[must_use]
pub fn edit(range: crate::TextRange, insert: impl Into<Arc<str>>) -> Self {
Self::Edit {
range,
insert: insert.into(),
}
}
}
/// Why a source update could not produce a new snapshot.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ChangeError {
/// The edit range is reversed or extends beyond the current text.
#[error("edit range {start}..{end} is outside a document of {text_len} bytes")]
OutOfBounds {
/// Requested start offset.
start: u32,
/// Requested exclusive end offset.
end: u32,
/// Current document length in bytes.
text_len: u32,
},
/// An edit offset splits a multi-byte UTF-8 scalar value.
#[error("byte offset {offset} is not a UTF-8 character boundary")]
InvalidUtf8Boundary {
/// The invalid byte offset.
offset: u32,
},
/// Incrementing the previous snapshot revision would exceed `u64`.
#[error("document revision overflowed")]
RevisionOverflow,
}
impl Document {
/// Parses a document using TOML 1.1 rules.
#[must_use]
pub fn parse(text: impl Into<Arc<str>>) -> Self {
Self::parse_as(text, TomlVersion::V1_1)
}
/// Parses a document with an explicit TOML language version.
#[must_use]
pub fn parse_as(text: impl Into<Arc<str>>, version: TomlVersion) -> Self {
Self::parse_at(text.into(), version, Revision::INITIAL)
}
fn parse_at(text: Arc<str>, version: TomlVersion, revision: Revision) -> Self {
Self::parse_pipeline(text, version, revision, None).0
}
/// Parses `text` under `version` and immediately formats the snapshot
/// with `options`, producing exactly what `parse_as` followed by
/// `format_with` would. One-shot pipelines get the formatted text's
/// purely lexical construction overlapped with semantic analysis.
#[must_use]
pub fn parse_and_format_with(
text: impl Into<Arc<str>>,
version: TomlVersion,
options: &crate::FormatOptions,
) -> (Self, crate::FormatOutcome) {
let text = text.into();
if options.target_version != version {
// A version mismatch makes the formatter's safety check re-parse
// under the target version, so there is no overlap to win here.
let document = Self::parse_at(text, version, Revision::INITIAL);
let outcome = document.format_with(options);
return (document, outcome);
}
let (document, formatted) =
Self::parse_pipeline(text, version, Revision::INITIAL, Some(options));
let outcome = match formatted {
Some(output) => crate::formatter::finish_prebuilt(&document, options, output),
None => document.format_with(options),
};
(document, outcome)
}
/// Shared parse pipeline. When `format_options` is given, the formatted
/// text is additionally produced on the side-analysis thread, so a
/// one-shot parse-then-format pipeline pays no extra wall time for it.
fn parse_pipeline(
text: Arc<str>,
version: TomlVersion,
revision: Revision,
format_options: Option<&crate::FormatOptions>,
) -> (Self, Option<String>) {
let syntax::Parse {
green,
mut diagnostics,
tokens,
} = syntax::parse(&text);
// Highlight collection, validation, and the optional lexical
// formatting pass only need the source text, token stream, and green
// tree. Native targets overlap them with semantic lowering. WebAssembly
// targets run the same pure operations sequentially because
// `wasm32-unknown-unknown` has no native thread-spawn capability.
#[cfg(target_family = "wasm")]
let (lowered, (highlights, validation_diagnostics, formatted)) = {
let lowered = semantic::lower(&text, &green);
let highlights = crate::highlight::collect(&text, &tokens);
let validation_diagnostics = crate::validate::validate(&text, version, &green, &tokens);
let formatted =
format_options.map(|options| crate::formatter::build_text(&text, options));
(lowered, (highlights, validation_diagnostics, formatted))
};
#[cfg(not(target_family = "wasm"))]
let (lowered, (highlights, validation_diagnostics, formatted)) =
std::thread::scope(|scope| {
let side = scope.spawn(|| {
let highlights = crate::highlight::collect(&text, &tokens);
let validation_diagnostics =
crate::validate::validate(&text, version, &green, &tokens);
let formatted =
format_options.map(|options| crate::formatter::build_text(&text, options));
(highlights, validation_diagnostics, formatted)
});
let lowered = semantic::lower(&text, &green);
let side = match side.join() {
Ok(side) => side,
Err(panic) => std::panic::resume_unwind(panic),
};
(lowered, side)
});
drop(tokens);
diagnostics.extend(validation_diagnostics);
diagnostics.extend(lowered.diagnostics);
diagnostics.sort_by_key(Diagnostic::range);
let document = Self {
inner: Arc::new(DocumentData {
text,
version,
revision,
green,
diagnostics: diagnostics.into(),
semantic: lowered.document,
highlights: highlights.into(),
}),
};
(document, formatted)
}
/// Returns the exact source text owned by this snapshot.
#[must_use]
pub fn text(&self) -> &str {
&self.inner.text
}
/// Returns the TOML language version selected for this snapshot.
#[must_use]
pub fn version(&self) -> TomlVersion {
self.inner.version
}
/// Returns the snapshot revision.
#[must_use]
pub fn revision(&self) -> Revision {
self.inner.revision
}
/// Returns parser, version, and semantic diagnostics sorted by primary range.
#[must_use]
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.inner.diagnostics
}
/// Returns declarations and lazily materialized decoded values for this snapshot.
#[must_use]
pub fn semantics(&self) -> &SemanticDocument {
&self.inner.semantic
}
/// Returns source-backed semantic highlight spans.
#[must_use]
pub fn highlights(&self) -> &[crate::Highlight] {
&self.inner.highlights
}
/// Formats with default layout options and this snapshot's TOML version.
///
/// Invalid snapshots are refused rather than rewritten.
#[must_use]
pub fn format(&self) -> crate::FormatOutcome {
let options = crate::FormatOptions {
target_version: self.version(),
..crate::FormatOptions::default()
};
self.format_with(&options)
}
/// Formats with explicit layout and target-version options.
///
/// If `options.target_version` differs from [`Self::version`], safety diagnostics are
/// recomputed under the target version before any change is returned.
#[must_use]
pub fn format_with(&self, options: &crate::FormatOptions) -> crate::FormatOutcome {
crate::formatter::format(self, options)
}
/// Returns a snapshot-scoped syntax root without exposing Rowan types.
#[must_use]
pub fn root(&self) -> SyntaxNode {
syntax::root(self.inner.green.clone())
}
/// Applies edits in iteration order and returns a new immutable snapshot.
/// Each edit range is interpreted against the result of the preceding edit.
///
/// # Errors
///
/// Returns an error when a range is out of bounds, splits a UTF-8 code point,
/// or the snapshot revision cannot be incremented.
pub fn with_changes(
&self,
changes: impl IntoIterator<Item = TextChange>,
) -> Result<Self, ChangeError> {
let mut text = self.text().to_owned();
for change in changes {
match change {
TextChange::Replace(replacement) => text = replacement.to_string(),
TextChange::Edit { range, insert } => {
let start = range.start() as usize;
let end = range.end() as usize;
if start > end || end > text.len() {
return Err(ChangeError::OutOfBounds {
start: range.start(),
end: range.end(),
text_len: u32::try_from(text.len()).unwrap_or(u32::MAX),
});
}
if !text.is_char_boundary(start) {
return Err(ChangeError::InvalidUtf8Boundary {
offset: range.start(),
});
}
if !text.is_char_boundary(end) {
return Err(ChangeError::InvalidUtf8Boundary {
offset: range.end(),
});
}
text.replace_range(start..end, &insert);
}
}
}
let revision = self
.revision()
.get()
.checked_add(1)
.map(Revision::new)
.ok_or(ChangeError::RevisionOverflow)?;
Ok(Self::parse_at(text.into(), self.version(), revision))
}
}
impl fmt::Debug for Document {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Document")
.field("version", &self.version())
.field("revision", &self.revision())
.field("text_len", &self.text().len())
.field("diagnostics", &self.diagnostics())
.finish_non_exhaustive()
}
}