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
//! Svelte formatting, and parsing to the wire JSON of Svelte's modern `parse()` — part of
//! [tsv](https://github.com/fuzdev/tsv).
//!
//! [`format()`] formats one component in one call; a [`Formatter`] formats many on one
//! thread, keeping its arenas warm between calls. Each `<script>`, `<style>` and template
//! expression is formatted by [`tsv_ts`](https://docs.rs/tsv_ts) or
//! [`tsv_css`](https://docs.rs/tsv_css) as part of one document. The formatter is
//! non-configurable: Prettier's style with a print width of 100, tabs, single quotes and no
//! trailing commas. Formatting output is not frozen — it changes between releases as
//! formatting bugs are fixed.
//!
//! ## Usage
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use tsv_svelte::{Formatter, format};
//!
//! assert_eq!(
//! format("<script>let x=1</script><p>{x}</p>")?,
//! "<script>\n\tlet x = 1;\n</script>\n\n<p>{x}</p>\n"
//! );
//! let mut formatter = Formatter::new();
//! assert_eq!(formatter.format("<p class=\"a\">y</p>")?, "<p class=\"a\">y</p>\n");
//!
//! // Parse to the wire JSON AST (the `json` feature, on by default)
//! # #[cfg(feature = "json")]
//! # {
//! let json = tsv_svelte::parse_to_json("<p>x</p>")?;
//! assert!(json.contains(r#""type":"Root""#));
//! # }
//! # Ok(())
//! # }
//! ```
//!
//! The wire JSON is the AST as JSON in the canonical parser's shape — Svelte's modern
//! `parse()`'s here. Its `start` / `end` are UTF-16 offsets, and the default wire is
//! span-only: no `loc` (the `locations` feature adds it). [`Error::span`], unlike the wire, is
//! a UTF-8 byte range.
//!
//! ## Errors
//!
//! A source the format cannot take is an [`Error`] — here a refusal of one that parses:
//!
//! ```
//! use tsv_svelte::{ErrorKind, format};
//!
//! // formatting folds this `\r` to `\n`, which would end the in-tag comment early
//! let err = format("<div // a\rb\n></div>").unwrap_err();
//! assert_eq!(err.kind(), ErrorKind::Refusal);
//! assert_eq!(err.span(), Some(9..10));
//! ```
//!
//! Every tsv language crate returns the same [`Error`]: its [`Error::kind`], its
//! [`Error::span`] in the input's UTF-8 bytes, and [`Error::to_report`] — how tsv's bindings
//! (its npm packages) report it — in the wire's UTF-16 offsets and lines; one line under
//! `{}`, the `tsv` CLI's frame under `{:#}`.
//!
//! ## Deep input
//!
//! The parser refuses a tree past its depth limits with [`ErrorKind::TooDeep`], so every
//! walk of an accepted tree fits a 2 MiB thread in an optimized build and a 16 MiB one in a
//! debug build. The limits count a whole
//! component, its `<script>`, `<style>` and template expressions included, against one
//! budget. A stack overflow aborts the process rather than panicking, so a debug
//! build handling input it does not control — `cargo test` runs each test on a 2 MiB thread —
//! wraps the call in [`run_with_stack`], which runs it on a thread reserving [`STACK_SIZE`].
//!
//! ## Features
//!
//! default features off for a format-only build.
//! - `locations` — `JsonOptions::locations`, adding a `loc` (line and column) to every
//! positioned object of the wire, and a `name_loc` to elements, attributes and directives.
//!
//! The `_internal_*` features are tsv's own diagnostics, not for consumers
//! ([Stability](#stability)).
//!
//! ## Stability
//!
//! This release exposes no AST: parsing returns the wire JSON, in Svelte's modern
//! `parse()` shape, which `@fuzdev/tsv-parse-wasm`'s [`tsv_ast.d.ts`] types.
//!
//! [`tsv_ast.d.ts`]: https://github.com/fuzdev/tsv/blob/main/crates/tsv_wasm/types/tsv_ast.d.ts
//!
//! Items hidden from these docs (`__private`, `ast` and every other `#[doc(hidden)]` item)
//! and the `_internal_*` features are tsv's own plumbing for its sibling crates, which pin
//! each other exactly; they change in any release, outside semver.
// The README's example compiles as a doctest, so the crates.io page cannot drift.
;
// A hidden module renders nowhere public, so its links to private items are maintainer
// navigation (`docs:audit` documents private items); only the public-only docs.rs build
// fires the lint, which `docs:audit:docsrs` denies everywhere else.
use ;
use Root;
pub use Formatter;
pub use ;
use ;
// `tests/public_reexports.rs` (outside this crate) names every item above through this
// crate's path: cargo-semver-checks cannot see a dropped or demoted re-export.
/// The coordinates a Svelte document's positions are reported in — Svelte's: a leading
/// BOM **elided** (Svelte's `parse` strips it before parsing, so every offset indexes the
/// BOM-less string, its acorn islands included), and `\n` alone ending a line, in the
/// markup and in every `<script>`, template expression and `<style>` alike. The wire
/// writer's tables and every parse error's point (`Error::wire_point`, and the
/// `line:col` its message prints) read this one statement. Hidden: plumbing for the sibling
/// crates.
pub const WIRE_COORDINATES: WireCoordinates =
new;
/// `parse_folded`'s refusal: parse the author's own bytes, and refuse the first in-tag `//`
/// comment that holds a lone `<CR>`. Its parse lands in `arena` beside the folded one, which
/// the caller resets with it — a cost only a document holding a lone `<CR>` pays.
/// Parse and format `source` in one call.
///
/// Carriage returns (`\r\n` and a lone `\r`) are folded to `\n` ahead of the parse, so
/// the output is LF-only.
/// A leading byte-order mark is not echoed — except ahead of a content U+FEFF at the start of
/// the output, which needs it to survive the next read — so a caller that keeps a file's BOM
/// writes it back only when the output does not already begin with U+FEFF. A source with
/// nothing to print — empty, or whitespace alone — formats to the empty string, not to a newline.
///
/// ```
/// # fn main() -> tsv_svelte::Result<()> {
/// assert_eq!(tsv_svelte::format("<p>{ x }</p>")?, "<p>{x}</p>\n");
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// A parse error, or a refusal of a lone `\r` inside an in-tag `//` comment, where the
/// fold would end the comment early.
/// The one format path, shared by [`format()`] and [`Formatter`]: fold, parse into `arena`,
/// then print into the doc arena `doc_arena` hands over once the parse has succeeded (handed
/// the folded text, so a fresh one is sized to it and a failed parse never builds one).
/// Nothing borrowed from either arena escapes: the result is owned.
pub
/// What [`parse_to_json_with`]'s wire carries. The default is [`parse_to_json`]'s: the
/// span-only wire. Its one option, `locations`, requires the `locations` feature.
///
/// ```
/// # fn main() -> tsv_svelte::Result<()> {
/// # #[cfg(feature = "locations")]
/// # {
/// use tsv_svelte::{JsonOptions, parse_to_json_with};
///
/// let json = parse_to_json_with("<p>x</p>", JsonOptions::new().locations(true))?;
/// assert!(json.contains(r#""loc":"#));
/// assert!(json.contains(r#""name_loc":"#));
/// # }
/// # Ok(())
/// # }
/// ```
// Options are plain data a caller may build once and share across threads; pin that so a
// field added later cannot take it away unnoticed.
const _: = ;
/// Parse `source` and return its wire JSON AST: compact JSON in Svelte's modern `parse()`
/// shape, every node's `start` / `end` a UTF-16 offset and no `loc`.
///
/// The span-only wire every binding ships and `tsv parse` writes by default. Line and
/// column are a pure function of those offsets plus the source, so a consumer holding the
/// source loses nothing; `JsonOptions::locations` (the `locations` feature) adds them. The
/// source is read as written — no line-terminator fold — so the offsets index the caller's
/// own text.
///
/// ```
/// # fn main() -> tsv_svelte::Result<()> {
/// let json = tsv_svelte::parse_to_json("<p>x</p>")?;
/// assert!(json.starts_with(r#"{"css":null,"js":[],"start":0,"end":8,"type":"Root""#));
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// A parse error.
/// [`parse_to_json`] under `options`: whether the wire carries `loc`.
///
/// Each call parses into a fresh arena sized to the source, dropped once the wire is
/// written.
///
/// ```
/// # fn main() -> tsv_svelte::Result<()> {
/// use tsv_svelte::{JsonOptions, parse_to_json, parse_to_json_with};
///
/// // the default options are `parse_to_json`'s
/// assert_eq!(parse_to_json_with("<p>x</p>", JsonOptions::new())?, parse_to_json("<p>x</p>")?);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// A parse error.
/// The wire's bytes as the `String` they are: the writer emits source slices and ASCII
/// fragments alone.
/// Byte spans of the instance/module `<script>` element contents.
///
/// Comments inside these spans belong to the embedded TS programs; comments
/// outside them are template expression comments. The wire writer partitions
/// the root comment list on it.
pub