1#[cfg(feature = "emit")]
11use core::cmp;
12use core::fmt;
13use core::iter;
14#[cfg(feature = "emit")]
15use core::ops::Range;
16use core::slice;
17
18#[cfg(feature = "emit")]
19use std::io;
20#[cfg(feature = "std")]
21use std::path::Path;
22
23use crate as rune;
24#[cfg(feature = "std")]
25use crate::alloc::borrow::Cow;
26use crate::alloc::prelude::*;
27use crate::alloc::{self, Box};
28use crate::ast::Span;
29#[cfg(feature = "emit")]
30use crate::termcolor::{self, WriteColor};
31
32#[derive(Debug)]
34pub struct FromPathError {
35 kind: FromPathErrorKind,
36}
37
38impl From<alloc::Error> for FromPathError {
39 fn from(error: alloc::Error) -> Self {
40 Self {
41 kind: FromPathErrorKind::Alloc(error),
42 }
43 }
44}
45
46#[cfg(feature = "std")]
47impl From<std::io::Error> for FromPathError {
48 fn from(error: std::io::Error) -> Self {
49 Self {
50 kind: FromPathErrorKind::Io(error),
51 }
52 }
53}
54
55impl fmt::Display for FromPathError {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match &self.kind {
58 FromPathErrorKind::Alloc(error) => error.fmt(f),
59 #[cfg(feature = "std")]
60 FromPathErrorKind::Io(error) => error.fmt(f),
61 }
62 }
63}
64
65#[derive(Debug)]
66enum FromPathErrorKind {
67 Alloc(alloc::Error),
68 #[cfg(feature = "std")]
69 Io(std::io::Error),
70}
71
72impl core::error::Error for FromPathError {
73 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
74 match &self.kind {
75 FromPathErrorKind::Alloc(error) => Some(error),
76 #[cfg(feature = "std")]
77 FromPathErrorKind::Io(error) => Some(error),
78 }
79 }
80}
81
82#[derive(Default, TryClone)]
84pub struct Source {
85 name: SourceName,
87 source: Box<str>,
89 #[cfg(feature = "std")]
91 path: Option<Box<Path>>,
92 line_starts: Box<[usize]>,
94}
95
96impl Source {
97 pub fn new(name: impl AsRef<str>, source: impl AsRef<str>) -> alloc::Result<Self> {
99 let name = Box::try_from(name.as_ref())?;
100 let source = source.as_ref();
101 let line_starts = line_starts(source).try_collect::<Box<[_]>>()?;
102
103 Ok(Self {
104 name: SourceName::Name(name),
105 source: source.try_into()?,
106 #[cfg(feature = "std")]
107 path: None,
108 line_starts,
109 })
110 }
111
112 pub fn memory(source: impl AsRef<str>) -> alloc::Result<Self> {
124 let source = source.as_ref();
125 let line_starts = line_starts(source).try_collect::<Box<[_]>>()?;
126
127 Ok(Self {
128 name: SourceName::Memory,
129 source: source.try_into()?,
130 #[cfg(feature = "std")]
131 path: None,
132 line_starts,
133 })
134 }
135
136 #[cfg(feature = "std")]
138 #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
139 pub fn from_path(path: impl AsRef<Path>) -> Result<Self, FromPathError> {
140 let name = Box::try_from(Cow::try_from(path.as_ref().to_string_lossy())?)?;
141 let source = Box::try_from(std::fs::read_to_string(path.as_ref())?)?;
142 let path = Some(path.as_ref().try_into()?);
143 let line_starts = line_starts(source.as_ref()).try_collect::<Box<[_]>>()?;
144
145 Ok(Self {
146 name: SourceName::Name(name),
147 source,
148 path,
149 line_starts,
150 })
151 }
152
153 #[cfg(feature = "std")]
167 #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
168 pub fn with_path(
169 name: impl AsRef<str>,
170 source: impl AsRef<str>,
171 path: impl AsRef<Path>,
172 ) -> alloc::Result<Self> {
173 let name = Box::try_from(name.as_ref())?;
174 let source = Box::try_from(source.as_ref())?;
175 let path = Some(path.as_ref().try_into()?);
176 let line_starts = line_starts(source.as_ref()).try_collect::<Box<[_]>>()?;
177
178 Ok(Self {
179 name: SourceName::Name(name),
180 source,
181 path,
182 line_starts,
183 })
184 }
185
186 pub(crate) fn line_starts(&self) -> &[usize] {
188 &self.line_starts
189 }
190
191 pub fn name(&self) -> &str {
193 match &self.name {
194 SourceName::Memory => "<memory>",
195 SourceName::Name(name) => name,
196 }
197 }
198
199 pub fn is_declaration(&self) -> bool {
219 #[cfg(feature = "std")]
220 if let Some(path) = &self.path {
221 return path
222 .file_name()
223 .and_then(|name| name.to_str())
224 .is_some_and(is_declaration_name);
225 }
226
227 is_declaration_name(self.name())
228 }
229
230 pub(crate) fn get<I>(&self, i: I) -> Option<&I::Output>
232 where
233 I: slice::SliceIndex<str>,
234 {
235 self.source.get(i)
236 }
237
238 pub(crate) fn as_str(&self) -> &str {
240 &self.source
241 }
242
243 #[cfg(feature = "std")]
257 #[cfg_attr(rune_docsrs, doc(cfg(feature = "std")))]
258 pub fn path(&self) -> Option<&Path> {
259 self.path.as_deref()
260 }
261
262 pub fn find_line_column(&self, position: usize) -> (usize, usize) {
269 let (line, offset, rest) = self.position(position);
270 let col = rest.char_indices().take_while(|&(n, _)| n < offset).count();
271 (line, col)
272 }
273
274 pub fn find_utf8_line_column(&self, position: usize) -> (usize, usize) {
280 let (line, offset, _) = self.position(position);
281 (line, offset)
282 }
283
284 pub fn find_utf16cu_line_column(&self, position: usize) -> (usize, usize) {
292 let (line, offset, rest) = self.position(position);
293
294 let col = rest
295 .char_indices()
296 .flat_map(|(n, c)| (n < offset).then(|| c.encode_utf16(&mut [0u16; 2]).len()))
297 .sum();
298
299 (line, col)
300 }
301
302 pub fn source_line(&self, span: Span) -> Option<SourceLine<'_>> {
304 let (line, column, text, _span) = line_for(self, span)?;
305
306 Some(SourceLine {
307 #[cfg(feature = "emit")]
308 name: self.name(),
309 line,
310 column,
311 text,
312 #[cfg(feature = "emit")]
313 span: _span,
314 })
315 }
316
317 #[cfg(feature = "emit")]
319 pub(crate) fn line_index(&self, byte_index: usize) -> usize {
320 self.line_starts
321 .binary_search(&byte_index)
322 .unwrap_or_else(|next_line| next_line.saturating_sub(1))
323 }
324
325 #[cfg(feature = "emit")]
327 pub(crate) fn line_range(&self, line_index: usize) -> Option<Range<usize>> {
328 let line_start = self.line_start(line_index)?;
329 let next_line_start = self.line_start(line_index.saturating_add(1))?;
330 Some(line_start..next_line_start)
331 }
332
333 #[cfg(feature = "emit")]
335 pub(crate) fn line_count(&self) -> usize {
336 self.line_starts.len()
337 }
338
339 #[cfg(feature = "emit")]
341 pub(crate) fn line(&self, span: Span) -> Option<(usize, usize, [&str; 3])> {
342 let from = span.range();
343 let (lin, col) = self.find_line_column(from.start);
344 let line = self.line_range(lin)?;
345
346 let start = from.start.checked_sub(line.start)?;
347 let end = from.end.checked_sub(line.start)?;
348
349 let text = self.source.get(line)?;
350 let prefix = text.get(..start)?;
351 let mid = text.get(start..end)?;
352 let suffix = text.get(end..)?;
353
354 Some((lin, col, [prefix, mid, suffix]))
355 }
356
357 fn position(&self, offset: usize) -> (usize, usize, &str) {
358 if offset == 0 {
359 return Default::default();
360 }
361
362 let line = match self.line_starts.binary_search(&offset) {
363 Ok(exact) => exact,
364 Err(0) => return Default::default(),
365 Err(n) => n - 1,
366 };
367
368 let line_start = self.line_starts[line];
369
370 let rest = &self.source[line_start..];
371 let offset = offset.saturating_sub(line_start);
372 (line, offset, rest)
373 }
374
375 #[cfg(feature = "emit")]
376 fn line_start(&self, line_index: usize) -> Option<usize> {
377 match line_index.cmp(&self.line_starts.len()) {
378 cmp::Ordering::Less => self.line_starts.get(line_index).copied(),
379 cmp::Ordering::Equal => Some(self.source.as_ref().len()),
380 cmp::Ordering::Greater => None,
381 }
382 }
383
384 #[cfg(feature = "workspace")]
385 pub(crate) fn len(&self) -> usize {
386 self.source.len()
387 }
388}
389
390impl fmt::Debug for Source {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 let mut st = f.debug_struct("Source");
393 st.field("name", &self.name);
394 #[cfg(feature = "std")]
395 st.field("path", &self.path);
396 st.finish()
397 }
398}
399
400pub struct SourceLine<'a> {
402 #[cfg(feature = "emit")]
403 name: &'a str,
404 pub line: usize,
406 pub column: usize,
408 pub text: &'a str,
410 #[cfg(feature = "emit")]
411 span: Span,
412}
413
414impl SourceLine<'_> {
415 #[cfg(feature = "emit")]
417 pub(crate) fn write(&self, o: &mut dyn WriteColor) -> io::Result<()> {
418 let mut highlight = termcolor::ColorSpec::new();
419 highlight.set_fg(Some(termcolor::Color::Yellow));
420
421 let mut new_line = termcolor::ColorSpec::new();
422 new_line.set_fg(Some(termcolor::Color::Red));
423
424 let text = self.text.trim_end();
425 let end = self.span.end.into_usize().min(text.len());
426
427 let before = &text[0..self.span.start.into_usize()].trim_start();
428 let inner = &text[self.span.start.into_usize()..end];
429 let after = &text[end..];
430
431 {
432 let name = self.name;
433 let line = self.line + 1;
434 let start = self.column + 1;
435 let end = start + inner.chars().count();
436 write!(o, "{name}:{line}:{start}-{end}: ")?;
437 }
438
439 write!(o, "{before}")?;
440 o.set_color(&highlight)?;
441 write!(o, "{inner}")?;
442 o.reset()?;
443 write!(o, "{after}")?;
444
445 if self.span.end != end {
446 o.set_color(&new_line)?;
447 write!(o, "\\n")?;
448 o.reset()?;
449 }
450
451 Ok(())
452 }
453}
454
455#[derive(Default, Debug, TryClone, PartialEq, Eq)]
457enum SourceName {
458 #[default]
461 Memory,
462 Name(Box<str>),
464}
465
466#[inline(always)]
467fn line_starts(source: &str) -> impl Iterator<Item = usize> + '_ {
468 iter::once(0).chain(source.match_indices('\n').map(|(i, _)| i + 1))
469}
470
471fn line_for(source: &Source, span: Span) -> Option<(usize, usize, &str, Span)> {
473 let line_starts = source.line_starts();
474
475 let line = match line_starts.binary_search(&span.start.into_usize()) {
476 Ok(n) => n,
477 Err(n) => n.saturating_sub(1),
478 };
479
480 let start = *line_starts.get(line)?;
481 let end = line.checked_add(1)?;
482
483 let s = if let Some(end) = line_starts.get(end) {
484 source.get(start..*end)?
485 } else {
486 source.get(start..)?
487 };
488
489 let line_end = span.start.into_usize().saturating_sub(start);
490
491 let column = s
492 .get(..line_end)
493 .into_iter()
494 .flat_map(|s| s.chars())
495 .count();
496
497 let start = start.try_into().unwrap();
498
499 Some((
500 line,
501 column,
502 s,
503 Span::new(
504 span.start.saturating_sub(start),
505 span.end.saturating_sub(start),
506 ),
507 ))
508}
509
510pub(crate) fn is_declaration_name(name: &str) -> bool {
512 name.ends_with(".d.rn")
513}