1use std::borrow::Cow;
25use std::fmt;
26use std::ops::Range;
27
28mod render;
29
30pub use render::RenderOptions;
31
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
38pub struct Span {
39 pub start: u32,
40 pub end: u32,
41}
42
43impl Span {
44 pub const MAX_INPUT: usize = u32::MAX as usize;
46
47 pub const fn new(start: u32, end: u32) -> Span {
48 debug_assert!(start <= end);
49 Span { start, end }
50 }
51
52 pub const fn at(offset: u32) -> Span {
54 Span {
55 start: offset,
56 end: offset,
57 }
58 }
59
60 pub const fn len(self) -> u32 {
61 self.end - self.start
62 }
63
64 pub const fn is_empty(self) -> bool {
65 self.start == self.end
66 }
67
68 pub const fn contains(self, offset: u32) -> bool {
70 self.start <= offset && offset < self.end
71 }
72
73 pub fn to(self, other: Span) -> Span {
75 Span {
76 start: self.start.min(other.start),
77 end: self.end.max(other.end),
78 }
79 }
80
81 pub const fn range(self) -> Range<usize> {
82 self.start as usize..self.end as usize
83 }
84
85 pub fn text(self, src: &str) -> &str {
88 src.get(self.range()).unwrap_or("")
89 }
90}
91
92impl From<Span> for Range<usize> {
93 fn from(s: Span) -> Range<usize> {
94 s.range()
95 }
96}
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
100pub struct LineCol {
101 pub line: u32,
102 pub column: u32,
103}
104
105impl From<(u32, u32)> for LineCol {
106 fn from((line, column): (u32, u32)) -> LineCol {
107 LineCol { line, column }
108 }
109}
110
111impl fmt::Display for LineCol {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 write!(f, "{}:{}", self.line, self.column)
114 }
115}
116
117const BLOCK: usize = 1024;
120
121#[derive(Clone, Debug)]
128pub struct LineIndex<'a> {
129 src: Cow<'a, str>,
130 starts: Vec<u32>,
132 chars: Vec<u32>,
134 utf16: Vec<u32>,
135}
136
137impl<'a> LineIndex<'a> {
138 pub fn new(src: &'a str) -> LineIndex<'a> {
140 LineIndex::build(Cow::Borrowed(src), false)
141 }
142
143 pub fn owned(src: String) -> LineIndex<'static> {
151 LineIndex::build(Cow::Owned(src), false)
152 }
153
154 pub fn ecmascript(src: &'a str) -> LineIndex<'a> {
157 LineIndex::build(Cow::Borrowed(src), true)
158 }
159
160 fn build(src: Cow<'a, str>, separators: bool) -> LineIndex<'a> {
161 assert!(
162 src.len() <= Span::MAX_INPUT,
163 "LineIndex takes at most 4 GiB"
164 );
165 let b = src.as_bytes();
166 let mut starts = vec![0];
167 let mut i = 0;
168 while i < b.len() {
169 match b[i] {
170 b'\n' => starts.push(i as u32 + 1),
171 b'\r' if b.get(i + 1) != Some(&b'\n') => starts.push(i as u32 + 1),
172 0xE2 if separators
174 && b.get(i + 1) == Some(&0x80)
175 && matches!(b.get(i + 2), Some(0xA8 | 0xA9)) =>
176 {
177 starts.push(i as u32 + 3);
178 i += 2;
179 }
180 _ => {}
181 }
182 i += 1;
183 }
184 let (mut chars, mut utf16) = (Vec::new(), Vec::new());
185 let (mut c, mut u) = (0, 0);
186 for block in b.chunks(BLOCK) {
187 chars.push(c);
188 utf16.push(u);
189 let (bc, bu) = count(block);
190 c += bc;
191 u += bu;
192 }
193 chars.push(c);
194 utf16.push(u);
195 LineIndex {
196 src,
197 starts,
198 chars,
199 utf16,
200 }
201 }
202
203 pub fn line_count(&self) -> u32 {
204 self.starts.len() as u32
205 }
206
207 pub fn line_start(&self, line: u32) -> Option<u32> {
209 self.starts.get(line.checked_sub(1)? as usize).copied()
210 }
211
212 pub fn line(&self, offset: u32) -> u32 {
215 self.starts.partition_point(|&s| s <= offset) as u32
216 }
217
218 pub fn line_col(&self, offset: u32) -> LineCol {
221 let line = self.line(offset);
222 let start = self.starts[line as usize - 1];
223 let column = 1 + self.before(offset).0 - self.before(start).0;
224 LineCol { line, column }
225 }
226
227 pub fn line_col_utf16(&self, offset: u32) -> LineCol {
230 let line = self.line(offset);
231 let start = self.starts[line as usize - 1];
232 let column = 1 + self.before(offset).1 - self.before(start).1;
233 LineCol { line, column }
234 }
235
236 pub fn utf16_offset(&self, offset: u32) -> u32 {
239 self.before(offset).1
240 }
241
242 pub fn char_offset(&self, offset: u32) -> u32 {
246 self.before(offset).0
247 }
248
249 fn before(&self, offset: u32) -> (u32, u32) {
251 let at = (offset as usize).min(self.src.len());
252 let block = at / BLOCK;
253 let (c, u) = count(&self.src.as_bytes()[block * BLOCK..at]);
254 (self.chars[block] + c, self.utf16[block] + u)
255 }
256}
257
258fn count(bytes: &[u8]) -> (u32, u32) {
262 let (mut c, mut u) = (0, 0);
263 for &b in bytes {
264 if b & 0xC0 != 0x80 {
265 c += 1;
266 u += 1 + u32::from(b >= 0xF0);
267 }
268 }
269 (c, u)
270}
271
272#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
274pub enum Severity {
275 Error,
278 Warning,
281}
282
283impl fmt::Display for Severity {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.write_str(match self {
286 Severity::Error => "error",
287 Severity::Warning => "warning",
288 })
289 }
290}
291
292#[derive(Clone, Debug, PartialEq, Eq, Hash)]
294pub struct Label {
295 pub span: Span,
296 pub message: Cow<'static, str>,
297}
298
299#[derive(Clone, Debug, PartialEq, Eq, Hash)]
304pub struct Diagnostic {
305 pub code: &'static str,
306 pub severity: Severity,
307 pub span: Span,
308 pub message: Cow<'static, str>,
309 pub labels: Vec<Label>,
310}
311
312impl Diagnostic {
313 pub fn new(
314 code: &'static str,
315 severity: Severity,
316 span: Span,
317 message: impl Into<Cow<'static, str>>,
318 ) -> Diagnostic {
319 Diagnostic {
320 code,
321 severity,
322 span,
323 message: message.into(),
324 labels: Vec::new(),
325 }
326 }
327
328 pub fn error(
329 code: &'static str,
330 span: Span,
331 message: impl Into<Cow<'static, str>>,
332 ) -> Diagnostic {
333 Diagnostic::new(code, Severity::Error, span, message)
334 }
335
336 pub fn warning(
337 code: &'static str,
338 span: Span,
339 message: impl Into<Cow<'static, str>>,
340 ) -> Diagnostic {
341 Diagnostic::new(code, Severity::Warning, span, message)
342 }
343
344 pub fn with_label(mut self, span: Span, message: impl Into<Cow<'static, str>>) -> Diagnostic {
346 self.labels.push(Label {
347 span,
348 message: message.into(),
349 });
350 self
351 }
352
353 pub fn is_error(&self) -> bool {
354 self.severity == Severity::Error
355 }
356}
357
358impl fmt::Display for Diagnostic {
359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 write!(
362 f,
363 "{}[{}] at {}..{}: {}",
364 self.severity, self.code, self.span.start, self.span.end, self.message
365 )
366 }
367}
368
369impl std::error::Error for Diagnostic {}
370
371#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
380pub struct Limits {
381 pub max_input: Option<usize>,
384 pub max_depth: Option<u32>,
386 pub max_steps: Option<u64>,
388}
389
390impl Limits {
391 pub fn check_input(&self, len: usize) -> Result<(), Diagnostic> {
394 let max = self.max_input.unwrap_or(usize::MAX).min(Span::MAX_INPUT);
395 if len <= max {
396 return Ok(());
397 }
398 Err(Diagnostic::error(
399 "input-too-large",
400 Span::at(0),
401 format!("the input is {len} bytes, and the limit is {max}"),
402 ))
403 }
404
405 pub fn too_deep(&self, depth: u32) -> bool {
407 self.max_depth.is_some_and(|max| depth > max)
408 }
409
410 pub fn budget(&self) -> Budget {
412 Budget {
413 left: self.max_steps,
414 }
415 }
416}
417
418#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
422pub struct Budget {
423 left: Option<u64>,
424}
425
426impl Budget {
427 pub const fn new(steps: u64) -> Budget {
428 Budget { left: Some(steps) }
429 }
430
431 pub const fn unlimited() -> Budget {
432 Budget { left: None }
433 }
434
435 pub fn spend(&mut self, steps: u64) -> Result<(), Exhausted> {
437 match &mut self.left {
438 None => Ok(()),
439 Some(left) if *left >= steps => {
440 *left -= steps;
441 Ok(())
442 }
443 Some(_) => Err(Exhausted),
444 }
445 }
446
447 pub const fn left(&self) -> Option<u64> {
449 self.left
450 }
451}
452
453#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
455pub struct Exhausted;
456
457impl fmt::Display for Exhausted {
458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459 f.write_str("the step budget ran out")
460 }
461}
462
463impl std::error::Error for Exhausted {}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 #[test]
470 fn span_basics() {
471 let s = Span::new(2, 5);
472 assert_eq!((s.len(), s.is_empty()), (3, false));
473 assert!(s.contains(2) && s.contains(4) && !s.contains(5));
474 assert!(Span::at(7).is_empty());
475 assert_eq!(s.to(Span::new(8, 9)), Span::new(2, 9));
476 assert_eq!(Span::new(8, 9).to(s), Span::new(2, 9));
477 assert_eq!(Range::<usize>::from(s), 2..5);
478 assert_eq!(s.text("abcdefg"), "cde");
479 assert_eq!(Span::new(1, 2).text("é"), "");
481 assert_eq!(Span::new(1, 20).text("abc"), "");
482 assert_eq!(std::mem::size_of::<Span>(), 8);
483 }
484
485 fn slow(src: &str, separators: bool, offset: usize) -> (u32, u32, u32, u32) {
487 let (mut line, mut col, mut col16, mut off16) = (1, 1, 1, 0);
488 let mut chars = src.char_indices().peekable();
489 while let Some((i, c)) = chars.next() {
490 if i >= offset {
491 break;
492 }
493 off16 += c.len_utf16() as u32;
494 let crlf = c == '\r' && chars.peek().is_some_and(|&(_, n)| n == '\n');
495 if (c == '\n'
496 || c == '\r' && !crlf
497 || separators && matches!(c, '\u{2028}' | '\u{2029}'))
498 && i + c.len_utf8() <= offset
499 {
500 line += 1;
501 col = 1;
502 col16 = 1;
503 } else {
504 col += 1;
505 col16 += c.len_utf16() as u32;
506 }
507 }
508 (line, col, col16, off16)
509 }
510
511 #[test]
512 fn line_col_agrees_with_counting() {
513 let src = "a\r\nb\rc\nd\u{2028}e\u{2029}é€😀\n".repeat(40) + &"😀x".repeat(700) + "\r\nend";
516 for separators in [false, true] {
517 let index = if separators {
518 LineIndex::ecmascript(&src)
519 } else {
520 LineIndex::new(&src)
521 };
522 for (offset, _) in src.char_indices().chain([(src.len(), ' ')]) {
523 let (line, col, col16, off16) = slow(&src, separators, offset);
524 let o = offset as u32;
525 assert_eq!(
526 index.line_col(o),
527 (line, col).into(),
528 "{offset} {separators}"
529 );
530 assert_eq!(index.line_col_utf16(o), (line, col16).into(), "{offset}");
531 assert_eq!(index.utf16_offset(o), off16, "{offset}");
532 }
533 }
534 }
535
536 #[test]
537 fn line_starts() {
538 let index = LineIndex::new("ab\r\ncd\ref\n");
539 assert_eq!(index.line_count(), 4);
540 assert_eq!(index.line_start(1), Some(0));
541 assert_eq!(index.line_start(2), Some(4));
542 assert_eq!(index.line_start(3), Some(7));
543 assert_eq!(index.line_start(4), Some(10));
544 assert_eq!((index.line_start(0), index.line_start(5)), (None, None));
545 assert_eq!((index.line(2), index.line(3), index.line(4)), (1, 1, 2));
547 assert_eq!(index.line(1000), 4);
549 assert_eq!(LineIndex::new("a\u{2028}b").line_count(), 1);
551 assert_eq!(LineIndex::ecmascript("a\u{2028}b").line_count(), 2);
552 assert_eq!(LineIndex::new("").line_col(0), (1, 1).into());
553 }
554
555 #[test]
556 fn diagnostics() {
557 let d = Diagnostic::error("bad-thing", Span::new(3, 4), "a bad thing")
558 .with_label(Span::new(0, 1), "started here");
559 assert!(d.is_error());
560 assert_eq!(d.labels[0].message, "started here");
561 assert_eq!(d.to_string(), "error[bad-thing] at 3..4: a bad thing");
562 let w = Diagnostic::warning("odd", Span::at(0), String::from("odd"));
563 assert_eq!(
564 (w.is_error(), w.severity.to_string()),
565 (false, "warning".into())
566 );
567 assert!(Severity::Error < Severity::Warning);
568 }
569
570 #[test]
571 fn limits_and_budget() {
572 let none = Limits::default();
573 assert!(none.check_input(1 << 30).is_ok());
574 assert!(none.check_input(Span::MAX_INPUT + 1).is_err());
575 assert!(!none.too_deep(u32::MAX));
576 let l = Limits {
577 max_input: Some(10),
578 max_depth: Some(2),
579 max_steps: Some(5),
580 };
581 assert!(l.check_input(10).is_ok());
582 assert_eq!(l.check_input(11).unwrap_err().code, "input-too-large");
583 assert!(!l.too_deep(2) && l.too_deep(3));
584 let mut b = l.budget();
585 assert_eq!(b.spend(3), Ok(()));
586 assert_eq!(b.spend(3), Err(Exhausted));
587 assert_eq!(b.left(), Some(2));
588 assert_eq!(b.spend(2), Ok(()));
589 assert_eq!(b.spend(1), Err(Exhausted));
590 let mut u = Budget::unlimited();
591 assert_eq!((u.spend(u64::MAX), u.left()), (Ok(()), None));
592 assert_eq!(Budget::new(1).left(), Some(1));
593 }
594}