Skip to main content

rune/
source.rs

1//! Module for dealing with sources.
2//!
3//! The primary type in here is the [`Source`] struct, which holds onto all
4//! metadata necessary related to a source in order to build it.
5//!
6//! Sources are stored in the [`Sources`] collection.
7//!
8//! [`Sources`]: crate::sources::Sources
9
10#[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/// Error raised when constructing a source.
33#[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/// A single source file.
83#[derive(Default, TryClone)]
84pub struct Source {
85    /// The name of the source.
86    name: SourceName,
87    /// The source string.
88    source: Box<str>,
89    /// The path the source was loaded from.
90    #[cfg(feature = "std")]
91    path: Option<Box<Path>>,
92    /// The starting byte indices in the source code.
93    line_starts: Box<[usize]>,
94}
95
96impl Source {
97    /// Construct a new source with the given name.
98    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    /// Construct a new anonymously named `<memory>` source.
113    ///
114    /// # Examples
115    ///
116    /// ```
117    /// use rune::Source;
118    ///
119    /// let source = Source::memory("pub fn main() { 42 }")?;
120    /// assert_eq!(source.name(), "<memory>");
121    /// # Ok::<_, rune::support::Error>(())
122    /// ```
123    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    /// Read and load a source from the given filesystem path.
137    #[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    /// Construct a new source with the given content and path.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use std::path::Path;
159    /// use rune::Source;
160    ///
161    /// let source = Source::with_path("test", "pub fn main() { 42 }", "test.rn")?;
162    /// assert_eq!(source.name(), "test");
163    /// assert_eq!(source.path(), Some(Path::new("test.rn")));
164    /// # Ok::<_, rune::support::Error>(())
165    /// ```
166    #[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    /// Access all line starts in the source.
187    pub(crate) fn line_starts(&self) -> &[usize] {
188        &self.line_starts
189    }
190
191    /// Get the name of the source.
192    pub fn name(&self) -> &str {
193        match &self.name {
194            SourceName::Memory => "<memory>",
195            SourceName::Name(name) => name,
196        }
197    }
198
199    /// Test if this is a declaration source.
200    ///
201    /// A declaration source is one whose path, or failing that whose name,
202    /// ends in `.d.rn`. It holds only signatures, type definitions and their
203    /// documentation, the way a host describes what it provides natively, and
204    /// none of what is declared in it is compiled into a unit.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// use rune::Source;
210    ///
211    /// let source = Source::new("host.d.rn", "fn hello(value: u64) -> u64;")?;
212    /// assert!(source.is_declaration());
213    ///
214    /// let source = Source::new("host.rn", "fn hello(value) { value }")?;
215    /// assert!(!source.is_declaration());
216    /// # Ok::<_, rune::support::Error>(())
217    /// ```
218    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    ///  et the given range from the source.
231    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    /// Access the underlying string for the source.
239    pub(crate) fn as_str(&self) -> &str {
240        &self.source
241    }
242
243    /// Get the path associated with the source.
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// use std::path::Path;
249    /// use rune::Source;
250    ///
251    /// let source = Source::with_path("test", "pub fn main() { 42 }", "test.rn")?;
252    /// assert_eq!(source.name(), "test");
253    /// assert_eq!(source.path(), Some(Path::new("test.rn")));
254    /// # Ok::<_, rune::support::Error>(())
255    /// ```
256    #[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    /// Convert the given position to a utf-8 line position in code units.
263    ///
264    /// A position is a character offset into the source in utf-8 characters.
265    ///
266    /// Note that utf-8 code units is what you'd count when using the
267    /// [`str::chars()`] iterator.
268    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    /// Convert the given position to a line and the number of bytes into that
275    /// line.
276    ///
277    /// This is what the language server protocol counts when it has been told
278    /// to use `utf-8` positions: a character there is a byte, not a character.
279    pub fn find_utf8_line_column(&self, position: usize) -> (usize, usize) {
280        let (line, offset, _) = self.position(position);
281        (line, offset)
282    }
283
284    /// Convert the given position to a utf-16 code units line and character.
285    ///
286    /// A position is a character offset into the source in utf-16 characters.
287    ///
288    /// Note that utf-16 code units is what you'd count when iterating over the
289    /// string in terms of characters as-if they would have been encoded with
290    /// [`char::encode_utf16()`].
291    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    /// Fetch [`SourceLine`] information for the given span.
303    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    /// Get the line index for the given byte.
318    #[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    /// Get the range corresponding to the given line index.
326    #[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    /// Get the number of lines in the source.
334    #[cfg(feature = "emit")]
335    pub(crate) fn line_count(&self) -> usize {
336        self.line_starts.len()
337    }
338
339    /// Access the line number of content that starts with the given span.
340    #[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
400/// An extracted source line.
401pub struct SourceLine<'a> {
402    #[cfg(feature = "emit")]
403    name: &'a str,
404    /// The line number in the source.
405    pub line: usize,
406    /// The column number in the source.
407    pub column: usize,
408    /// The text of the span.
409    pub text: &'a str,
410    #[cfg(feature = "emit")]
411    span: Span,
412}
413
414impl SourceLine<'_> {
415    /// Pretty write a source line to the given output.
416    #[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/// Holder for the name of a source.
456#[derive(Default, Debug, TryClone, PartialEq, Eq)]
457enum SourceName {
458    /// An in-memory source, will use `<memory>` when the source is being
459    /// referred to in diagnostics.
460    #[default]
461    Memory,
462    /// A named source.
463    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
471/// Get the line number and source line for the given source and span.
472fn 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
510/// Test if a file name is that of a declaration source.
511pub(crate) fn is_declaration_name(name: &str) -> bool {
512    name.ends_with(".d.rn")
513}