compiler_base_span/
lib.rs

1//! Source positions and related helper functions.
2//!
3//! Important concepts in this module include:
4//!
5//! - the *span*, represented by [`Span`] and related types;
6//! - interned strings, represented by [`Symbol`]s, with some common symbols available statically in the [`sym`] module.
7//!
8//! Reference: https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/lib.rs
9
10pub mod span;
11pub use rustc_span::fatal_error;
12pub use span::{BytePos, Span, SpanData, DUMMY_SP};
13
14pub type SourceMap = rustc_span::SourceMap;
15pub type SourceFile = rustc_span::SourceFile;
16pub type FilePathMapping = rustc_span::source_map::FilePathMapping;
17pub type Loc = rustc_span::Loc;
18
19/// Get the filename from `SourceMap` by `Span`.
20///
21/// # Examples
22///
23/// ```rust
24/// # use compiler_base_span::{span_to_filename_string, span::new_byte_pos, FilePathMapping, SourceMap};
25/// # use rustc_span::SpanData;
26/// # use std::path::PathBuf;
27/// # use std::fs;
28///
29/// // 1. You need to hold a `SourceMap` at first.
30/// let filename = fs::canonicalize(&PathBuf::from("./src/test_datas/code_snippet")).unwrap().display().to_string();
31/// let src = std::fs::read_to_string(filename.clone()).unwrap();
32/// let sm = SourceMap::new(FilePathMapping::empty());
33/// sm.new_source_file(PathBuf::from(filename.clone()).into(), src.to_string());
34///
35/// // 2. You got the span in `SourceMap`.
36/// let code_span = SpanData {
37///     lo: new_byte_pos(21),
38///     hi: new_byte_pos(22),
39/// }.span();
40///
41/// // 3. You can got the filename by `span_to_filename_string()`.
42/// assert_eq!(filename, span_to_filename_string(&code_span, &sm));
43/// ```
44#[inline]
45pub fn span_to_filename_string(span: &Span, sm: &SourceMap) -> String {
46    format!("{}", sm.span_to_filename(*span).prefer_remapped())
47}