]>
Commit | Line | Data |
---|---|---|
5869c6ff XL |
1 | //! Source positions and related helper functions. |
2 | //! | |
3 | //! Important concepts in this module include: | |
4 | //! | |
5 | //! - the *span*, represented by [`SpanData`] and related types; | |
6 | //! - source code as represented by a [`SourceMap`]; and | |
7 | //! - interned strings, represented by [`Symbol`]s, with some common symbols available statically in the [`sym`] module. | |
8 | //! | |
9 | //! Unlike most compilers, the span contains not only the position in the source code, but also various other metadata, | |
10 | //! such as the edition and macro hygiene. This metadata is stored in [`SyntaxContext`] and [`ExpnData`]. | |
3157f602 | 11 | //! |
0731742a | 12 | //! ## Note |
3157f602 XL |
13 | //! |
14 | //! This API is completely unstable and subject to change. | |
15 | ||
1b1a35ee XL |
16 | #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] |
17 | #![feature(array_windows)] | |
5e7ed085 | 18 | #![feature(let_else)] |
94222f64 | 19 | #![feature(if_let_guard)] |
f9f354fc | 20 | #![feature(negative_impls)] |
f9f354fc | 21 | #![feature(min_specialization)] |
5e7ed085 FG |
22 | #![feature(rustc_attrs)] |
23 | #![allow(rustc::potential_query_instability)] | |
f9f354fc | 24 | |
3dfed10e | 25 | #[macro_use] |
f9f354fc | 26 | extern crate rustc_macros; |
3157f602 | 27 | |
c295e0f8 XL |
28 | #[macro_use] |
29 | extern crate tracing; | |
30 | ||
dfeec247 | 31 | use rustc_data_structures::AtomicRef; |
60c5eb7d | 32 | use rustc_macros::HashStable_Generic; |
dfeec247 | 33 | use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; |
60c5eb7d | 34 | |
60c5eb7d | 35 | mod caching_source_map_view; |
dfeec247 | 36 | pub mod source_map; |
60c5eb7d | 37 | pub use self::caching_source_map_view::CachingSourceMapView; |
f035d41b | 38 | use source_map::SourceMap; |
3157f602 | 39 | |
94b46f34 | 40 | pub mod edition; |
dc9dc135 | 41 | use edition::Edition; |
cc61c64b | 42 | pub mod hygiene; |
e1599b0c | 43 | use hygiene::Transparency; |
3c0e092e | 44 | pub use hygiene::{DesugaringKind, ExpnKind, MacroKind}; |
136023e0 | 45 | pub use hygiene::{ExpnData, ExpnHash, ExpnId, LocalExpnId, SyntaxContext}; |
5099ac24 | 46 | use rustc_data_structures::stable_hasher::HashingControls; |
74b04a01 | 47 | pub mod def_id; |
c295e0f8 | 48 | use def_id::{CrateNum, DefId, DefPathHash, LocalDefId, LOCAL_CRATE}; |
fc512014 | 49 | pub mod lev_distance; |
ea8adc8c XL |
50 | mod span_encoding; |
51 | pub use span_encoding::{Span, DUMMY_SP}; | |
52 | ||
cc61c64b | 53 | pub mod symbol; |
dfeec247 | 54 | pub use symbol::{sym, Symbol}; |
cc61c64b | 55 | |
b7449926 | 56 | mod analyze_source_file; |
60c5eb7d | 57 | pub mod fatal_error; |
8faf50e0 | 58 | |
04454e1e FG |
59 | pub mod profiling; |
60 | ||
dfeec247 XL |
61 | use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; |
62 | use rustc_data_structures::sync::{Lock, Lrc}; | |
0731742a XL |
63 | |
64 | use std::borrow::Cow; | |
0731742a XL |
65 | use std::cmp::{self, Ordering}; |
66 | use std::fmt; | |
ba9703b0 | 67 | use std::hash::Hash; |
29967ef6 | 68 | use std::ops::{Add, Range, Sub}; |
ba9703b0 XL |
69 | use std::path::{Path, PathBuf}; |
70 | use std::str::FromStr; | |
04454e1e | 71 | use std::sync::Arc; |
ba9703b0 | 72 | |
5099ac24 | 73 | use md5::Digest; |
ba9703b0 | 74 | use md5::Md5; |
ba9703b0 | 75 | use sha1::Sha1; |
29967ef6 XL |
76 | use sha2::Sha256; |
77 | ||
78 | use tracing::debug; | |
0731742a | 79 | |
416331ca XL |
80 | #[cfg(test)] |
81 | mod tests; | |
82 | ||
f035d41b XL |
83 | // Per-session global variables: this struct is stored in thread-local storage |
84 | // in such a way that it is accessible without any kind of handle to all | |
85 | // threads within the compilation session, but is not accessible outside the | |
86 | // session. | |
87 | pub struct SessionGlobals { | |
c295e0f8 | 88 | symbol_interner: symbol::Interner, |
0531ce1d XL |
89 | span_interner: Lock<span_encoding::SpanInterner>, |
90 | hygiene_data: Lock<hygiene::HygieneData>, | |
f035d41b | 91 | source_map: Lock<Option<Lrc<SourceMap>>>, |
0531ce1d XL |
92 | } |
93 | ||
f035d41b XL |
94 | impl SessionGlobals { |
95 | pub fn new(edition: Edition) -> SessionGlobals { | |
96 | SessionGlobals { | |
c295e0f8 | 97 | symbol_interner: symbol::Interner::fresh(), |
0531ce1d | 98 | span_interner: Lock::new(span_encoding::SpanInterner::default()), |
416331ca | 99 | hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), |
f035d41b | 100 | source_map: Lock::new(None), |
0531ce1d XL |
101 | } |
102 | } | |
103 | } | |
104 | ||
136023e0 XL |
105 | #[inline] |
106 | pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R { | |
107 | assert!( | |
108 | !SESSION_GLOBALS.is_set(), | |
109 | "SESSION_GLOBALS should never be overwritten! \ | |
110 | Use another thread if you need another SessionGlobals" | |
111 | ); | |
3dfed10e XL |
112 | let session_globals = SessionGlobals::new(edition); |
113 | SESSION_GLOBALS.set(&session_globals, f) | |
114 | } | |
115 | ||
136023e0 XL |
116 | #[inline] |
117 | pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { | |
118 | assert!( | |
119 | !SESSION_GLOBALS.is_set(), | |
120 | "SESSION_GLOBALS should never be overwritten! \ | |
121 | Use another thread if you need another SessionGlobals" | |
122 | ); | |
123 | SESSION_GLOBALS.set(session_globals, f) | |
124 | } | |
125 | ||
126 | #[inline] | |
127 | pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R | |
128 | where | |
129 | F: FnOnce(&SessionGlobals) -> R, | |
130 | { | |
131 | create_session_if_not_set_then(edition::DEFAULT_EDITION, f) | |
132 | } | |
133 | ||
134 | #[inline] | |
135 | pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R | |
136 | where | |
137 | F: FnOnce(&SessionGlobals) -> R, | |
138 | { | |
139 | if !SESSION_GLOBALS.is_set() { | |
140 | let session_globals = SessionGlobals::new(edition); | |
141 | SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) | |
142 | } else { | |
143 | SESSION_GLOBALS.with(f) | |
144 | } | |
145 | } | |
146 | ||
147 | #[inline] | |
148 | pub fn with_session_globals<R, F>(f: F) -> R | |
149 | where | |
150 | F: FnOnce(&SessionGlobals) -> R, | |
151 | { | |
152 | SESSION_GLOBALS.with(f) | |
153 | } | |
154 | ||
155 | #[inline] | |
156 | pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R { | |
157 | create_session_globals_then(edition::DEFAULT_EDITION, f) | |
3dfed10e XL |
158 | } |
159 | ||
160 | // If this ever becomes non thread-local, `decode_syntax_context` | |
161 | // and `decode_expn_id` will need to be updated to handle concurrent | |
162 | // deserialization. | |
136023e0 | 163 | scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); |
0531ce1d | 164 | |
ba9703b0 XL |
165 | // FIXME: We should use this enum or something like it to get rid of the |
166 | // use of magic `/rust/1.x/...` paths across the board. | |
17df50a5 | 167 | #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] |
94222f64 | 168 | #[derive(Decodable)] |
ba9703b0 | 169 | pub enum RealFileName { |
17df50a5 XL |
170 | LocalPath(PathBuf), |
171 | /// For remapped paths (namely paths into libstd that have been mapped | |
172 | /// to the appropriate spot on the local host's file system, and local file | |
173 | /// system paths that have been remapped with `FilePathMapping`), | |
174 | Remapped { | |
175 | /// `local_path` is the (host-dependent) local path to the file. This is | |
176 | /// None if the file was imported from another crate | |
177 | local_path: Option<PathBuf>, | |
ba9703b0 XL |
178 | /// `virtual_name` is the stable path rustc will store internally within |
179 | /// build artifacts. | |
180 | virtual_name: PathBuf, | |
181 | }, | |
182 | } | |
183 | ||
17df50a5 XL |
184 | impl Hash for RealFileName { |
185 | fn hash<H: std::hash::Hasher>(&self, state: &mut H) { | |
186 | // To prevent #70924 from happening again we should only hash the | |
187 | // remapped (virtualized) path if that exists. This is because | |
188 | // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) | |
189 | // remain stable even if the corresponding local_path changes | |
190 | self.remapped_path_if_available().hash(state) | |
191 | } | |
192 | } | |
193 | ||
194 | // This is functionally identical to #[derive(Encodable)], with the exception of | |
195 | // an added assert statement | |
196 | impl<S: Encoder> Encodable<S> for RealFileName { | |
923072b8 FG |
197 | fn encode(&self, encoder: &mut S) { |
198 | match *self { | |
199 | RealFileName::LocalPath(ref local_path) => encoder.emit_enum_variant(0, |encoder| { | |
200 | local_path.encode(encoder); | |
201 | }), | |
17df50a5 XL |
202 | |
203 | RealFileName::Remapped { ref local_path, ref virtual_name } => encoder | |
923072b8 | 204 | .emit_enum_variant(1, |encoder| { |
17df50a5 XL |
205 | // For privacy and build reproducibility, we must not embed host-dependant path in artifacts |
206 | // if they have been remapped by --remap-path-prefix | |
207 | assert!(local_path.is_none()); | |
923072b8 FG |
208 | local_path.encode(encoder); |
209 | virtual_name.encode(encoder); | |
17df50a5 | 210 | }), |
923072b8 | 211 | } |
17df50a5 XL |
212 | } |
213 | } | |
214 | ||
ba9703b0 | 215 | impl RealFileName { |
17df50a5 XL |
216 | /// Returns the path suitable for reading from the file system on the local host, |
217 | /// if this information exists. | |
218 | /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. | |
219 | pub fn local_path(&self) -> Option<&Path> { | |
ba9703b0 | 220 | match self { |
17df50a5 XL |
221 | RealFileName::LocalPath(p) => Some(p), |
222 | RealFileName::Remapped { local_path: p, virtual_name: _ } => { | |
223 | p.as_ref().map(PathBuf::as_path) | |
224 | } | |
ba9703b0 XL |
225 | } |
226 | } | |
227 | ||
17df50a5 XL |
228 | /// Returns the path suitable for reading from the file system on the local host, |
229 | /// if this information exists. | |
230 | /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. | |
231 | pub fn into_local_path(self) -> Option<PathBuf> { | |
ba9703b0 | 232 | match self { |
17df50a5 XL |
233 | RealFileName::LocalPath(p) => Some(p), |
234 | RealFileName::Remapped { local_path: p, virtual_name: _ } => p, | |
ba9703b0 XL |
235 | } |
236 | } | |
237 | ||
17df50a5 XL |
238 | /// Returns the path suitable for embedding into build artifacts. This would still |
239 | /// be a local path if it has not been remapped. A remapped path will not correspond | |
240 | /// to a valid file system path: see `local_path_if_available()` for something that | |
241 | /// is more likely to return paths into the local host file system. | |
242 | pub fn remapped_path_if_available(&self) -> &Path { | |
ba9703b0 | 243 | match self { |
17df50a5 XL |
244 | RealFileName::LocalPath(p) |
245 | | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, | |
246 | } | |
247 | } | |
248 | ||
249 | /// Returns the path suitable for reading from the file system on the local host, | |
250 | /// if this information exists. Otherwise returns the remapped name. | |
251 | /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. | |
252 | pub fn local_path_if_available(&self) -> &Path { | |
253 | match self { | |
254 | RealFileName::LocalPath(path) | |
255 | | RealFileName::Remapped { local_path: None, virtual_name: path } | |
256 | | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, | |
257 | } | |
258 | } | |
259 | ||
94222f64 XL |
260 | pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { |
261 | match display_pref { | |
262 | FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), | |
263 | FileNameDisplayPreference::Remapped => { | |
264 | self.remapped_path_if_available().to_string_lossy() | |
265 | } | |
ba9703b0 XL |
266 | } |
267 | } | |
268 | } | |
269 | ||
0731742a | 270 | /// Differentiates between real files and common virtual files. |
3dfed10e | 271 | #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] |
94222f64 | 272 | #[derive(Decodable, Encodable)] |
ff7c6d11 | 273 | pub enum FileName { |
ba9703b0 | 274 | Real(RealFileName), |
0731742a XL |
275 | /// Call to `quote!`. |
276 | QuoteExpansion(u64), | |
277 | /// Command line. | |
278 | Anon(u64), | |
74b04a01 | 279 | /// Hack in `src/librustc_ast/parse.rs`. |
0731742a XL |
280 | // FIXME(jseyfried) |
281 | MacroExpansion(u64), | |
282 | ProcMacroSourceCode(u64), | |
283 | /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. | |
284 | CfgSpec(u64), | |
285 | /// Strings provided as crate attributes in the CLI. | |
286 | CliCrateAttr(u64), | |
287 | /// Custom sources for explicit parser calls from plugins and drivers. | |
ff7c6d11 | 288 | Custom(String), |
0731742a | 289 | DocTest(PathBuf, isize), |
5869c6ff | 290 | /// Post-substitution inline assembly from LLVM. |
f9f354fc | 291 | InlineAsm(u64), |
ff7c6d11 XL |
292 | } |
293 | ||
17df50a5 XL |
294 | impl From<PathBuf> for FileName { |
295 | fn from(p: PathBuf) -> Self { | |
296 | assert!(!p.to_string_lossy().ends_with('>')); | |
297 | FileName::Real(RealFileName::LocalPath(p)) | |
298 | } | |
299 | } | |
300 | ||
94222f64 XL |
301 | #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] |
302 | pub enum FileNameDisplayPreference { | |
303 | Remapped, | |
304 | Local, | |
305 | } | |
306 | ||
17df50a5 XL |
307 | pub struct FileNameDisplay<'a> { |
308 | inner: &'a FileName, | |
94222f64 | 309 | display_pref: FileNameDisplayPreference, |
17df50a5 XL |
310 | } |
311 | ||
312 | impl fmt::Display for FileNameDisplay<'_> { | |
9fa01778 XL |
313 | fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
314 | use FileName::*; | |
17df50a5 XL |
315 | match *self.inner { |
316 | Real(ref name) => { | |
94222f64 | 317 | write!(fmt, "{}", name.to_string_lossy(self.display_pref)) |
ba9703b0 | 318 | } |
0731742a XL |
319 | QuoteExpansion(_) => write!(fmt, "<quote expansion>"), |
320 | MacroExpansion(_) => write!(fmt, "<macro expansion>"), | |
321 | Anon(_) => write!(fmt, "<anon>"), | |
dfeec247 | 322 | ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"), |
0731742a XL |
323 | CfgSpec(_) => write!(fmt, "<cfgspec>"), |
324 | CliCrateAttr(_) => write!(fmt, "<crate attribute>"), | |
ff7c6d11 | 325 | Custom(ref s) => write!(fmt, "<{}>", s), |
0731742a | 326 | DocTest(ref path, _) => write!(fmt, "{}", path.display()), |
f9f354fc | 327 | InlineAsm(_) => write!(fmt, "<inline asm>"), |
ff7c6d11 XL |
328 | } |
329 | } | |
330 | } | |
331 | ||
923072b8 FG |
332 | impl<'a> FileNameDisplay<'a> { |
333 | pub fn to_string_lossy(&self) -> Cow<'a, str> { | |
17df50a5 | 334 | match self.inner { |
94222f64 | 335 | FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), |
923072b8 | 336 | _ => Cow::from(self.to_string()), |
17df50a5 | 337 | } |
ff7c6d11 XL |
338 | } |
339 | } | |
340 | ||
341 | impl FileName { | |
342 | pub fn is_real(&self) -> bool { | |
9fa01778 | 343 | use FileName::*; |
ff7c6d11 XL |
344 | match *self { |
345 | Real(_) => true, | |
ba9703b0 | 346 | Anon(_) |
dfeec247 XL |
347 | | MacroExpansion(_) |
348 | | ProcMacroSourceCode(_) | |
349 | | CfgSpec(_) | |
350 | | CliCrateAttr(_) | |
351 | | Custom(_) | |
352 | | QuoteExpansion(_) | |
f9f354fc XL |
353 | | DocTest(_, _) |
354 | | InlineAsm(_) => false, | |
ff7c6d11 XL |
355 | } |
356 | } | |
357 | ||
17df50a5 | 358 | pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { |
94222f64 | 359 | FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } |
17df50a5 XL |
360 | } |
361 | ||
362 | // This may include transient local filesystem information. | |
363 | // Must not be embedded in build outputs. | |
364 | pub fn prefer_local(&self) -> FileNameDisplay<'_> { | |
94222f64 XL |
365 | FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } |
366 | } | |
367 | ||
368 | pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { | |
369 | FileNameDisplay { inner: self, display_pref } | |
17df50a5 XL |
370 | } |
371 | ||
0731742a XL |
372 | pub fn macro_expansion_source_code(src: &str) -> FileName { |
373 | let mut hasher = StableHasher::new(); | |
374 | src.hash(&mut hasher); | |
375 | FileName::MacroExpansion(hasher.finish()) | |
376 | } | |
377 | ||
378 | pub fn anon_source_code(src: &str) -> FileName { | |
379 | let mut hasher = StableHasher::new(); | |
380 | src.hash(&mut hasher); | |
381 | FileName::Anon(hasher.finish()) | |
382 | } | |
383 | ||
384 | pub fn proc_macro_source_code(src: &str) -> FileName { | |
385 | let mut hasher = StableHasher::new(); | |
386 | src.hash(&mut hasher); | |
387 | FileName::ProcMacroSourceCode(hasher.finish()) | |
388 | } | |
389 | ||
390 | pub fn cfg_spec_source_code(src: &str) -> FileName { | |
391 | let mut hasher = StableHasher::new(); | |
392 | src.hash(&mut hasher); | |
393 | FileName::QuoteExpansion(hasher.finish()) | |
394 | } | |
395 | ||
396 | pub fn cli_crate_attr_source_code(src: &str) -> FileName { | |
397 | let mut hasher = StableHasher::new(); | |
398 | src.hash(&mut hasher); | |
399 | FileName::CliCrateAttr(hasher.finish()) | |
400 | } | |
401 | ||
dfeec247 | 402 | pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName { |
0731742a XL |
403 | FileName::DocTest(path, line) |
404 | } | |
f9f354fc XL |
405 | |
406 | pub fn inline_asm_source_code(src: &str) -> FileName { | |
407 | let mut hasher = StableHasher::new(); | |
408 | src.hash(&mut hasher); | |
409 | FileName::InlineAsm(hasher.finish()) | |
410 | } | |
ff7c6d11 | 411 | } |
3157f602 | 412 | |
5869c6ff XL |
413 | /// Represents a span. |
414 | /// | |
3157f602 | 415 | /// Spans represent a region of code, used for error reporting. Positions in spans |
5869c6ff XL |
416 | /// are *absolute* positions from the beginning of the [`SourceMap`], not positions |
417 | /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back | |
3157f602 | 418 | /// to the original source. |
5869c6ff XL |
419 | /// |
420 | /// You must be careful if the span crosses more than one file, since you will not be | |
b7449926 | 421 | /// able to use many of the functions on spans in source_map and you cannot assume |
5869c6ff XL |
422 | /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the |
423 | /// [`BytePos`] range between files. | |
ea8adc8c XL |
424 | /// |
425 | /// `SpanData` is public because `Span` uses a thread-local interner and can't be | |
426 | /// sent to other threads, but some pieces of performance infra run in a separate thread. | |
427 | /// Using `Span` is generally preferred. | |
a2a8927a | 428 | #[derive(Clone, Copy, Hash, PartialEq, Eq)] |
ea8adc8c | 429 | pub struct SpanData { |
3157f602 XL |
430 | pub lo: BytePos, |
431 | pub hi: BytePos, | |
432 | /// Information about where the macro came from, if this piece of | |
433 | /// code was created by a macro expansion. | |
cc61c64b | 434 | pub ctxt: SyntaxContext, |
c295e0f8 | 435 | pub parent: Option<LocalDefId>, |
3157f602 XL |
436 | } |
437 | ||
a2a8927a XL |
438 | // Order spans by position in the file. |
439 | impl Ord for SpanData { | |
440 | fn cmp(&self, other: &Self) -> Ordering { | |
441 | let SpanData { | |
442 | lo: s_lo, | |
443 | hi: s_hi, | |
444 | ctxt: s_ctxt, | |
445 | // `LocalDefId` does not implement `Ord`. | |
446 | // The other fields are enough to determine in-file order. | |
447 | parent: _, | |
448 | } = self; | |
449 | let SpanData { | |
450 | lo: o_lo, | |
451 | hi: o_hi, | |
452 | ctxt: o_ctxt, | |
453 | // `LocalDefId` does not implement `Ord`. | |
454 | // The other fields are enough to determine in-file order. | |
455 | parent: _, | |
456 | } = other; | |
457 | ||
458 | (s_lo, s_hi, s_ctxt).cmp(&(o_lo, o_hi, o_ctxt)) | |
459 | } | |
460 | } | |
461 | ||
462 | impl PartialOrd for SpanData { | |
463 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
464 | Some(self.cmp(other)) | |
465 | } | |
466 | } | |
467 | ||
abe05a73 | 468 | impl SpanData { |
5869c6ff XL |
469 | #[inline] |
470 | pub fn span(&self) -> Span { | |
c295e0f8 | 471 | Span::new(self.lo, self.hi, self.ctxt, self.parent) |
5869c6ff | 472 | } |
abe05a73 XL |
473 | #[inline] |
474 | pub fn with_lo(&self, lo: BytePos) -> Span { | |
c295e0f8 | 475 | Span::new(lo, self.hi, self.ctxt, self.parent) |
abe05a73 XL |
476 | } |
477 | #[inline] | |
478 | pub fn with_hi(&self, hi: BytePos) -> Span { | |
c295e0f8 | 479 | Span::new(self.lo, hi, self.ctxt, self.parent) |
abe05a73 XL |
480 | } |
481 | #[inline] | |
482 | pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span { | |
c295e0f8 XL |
483 | Span::new(self.lo, self.hi, ctxt, self.parent) |
484 | } | |
485 | #[inline] | |
486 | pub fn with_parent(&self, parent: Option<LocalDefId>) -> Span { | |
487 | Span::new(self.lo, self.hi, self.ctxt, parent) | |
488 | } | |
489 | /// Returns `true` if this is a dummy span with any hygienic context. | |
490 | #[inline] | |
491 | pub fn is_dummy(self) -> bool { | |
492 | self.lo.0 == 0 && self.hi.0 == 0 | |
493 | } | |
494 | /// Returns `true` if `self` fully encloses `other`. | |
495 | pub fn contains(self, other: Self) -> bool { | |
496 | self.lo <= other.lo && other.hi <= self.hi | |
abe05a73 XL |
497 | } |
498 | } | |
499 | ||
0531ce1d | 500 | // The interner is pointed to by a thread local value which is only set on the main thread |
0731742a | 501 | // with parallelization is disabled. So we don't allow `Span` to transfer between threads |
0531ce1d | 502 | // to avoid panics and other errors, even though it would be memory safe to do so. |
9fa01778 | 503 | #[cfg(not(parallel_compiler))] |
ea8adc8c | 504 | impl !Send for Span {} |
9fa01778 | 505 | #[cfg(not(parallel_compiler))] |
ea8adc8c XL |
506 | impl !Sync for Span {} |
507 | ||
508 | impl PartialOrd for Span { | |
509 | fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> { | |
510 | PartialOrd::partial_cmp(&self.data(), &rhs.data()) | |
511 | } | |
512 | } | |
513 | impl Ord for Span { | |
514 | fn cmp(&self, rhs: &Self) -> Ordering { | |
515 | Ord::cmp(&self.data(), &rhs.data()) | |
516 | } | |
517 | } | |
518 | ||
3157f602 | 519 | impl Span { |
ea8adc8c XL |
520 | #[inline] |
521 | pub fn lo(self) -> BytePos { | |
522 | self.data().lo | |
523 | } | |
524 | #[inline] | |
525 | pub fn with_lo(self, lo: BytePos) -> Span { | |
abe05a73 | 526 | self.data().with_lo(lo) |
ea8adc8c XL |
527 | } |
528 | #[inline] | |
529 | pub fn hi(self) -> BytePos { | |
530 | self.data().hi | |
531 | } | |
532 | #[inline] | |
533 | pub fn with_hi(self, hi: BytePos) -> Span { | |
abe05a73 | 534 | self.data().with_hi(hi) |
ea8adc8c XL |
535 | } |
536 | #[inline] | |
537 | pub fn ctxt(self) -> SyntaxContext { | |
c295e0f8 | 538 | self.data_untracked().ctxt |
ea8adc8c | 539 | } |
923072b8 FG |
540 | pub fn eq_ctxt(self, other: Span) -> bool { |
541 | self.data_untracked().ctxt == other.data_untracked().ctxt | |
542 | } | |
ea8adc8c XL |
543 | #[inline] |
544 | pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { | |
c295e0f8 XL |
545 | self.data_untracked().with_ctxt(ctxt) |
546 | } | |
547 | #[inline] | |
548 | pub fn parent(self) -> Option<LocalDefId> { | |
549 | self.data().parent | |
550 | } | |
551 | #[inline] | |
552 | pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span { | |
553 | self.data().with_parent(ctxt) | |
ea8adc8c XL |
554 | } |
555 | ||
8faf50e0 XL |
556 | /// Returns `true` if this is a dummy span with any hygienic context. |
557 | #[inline] | |
558 | pub fn is_dummy(self) -> bool { | |
c295e0f8 | 559 | self.data_untracked().is_dummy() |
8faf50e0 XL |
560 | } |
561 | ||
e1599b0c XL |
562 | /// Returns `true` if this span comes from a macro or desugaring. |
563 | #[inline] | |
564 | pub fn from_expansion(self) -> bool { | |
565 | self.ctxt() != SyntaxContext::root() | |
566 | } | |
567 | ||
dfeec247 XL |
568 | /// Returns `true` if `span` originates in a derive-macro's expansion. |
569 | pub fn in_derive_expansion(self) -> bool { | |
136023e0 | 570 | matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _)) |
dfeec247 XL |
571 | } |
572 | ||
a2a8927a XL |
573 | /// Gate suggestions that would not be appropriate in a context the user didn't write. |
574 | pub fn can_be_used_for_suggestions(self) -> bool { | |
575 | !self.from_expansion() | |
576 | // FIXME: If this span comes from a `derive` macro but it points at code the user wrote, | |
577 | // the callsite span and the span will be pointing at different places. It also means that | |
578 | // we can safely provide suggestions on this span. | |
579 | || (matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _)) | |
580 | && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi()))) | |
581 | } | |
582 | ||
e1599b0c XL |
583 | #[inline] |
584 | pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span { | |
c295e0f8 | 585 | Span::new(lo, hi, SyntaxContext::root(), None) |
e1599b0c XL |
586 | } |
587 | ||
5869c6ff | 588 | /// Returns a new span representing an empty span at the beginning of this span. |
0531ce1d XL |
589 | #[inline] |
590 | pub fn shrink_to_lo(self) -> Span { | |
c295e0f8 | 591 | let span = self.data_untracked(); |
0531ce1d XL |
592 | span.with_hi(span.lo) |
593 | } | |
0731742a | 594 | /// Returns a new span representing an empty span at the end of this span. |
0531ce1d XL |
595 | #[inline] |
596 | pub fn shrink_to_hi(self) -> Span { | |
c295e0f8 | 597 | let span = self.data_untracked(); |
0531ce1d XL |
598 | span.with_lo(span.hi) |
599 | } | |
600 | ||
1b1a35ee | 601 | #[inline] |
5869c6ff | 602 | /// Returns `true` if `hi == lo`. |
5099ac24 | 603 | pub fn is_empty(self) -> bool { |
c295e0f8 | 604 | let span = self.data_untracked(); |
1b1a35ee XL |
605 | span.hi == span.lo |
606 | } | |
607 | ||
3157f602 XL |
608 | /// Returns `self` if `self` is not the dummy span, and `other` otherwise. |
609 | pub fn substitute_dummy(self, other: Span) -> Span { | |
8faf50e0 | 610 | if self.is_dummy() { other } else { self } |
3157f602 XL |
611 | } |
612 | ||
9fa01778 | 613 | /// Returns `true` if `self` fully encloses `other`. |
3157f602 | 614 | pub fn contains(self, other: Span) -> bool { |
abe05a73 XL |
615 | let span = self.data(); |
616 | let other = other.data(); | |
c295e0f8 | 617 | span.contains(other) |
3157f602 XL |
618 | } |
619 | ||
9fa01778 | 620 | /// Returns `true` if `self` touches `other`. |
0731742a XL |
621 | pub fn overlaps(self, other: Span) -> bool { |
622 | let span = self.data(); | |
623 | let other = other.data(); | |
624 | span.lo < other.hi && other.lo < span.hi | |
625 | } | |
626 | ||
9fa01778 | 627 | /// Returns `true` if the spans are equal with regards to the source text. |
3157f602 XL |
628 | /// |
629 | /// Use this instead of `==` when either span could be generated code, | |
630 | /// and you only care that they point to the same bytes of source text. | |
5099ac24 | 631 | pub fn source_equal(self, other: Span) -> bool { |
abe05a73 XL |
632 | let span = self.data(); |
633 | let other = other.data(); | |
634 | span.lo == other.lo && span.hi == other.hi | |
3157f602 XL |
635 | } |
636 | ||
0731742a | 637 | /// Returns `Some(span)`, where the start is trimmed by the end of `other`. |
3157f602 | 638 | pub fn trim_start(self, other: Span) -> Option<Span> { |
abe05a73 XL |
639 | let span = self.data(); |
640 | let other = other.data(); | |
dfeec247 | 641 | if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None } |
3157f602 | 642 | } |
cc61c64b | 643 | |
9fa01778 | 644 | /// Returns the source span -- this is either the supplied span, or the span for |
cc61c64b XL |
645 | /// the macro callsite that expanded to it. |
646 | pub fn source_callsite(self) -> Span { | |
e1599b0c XL |
647 | let expn_data = self.ctxt().outer_expn_data(); |
648 | if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self } | |
cc61c64b XL |
649 | } |
650 | ||
83c7162d | 651 | /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, |
0731742a | 652 | /// if any. |
c295e0f8 | 653 | pub fn parent_callsite(self) -> Option<Span> { |
e1599b0c XL |
654 | let expn_data = self.ctxt().outer_expn_data(); |
655 | if !expn_data.is_root() { Some(expn_data.call_site) } else { None } | |
83c7162d XL |
656 | } |
657 | ||
94222f64 XL |
658 | /// Walk down the expansion ancestors to find a span that's contained within `outer`. |
659 | pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> { | |
660 | while !outer.contains(self) { | |
c295e0f8 | 661 | self = self.parent_callsite()?; |
94222f64 XL |
662 | } |
663 | Some(self) | |
664 | } | |
665 | ||
94b46f34 XL |
666 | /// Edition of the crate from which this span came. |
667 | pub fn edition(self) -> edition::Edition { | |
5869c6ff | 668 | self.ctxt().edition() |
94b46f34 XL |
669 | } |
670 | ||
13cf67c4 | 671 | #[inline] |
5099ac24 | 672 | pub fn rust_2015(self) -> bool { |
13cf67c4 XL |
673 | self.edition() == edition::Edition::Edition2015 |
674 | } | |
675 | ||
676 | #[inline] | |
5099ac24 | 677 | pub fn rust_2018(self) -> bool { |
13cf67c4 XL |
678 | self.edition() >= edition::Edition::Edition2018 |
679 | } | |
680 | ||
5869c6ff | 681 | #[inline] |
5099ac24 | 682 | pub fn rust_2021(self) -> bool { |
5869c6ff XL |
683 | self.edition() >= edition::Edition::Edition2021 |
684 | } | |
685 | ||
04454e1e FG |
686 | #[inline] |
687 | pub fn rust_2024(self) -> bool { | |
688 | self.edition() >= edition::Edition::Edition2024 | |
689 | } | |
690 | ||
9fa01778 | 691 | /// Returns the source callee. |
cc61c64b | 692 | /// |
8faf50e0 | 693 | /// Returns `None` if the supplied span has no expansion trace, |
e1599b0c | 694 | /// else returns the `ExpnData` for the macro definition |
cc61c64b | 695 | /// corresponding to the source callsite. |
e1599b0c XL |
696 | pub fn source_callee(self) -> Option<ExpnData> { |
697 | fn source_callee(expn_data: ExpnData) -> ExpnData { | |
698 | let next_expn_data = expn_data.call_site.ctxt().outer_expn_data(); | |
699 | if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data } | |
cc61c64b | 700 | } |
e1599b0c XL |
701 | let expn_data = self.ctxt().outer_expn_data(); |
702 | if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } | |
cc61c64b XL |
703 | } |
704 | ||
9fa01778 | 705 | /// Checks if a span is "internal" to a macro in which `#[unstable]` |
cc61c64b XL |
706 | /// items can be used (that is, a macro marked with |
707 | /// `#[allow_internal_unstable]`). | |
5099ac24 | 708 | pub fn allows_unstable(self, feature: Symbol) -> bool { |
6a06907d XL |
709 | self.ctxt() |
710 | .outer_expn_data() | |
711 | .allow_internal_unstable | |
712 | .map_or(false, |features| features.iter().any(|&f| f == feature)) | |
cc61c64b XL |
713 | } |
714 | ||
9fa01778 | 715 | /// Checks if this span arises from a compiler desugaring of kind `kind`. |
5099ac24 | 716 | pub fn is_desugaring(self, kind: DesugaringKind) -> bool { |
e1599b0c XL |
717 | match self.ctxt().outer_expn_data().kind { |
718 | ExpnKind::Desugaring(k) => k == kind, | |
719 | _ => false, | |
3b2f2976 XL |
720 | } |
721 | } | |
722 | ||
9fa01778 | 723 | /// Returns the compiler desugaring that created this span, or `None` |
ea8adc8c | 724 | /// if this span is not from a desugaring. |
5099ac24 | 725 | pub fn desugaring_kind(self) -> Option<DesugaringKind> { |
e1599b0c XL |
726 | match self.ctxt().outer_expn_data().kind { |
727 | ExpnKind::Desugaring(k) => Some(k), | |
dfeec247 | 728 | _ => None, |
ea8adc8c XL |
729 | } |
730 | } | |
731 | ||
9fa01778 | 732 | /// Checks if a span is "internal" to a macro in which `unsafe` |
5869c6ff | 733 | /// can be used without triggering the `unsafe_code` lint. |
3b2f2976 | 734 | // (that is, a macro marked with `#[allow_internal_unsafe]`). |
5099ac24 | 735 | pub fn allows_unsafe(self) -> bool { |
e1599b0c | 736 | self.ctxt().outer_expn_data().allow_internal_unsafe |
3b2f2976 XL |
737 | } |
738 | ||
dfeec247 | 739 | pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> { |
cc61c64b | 740 | let mut prev_span = DUMMY_SP; |
dfeec247 XL |
741 | std::iter::from_fn(move || { |
742 | loop { | |
743 | let expn_data = self.ctxt().outer_expn_data(); | |
744 | if expn_data.is_root() { | |
745 | return None; | |
746 | } | |
cc61c64b | 747 | |
5099ac24 | 748 | let is_recursive = expn_data.call_site.source_equal(prev_span); |
dfeec247 XL |
749 | |
750 | prev_span = self; | |
751 | self = expn_data.call_site; | |
752 | ||
753 | // Don't print recursive invocations. | |
754 | if !is_recursive { | |
755 | return Some(expn_data); | |
756 | } | |
757 | } | |
758 | }) | |
cc61c64b XL |
759 | } |
760 | ||
9fa01778 | 761 | /// Returns a `Span` that would enclose both `self` and `end`. |
1b1a35ee XL |
762 | /// |
763 | /// ```text | |
764 | /// ____ ___ | |
765 | /// self lorem ipsum end | |
766 | /// ^^^^^^^^^^^^^^^^^^^^ | |
767 | /// ``` | |
cc61c64b | 768 | pub fn to(self, end: Span) -> Span { |
2c00a5a8 XL |
769 | let span_data = self.data(); |
770 | let end_data = end.data(); | |
0731742a | 771 | // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). |
2c00a5a8 XL |
772 | // Return the macro span on its own to avoid weird diagnostic output. It is preferable to |
773 | // have an incomplete span than a completely nonsensical one. | |
774 | if span_data.ctxt != end_data.ctxt { | |
e1599b0c | 775 | if span_data.ctxt == SyntaxContext::root() { |
2c00a5a8 | 776 | return end; |
e1599b0c | 777 | } else if end_data.ctxt == SyntaxContext::root() { |
2c00a5a8 XL |
778 | return self; |
779 | } | |
0731742a XL |
780 | // Both spans fall within a macro. |
781 | // FIXME(estebank): check if it is the *same* macro. | |
2c00a5a8 | 782 | } |
ea8adc8c | 783 | Span::new( |
2c00a5a8 XL |
784 | cmp::min(span_data.lo, end_data.lo), |
785 | cmp::max(span_data.hi, end_data.hi), | |
e1599b0c | 786 | if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, |
c295e0f8 | 787 | if span_data.parent == end_data.parent { span_data.parent } else { None }, |
ea8adc8c | 788 | ) |
cc61c64b XL |
789 | } |
790 | ||
9fa01778 | 791 | /// Returns a `Span` between the end of `self` to the beginning of `end`. |
1b1a35ee XL |
792 | /// |
793 | /// ```text | |
794 | /// ____ ___ | |
795 | /// self lorem ipsum end | |
796 | /// ^^^^^^^^^^^^^ | |
797 | /// ``` | |
cc61c64b | 798 | pub fn between(self, end: Span) -> Span { |
abe05a73 XL |
799 | let span = self.data(); |
800 | let end = end.data(); | |
ea8adc8c | 801 | Span::new( |
abe05a73 XL |
802 | span.hi, |
803 | end.lo, | |
e1599b0c | 804 | if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, |
c295e0f8 | 805 | if span.parent == end.parent { span.parent } else { None }, |
ea8adc8c | 806 | ) |
cc61c64b XL |
807 | } |
808 | ||
1b1a35ee XL |
809 | /// Returns a `Span` from the beginning of `self` until the beginning of `end`. |
810 | /// | |
811 | /// ```text | |
812 | /// ____ ___ | |
813 | /// self lorem ipsum end | |
814 | /// ^^^^^^^^^^^^^^^^^ | |
815 | /// ``` | |
cc61c64b | 816 | pub fn until(self, end: Span) -> Span { |
c295e0f8 XL |
817 | // Most of this function's body is copied from `to`. |
818 | // We can't just do `self.to(end.shrink_to_lo())`, | |
819 | // because to also does some magic where it uses min/max so | |
820 | // it can handle overlapping spans. Some advanced mis-use of | |
821 | // `until` with different ctxts makes this visible. | |
822 | let span_data = self.data(); | |
823 | let end_data = end.data(); | |
824 | // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). | |
825 | // Return the macro span on its own to avoid weird diagnostic output. It is preferable to | |
826 | // have an incomplete span than a completely nonsensical one. | |
827 | if span_data.ctxt != end_data.ctxt { | |
828 | if span_data.ctxt == SyntaxContext::root() { | |
829 | return end; | |
830 | } else if end_data.ctxt == SyntaxContext::root() { | |
831 | return self; | |
832 | } | |
833 | // Both spans fall within a macro. | |
834 | // FIXME(estebank): check if it is the *same* macro. | |
835 | } | |
ea8adc8c | 836 | Span::new( |
c295e0f8 XL |
837 | span_data.lo, |
838 | end_data.lo, | |
839 | if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, | |
840 | if span_data.parent == end_data.parent { span_data.parent } else { None }, | |
ea8adc8c | 841 | ) |
cc61c64b | 842 | } |
83c7162d | 843 | |
dc9dc135 | 844 | pub fn from_inner(self, inner: InnerSpan) -> Span { |
94b46f34 | 845 | let span = self.data(); |
dfeec247 XL |
846 | Span::new( |
847 | span.lo + BytePos::from_usize(inner.start), | |
848 | span.lo + BytePos::from_usize(inner.end), | |
849 | span.ctxt, | |
c295e0f8 | 850 | span.parent, |
dfeec247 | 851 | ) |
94b46f34 XL |
852 | } |
853 | ||
e1599b0c XL |
854 | /// Equivalent of `Span::def_site` from the proc macro API, |
855 | /// except that the location is taken from the `self` span. | |
856 | pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { | |
857 | self.with_ctxt_from_mark(expn_id, Transparency::Opaque) | |
858 | } | |
859 | ||
860 | /// Equivalent of `Span::call_site` from the proc macro API, | |
861 | /// except that the location is taken from the `self` span. | |
5099ac24 | 862 | pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { |
e1599b0c XL |
863 | self.with_ctxt_from_mark(expn_id, Transparency::Transparent) |
864 | } | |
865 | ||
e74abb32 XL |
866 | /// Equivalent of `Span::mixed_site` from the proc macro API, |
867 | /// except that the location is taken from the `self` span. | |
5099ac24 | 868 | pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { |
e74abb32 XL |
869 | self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) |
870 | } | |
871 | ||
e1599b0c XL |
872 | /// Produces a span with the same location as `self` and context produced by a macro with the |
873 | /// given ID and transparency, assuming that macro was defined directly and not produced by | |
874 | /// some other macro (which is the case for built-in and procedural macros). | |
875 | pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { | |
876 | self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) | |
877 | } | |
878 | ||
83c7162d | 879 | #[inline] |
e1599b0c | 880 | pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { |
83c7162d | 881 | let span = self.data(); |
e1599b0c | 882 | span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) |
83c7162d XL |
883 | } |
884 | ||
885 | #[inline] | |
416331ca | 886 | pub fn remove_mark(&mut self) -> ExpnId { |
83c7162d XL |
887 | let mut span = self.data(); |
888 | let mark = span.ctxt.remove_mark(); | |
c295e0f8 | 889 | *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); |
83c7162d XL |
890 | mark |
891 | } | |
892 | ||
893 | #[inline] | |
416331ca | 894 | pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> { |
83c7162d | 895 | let mut span = self.data(); |
416331ca | 896 | let mark = span.ctxt.adjust(expn_id); |
c295e0f8 | 897 | *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); |
83c7162d XL |
898 | mark |
899 | } | |
900 | ||
901 | #[inline] | |
ba9703b0 | 902 | pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> { |
83c7162d | 903 | let mut span = self.data(); |
ba9703b0 | 904 | let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); |
c295e0f8 | 905 | *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); |
83c7162d XL |
906 | mark |
907 | } | |
908 | ||
909 | #[inline] | |
416331ca | 910 | pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> { |
dc9dc135 | 911 | let mut span = self.data(); |
416331ca | 912 | let mark = span.ctxt.glob_adjust(expn_id, glob_span); |
c295e0f8 | 913 | *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); |
dc9dc135 XL |
914 | mark |
915 | } | |
916 | ||
917 | #[inline] | |
dfeec247 XL |
918 | pub fn reverse_glob_adjust( |
919 | &mut self, | |
920 | expn_id: ExpnId, | |
921 | glob_span: Span, | |
922 | ) -> Option<Option<ExpnId>> { | |
83c7162d | 923 | let mut span = self.data(); |
416331ca | 924 | let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); |
c295e0f8 | 925 | *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); |
83c7162d XL |
926 | mark |
927 | } | |
928 | ||
929 | #[inline] | |
ba9703b0 | 930 | pub fn normalize_to_macros_2_0(self) -> Span { |
83c7162d | 931 | let span = self.data(); |
ba9703b0 | 932 | span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) |
83c7162d | 933 | } |
8faf50e0 XL |
934 | |
935 | #[inline] | |
ba9703b0 | 936 | pub fn normalize_to_macro_rules(self) -> Span { |
8faf50e0 | 937 | let span = self.data(); |
ba9703b0 | 938 | span.with_ctxt(span.ctxt.normalize_to_macro_rules()) |
8faf50e0 | 939 | } |
3157f602 XL |
940 | } |
941 | ||
3b2f2976 XL |
942 | impl Default for Span { |
943 | fn default() -> Self { | |
944 | DUMMY_SP | |
945 | } | |
946 | } | |
947 | ||
3dfed10e | 948 | impl<E: Encoder> Encodable<E> for Span { |
923072b8 | 949 | default fn encode(&self, s: &mut E) { |
abe05a73 | 950 | let span = self.data(); |
923072b8 FG |
951 | span.lo.encode(s); |
952 | span.hi.encode(s); | |
3157f602 XL |
953 | } |
954 | } | |
3dfed10e | 955 | impl<D: Decoder> Decodable<D> for Span { |
5099ac24 | 956 | default fn decode(s: &mut D) -> Span { |
5e7ed085 FG |
957 | let lo = Decodable::decode(s); |
958 | let hi = Decodable::decode(s); | |
3dfed10e | 959 | |
5e7ed085 | 960 | Span::new(lo, hi, SyntaxContext::root(), None) |
3157f602 XL |
961 | } |
962 | } | |
963 | ||
f035d41b | 964 | /// Calls the provided closure, using the provided `SourceMap` to format |
29967ef6 | 965 | /// any spans that are debug-printed during the closure's execution. |
f035d41b XL |
966 | /// |
967 | /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` | |
5869c6ff | 968 | /// (see `rustc_interface::callbacks::span_debug1`). However, some parts |
f035d41b XL |
969 | /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before |
970 | /// a `TyCtxt` is available. In this case, we fall back to | |
971 | /// the `SourceMap` provided to this function. If that is not available, | |
29967ef6 | 972 | /// we fall back to printing the raw `Span` field values. |
f035d41b | 973 | pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T { |
136023e0 | 974 | with_session_globals(|session_globals| { |
f035d41b XL |
975 | *session_globals.source_map.borrow_mut() = Some(source_map); |
976 | }); | |
977 | struct ClearSourceMap; | |
978 | impl Drop for ClearSourceMap { | |
979 | fn drop(&mut self) { | |
136023e0 | 980 | with_session_globals(|session_globals| { |
f035d41b XL |
981 | session_globals.source_map.borrow_mut().take(); |
982 | }); | |
983 | } | |
984 | } | |
985 | ||
986 | let _guard = ClearSourceMap; | |
987 | f() | |
988 | } | |
989 | ||
3157f602 | 990 | impl fmt::Debug for Span { |
9fa01778 | 991 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
5099ac24 FG |
992 | with_session_globals(|session_globals| { |
993 | if let Some(source_map) = &*session_globals.source_map.borrow() { | |
994 | write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt()) | |
995 | } else { | |
996 | f.debug_struct("Span") | |
997 | .field("lo", &self.lo()) | |
998 | .field("hi", &self.hi()) | |
999 | .field("ctxt", &self.ctxt()) | |
1000 | .finish() | |
1001 | } | |
1002 | }) | |
3157f602 XL |
1003 | } |
1004 | } | |
1005 | ||
ea8adc8c | 1006 | impl fmt::Debug for SpanData { |
9fa01778 | 1007 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
5099ac24 | 1008 | fmt::Debug::fmt(&Span::new(self.lo, self.hi, self.ctxt, self.parent), f) |
ea8adc8c XL |
1009 | } |
1010 | } | |
3157f602 | 1011 | |
0731742a | 1012 | /// Identifies an offset of a multi-byte character in a `SourceFile`. |
3dfed10e | 1013 | #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] |
3157f602 | 1014 | pub struct MultiByteChar { |
0731742a | 1015 | /// The absolute offset of the character in the `SourceMap`. |
3157f602 | 1016 | pub pos: BytePos, |
0731742a | 1017 | /// The number of bytes, `>= 2`. |
8faf50e0 | 1018 | pub bytes: u8, |
3157f602 XL |
1019 | } |
1020 | ||
0731742a | 1021 | /// Identifies an offset of a non-narrow character in a `SourceFile`. |
3dfed10e | 1022 | #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] |
abe05a73 | 1023 | pub enum NonNarrowChar { |
0731742a | 1024 | /// Represents a zero-width character. |
abe05a73 | 1025 | ZeroWidth(BytePos), |
0731742a | 1026 | /// Represents a wide (full-width) character. |
abe05a73 | 1027 | Wide(BytePos), |
0731742a | 1028 | /// Represents a tab character, represented visually with a width of 4 characters. |
ff7c6d11 | 1029 | Tab(BytePos), |
abe05a73 XL |
1030 | } |
1031 | ||
1032 | impl NonNarrowChar { | |
1033 | fn new(pos: BytePos, width: usize) -> Self { | |
1034 | match width { | |
1035 | 0 => NonNarrowChar::ZeroWidth(pos), | |
1036 | 2 => NonNarrowChar::Wide(pos), | |
ff7c6d11 | 1037 | 4 => NonNarrowChar::Tab(pos), |
abe05a73 XL |
1038 | _ => panic!("width {} given for non-narrow character", width), |
1039 | } | |
1040 | } | |
1041 | ||
0731742a | 1042 | /// Returns the absolute offset of the character in the `SourceMap`. |
abe05a73 XL |
1043 | pub fn pos(&self) -> BytePos { |
1044 | match *self { | |
dfeec247 | 1045 | NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p, |
abe05a73 XL |
1046 | } |
1047 | } | |
1048 | ||
0731742a | 1049 | /// Returns the width of the character, 0 (zero-width) or 2 (wide). |
abe05a73 XL |
1050 | pub fn width(&self) -> usize { |
1051 | match *self { | |
1052 | NonNarrowChar::ZeroWidth(_) => 0, | |
1053 | NonNarrowChar::Wide(_) => 2, | |
ff7c6d11 | 1054 | NonNarrowChar::Tab(_) => 4, |
abe05a73 XL |
1055 | } |
1056 | } | |
1057 | } | |
1058 | ||
1059 | impl Add<BytePos> for NonNarrowChar { | |
1060 | type Output = Self; | |
1061 | ||
1062 | fn add(self, rhs: BytePos) -> Self { | |
1063 | match self { | |
1064 | NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), | |
1065 | NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), | |
ff7c6d11 | 1066 | NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), |
abe05a73 XL |
1067 | } |
1068 | } | |
1069 | } | |
1070 | ||
1071 | impl Sub<BytePos> for NonNarrowChar { | |
1072 | type Output = Self; | |
1073 | ||
1074 | fn sub(self, rhs: BytePos) -> Self { | |
1075 | match self { | |
1076 | NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), | |
1077 | NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), | |
ff7c6d11 | 1078 | NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), |
abe05a73 XL |
1079 | } |
1080 | } | |
1081 | } | |
1082 | ||
e74abb32 | 1083 | /// Identifies an offset of a character that was normalized away from `SourceFile`. |
3dfed10e | 1084 | #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] |
e74abb32 XL |
1085 | pub struct NormalizedPos { |
1086 | /// The absolute offset of the character in the `SourceMap`. | |
1087 | pub pos: BytePos, | |
1088 | /// The difference between original and normalized string at position. | |
1089 | pub diff: u32, | |
1090 | } | |
1091 | ||
ba9703b0 | 1092 | #[derive(PartialEq, Eq, Clone, Debug)] |
041b39d2 | 1093 | pub enum ExternalSource { |
ba9703b0 XL |
1094 | /// No external source has to be loaded, since the `SourceFile` represents a local crate. |
1095 | Unneeded, | |
1096 | Foreign { | |
1097 | kind: ExternalSourceKind, | |
5869c6ff | 1098 | /// This SourceFile's byte-offset within the source_map of its original crate. |
ba9703b0 | 1099 | original_start_pos: BytePos, |
5869c6ff | 1100 | /// The end of this SourceFile within the source_map of its original crate. |
ba9703b0 XL |
1101 | original_end_pos: BytePos, |
1102 | }, | |
1103 | } | |
1104 | ||
1105 | /// The state of the lazy external source loading mechanism of a `SourceFile`. | |
1106 | #[derive(PartialEq, Eq, Clone, Debug)] | |
1107 | pub enum ExternalSourceKind { | |
041b39d2 | 1108 | /// The external source has been loaded already. |
ba9703b0 | 1109 | Present(Lrc<String>), |
041b39d2 XL |
1110 | /// No attempt has been made to load the external source. |
1111 | AbsentOk, | |
1112 | /// A failed attempt has been made to load the external source. | |
1113 | AbsentErr, | |
041b39d2 XL |
1114 | Unneeded, |
1115 | } | |
1116 | ||
1117 | impl ExternalSource { | |
ba9703b0 XL |
1118 | pub fn get_source(&self) -> Option<&Lrc<String>> { |
1119 | match self { | |
1120 | ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), | |
041b39d2 XL |
1121 | _ => None, |
1122 | } | |
1123 | } | |
1124 | } | |
1125 | ||
dc9dc135 XL |
1126 | #[derive(Debug)] |
1127 | pub struct OffsetOverflowError; | |
1128 | ||
3dfed10e | 1129 | #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] |
04454e1e | 1130 | #[derive(HashStable_Generic)] |
ba9703b0 XL |
1131 | pub enum SourceFileHashAlgorithm { |
1132 | Md5, | |
1133 | Sha1, | |
29967ef6 | 1134 | Sha256, |
ba9703b0 XL |
1135 | } |
1136 | ||
1137 | impl FromStr for SourceFileHashAlgorithm { | |
1138 | type Err = (); | |
1139 | ||
1140 | fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> { | |
1141 | match s { | |
1142 | "md5" => Ok(SourceFileHashAlgorithm::Md5), | |
1143 | "sha1" => Ok(SourceFileHashAlgorithm::Sha1), | |
29967ef6 | 1144 | "sha256" => Ok(SourceFileHashAlgorithm::Sha256), |
ba9703b0 XL |
1145 | _ => Err(()), |
1146 | } | |
1147 | } | |
1148 | } | |
1149 | ||
ba9703b0 | 1150 | /// The hash of the on-disk source file used for debug info. |
923072b8 | 1151 | #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] |
3dfed10e | 1152 | #[derive(HashStable_Generic, Encodable, Decodable)] |
ba9703b0 XL |
1153 | pub struct SourceFileHash { |
1154 | pub kind: SourceFileHashAlgorithm, | |
29967ef6 | 1155 | value: [u8; 32], |
ba9703b0 XL |
1156 | } |
1157 | ||
1158 | impl SourceFileHash { | |
1159 | pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { | |
1160 | let mut hash = SourceFileHash { kind, value: Default::default() }; | |
1161 | let len = hash.hash_len(); | |
1162 | let value = &mut hash.value[..len]; | |
1163 | let data = src.as_bytes(); | |
1164 | match kind { | |
1165 | SourceFileHashAlgorithm::Md5 => { | |
1166 | value.copy_from_slice(&Md5::digest(data)); | |
1167 | } | |
1168 | SourceFileHashAlgorithm::Sha1 => { | |
1169 | value.copy_from_slice(&Sha1::digest(data)); | |
1170 | } | |
29967ef6 XL |
1171 | SourceFileHashAlgorithm::Sha256 => { |
1172 | value.copy_from_slice(&Sha256::digest(data)); | |
1173 | } | |
ba9703b0 XL |
1174 | } |
1175 | hash | |
1176 | } | |
1177 | ||
1178 | /// Check if the stored hash matches the hash of the string. | |
1179 | pub fn matches(&self, src: &str) -> bool { | |
1180 | Self::new(self.kind, src) == *self | |
1181 | } | |
1182 | ||
1183 | /// The bytes of the hash. | |
1184 | pub fn hash_bytes(&self) -> &[u8] { | |
1185 | let len = self.hash_len(); | |
1186 | &self.value[..len] | |
1187 | } | |
1188 | ||
1189 | fn hash_len(&self) -> usize { | |
1190 | match self.kind { | |
1191 | SourceFileHashAlgorithm::Md5 => 16, | |
1192 | SourceFileHashAlgorithm::Sha1 => 20, | |
29967ef6 | 1193 | SourceFileHashAlgorithm::Sha256 => 32, |
ba9703b0 XL |
1194 | } |
1195 | } | |
1196 | } | |
1197 | ||
04454e1e FG |
1198 | #[derive(HashStable_Generic)] |
1199 | #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, Encodable, Decodable)] | |
1200 | pub enum DebuggerVisualizerType { | |
1201 | Natvis, | |
923072b8 | 1202 | GdbPrettyPrinter, |
04454e1e FG |
1203 | } |
1204 | ||
1205 | /// A single debugger visualizer file. | |
1206 | #[derive(HashStable_Generic)] | |
1207 | #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable)] | |
1208 | pub struct DebuggerVisualizerFile { | |
1209 | /// The complete debugger visualizer source. | |
1210 | pub src: Arc<[u8]>, | |
1211 | /// Indicates which visualizer type this targets. | |
1212 | pub visualizer_type: DebuggerVisualizerType, | |
1213 | } | |
1214 | ||
1215 | impl DebuggerVisualizerFile { | |
1216 | pub fn new(src: Arc<[u8]>, visualizer_type: DebuggerVisualizerType) -> Self { | |
1217 | DebuggerVisualizerFile { src, visualizer_type } | |
1218 | } | |
1219 | } | |
1220 | ||
923072b8 FG |
1221 | #[derive(Clone)] |
1222 | pub enum SourceFileLines { | |
1223 | /// The source file lines, in decoded (random-access) form. | |
1224 | Lines(Vec<BytePos>), | |
1225 | ||
1226 | /// The source file lines, in undecoded difference list form. | |
1227 | Diffs(SourceFileDiffs), | |
1228 | } | |
1229 | ||
1230 | impl SourceFileLines { | |
1231 | pub fn is_lines(&self) -> bool { | |
1232 | matches!(self, SourceFileLines::Lines(_)) | |
1233 | } | |
1234 | } | |
1235 | ||
1236 | /// The source file lines in difference list form. This matches the form | |
1237 | /// used within metadata, which saves space by exploiting the fact that the | |
1238 | /// lines list is sorted and individual lines are usually not that long. | |
1239 | /// | |
1240 | /// We read it directly from metadata and only decode it into `Lines` form | |
1241 | /// when necessary. This is a significant performance win, especially for | |
1242 | /// small crates where very little of `std`'s metadata is used. | |
1243 | #[derive(Clone)] | |
1244 | pub struct SourceFileDiffs { | |
1245 | /// Position of the first line. Note that this is always encoded as a | |
1246 | /// `BytePos` because it is often much larger than any of the | |
1247 | /// differences. | |
1248 | line_start: BytePos, | |
1249 | ||
1250 | /// Always 1, 2, or 4. Always as small as possible, while being big | |
1251 | /// enough to hold the length of the longest line in the source file. | |
1252 | /// The 1 case is by far the most common. | |
1253 | bytes_per_diff: usize, | |
1254 | ||
1255 | /// The number of diffs encoded in `raw_diffs`. Always one less than | |
1256 | /// the number of lines in the source file. | |
1257 | num_diffs: usize, | |
1258 | ||
1259 | /// The diffs in "raw" form. Each segment of `bytes_per_diff` length | |
1260 | /// encodes one little-endian diff. Note that they aren't LEB128 | |
1261 | /// encoded. This makes for much faster decoding. Besides, the | |
1262 | /// bytes_per_diff==1 case is by far the most common, and LEB128 | |
1263 | /// encoding has no effect on that case. | |
1264 | raw_diffs: Vec<u8>, | |
1265 | } | |
1266 | ||
5869c6ff | 1267 | /// A single source in the [`SourceMap`]. |
7cac9316 | 1268 | #[derive(Clone)] |
b7449926 | 1269 | pub struct SourceFile { |
e74abb32 | 1270 | /// The name of the file that the source came from. Source that doesn't |
0731742a XL |
1271 | /// originate from files has names between angle brackets by convention |
1272 | /// (e.g., `<anon>`). | |
3157f602 | 1273 | pub name: FileName, |
0731742a | 1274 | /// The complete source code. |
0531ce1d | 1275 | pub src: Option<Lrc<String>>, |
0731742a | 1276 | /// The source code's hash. |
ba9703b0 | 1277 | pub src_hash: SourceFileHash, |
041b39d2 XL |
1278 | /// The external source code (used for external crates, which will have a `None` |
1279 | /// value as `self.src`. | |
0531ce1d | 1280 | pub external_src: Lock<ExternalSource>, |
0731742a | 1281 | /// The start position of this source in the `SourceMap`. |
3157f602 | 1282 | pub start_pos: BytePos, |
0731742a | 1283 | /// The end position of this source in the `SourceMap`. |
3157f602 | 1284 | pub end_pos: BytePos, |
0731742a | 1285 | /// Locations of lines beginnings in the source code. |
923072b8 | 1286 | pub lines: Lock<SourceFileLines>, |
0731742a | 1287 | /// Locations of multi-byte characters in the source code. |
8faf50e0 | 1288 | pub multibyte_chars: Vec<MultiByteChar>, |
0731742a | 1289 | /// Width of characters that are not narrow in the source code. |
8faf50e0 | 1290 | pub non_narrow_chars: Vec<NonNarrowChar>, |
e74abb32 XL |
1291 | /// Locations of characters removed during normalization. |
1292 | pub normalized_pos: Vec<NormalizedPos>, | |
0731742a | 1293 | /// A hash of the filename, used for speeding up hashing in incremental compilation. |
ff7c6d11 | 1294 | pub name_hash: u128, |
ba9703b0 XL |
1295 | /// Indicates which crate this `SourceFile` was imported from. |
1296 | pub cnum: CrateNum, | |
3157f602 XL |
1297 | } |
1298 | ||
3dfed10e | 1299 | impl<S: Encoder> Encodable<S> for SourceFile { |
923072b8 FG |
1300 | fn encode(&self, s: &mut S) { |
1301 | self.name.encode(s); | |
1302 | self.src_hash.encode(s); | |
1303 | self.start_pos.encode(s); | |
1304 | self.end_pos.encode(s); | |
1305 | ||
1306 | // We are always in `Lines` form by the time we reach here. | |
1307 | assert!(self.lines.borrow().is_lines()); | |
1308 | self.lines(|lines| { | |
1309 | // Store the length. | |
1310 | s.emit_u32(lines.len() as u32); | |
1311 | ||
1312 | // Compute and store the difference list. | |
1313 | if lines.len() != 0 { | |
1314 | let max_line_length = if lines.len() == 1 { | |
1315 | 0 | |
1316 | } else { | |
1317 | lines | |
1318 | .array_windows() | |
1319 | .map(|&[fst, snd]| snd - fst) | |
1320 | .map(|bp| bp.to_usize()) | |
1321 | .max() | |
1322 | .unwrap() | |
1323 | }; | |
1324 | ||
1325 | let bytes_per_diff: usize = match max_line_length { | |
1326 | 0..=0xFF => 1, | |
1327 | 0x100..=0xFFFF => 2, | |
1328 | _ => 4, | |
1329 | }; | |
1330 | ||
1331 | // Encode the number of bytes used per diff. | |
1332 | s.emit_u8(bytes_per_diff as u8); | |
1333 | ||
1334 | // Encode the first element. | |
1335 | lines[0].encode(s); | |
1336 | ||
1337 | // Encode the difference list. | |
1338 | let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); | |
1339 | let num_diffs = lines.len() - 1; | |
1340 | let mut raw_diffs; | |
1341 | match bytes_per_diff { | |
1342 | 1 => { | |
1343 | raw_diffs = Vec::with_capacity(num_diffs); | |
1344 | for diff in diff_iter { | |
1345 | raw_diffs.push(diff.0 as u8); | |
dfeec247 | 1346 | } |
923072b8 FG |
1347 | } |
1348 | 2 => { | |
1349 | raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs); | |
1350 | for diff in diff_iter { | |
1351 | raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes()); | |
dfeec247 | 1352 | } |
923072b8 FG |
1353 | } |
1354 | 4 => { | |
1355 | raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs); | |
1356 | for diff in diff_iter { | |
1357 | raw_diffs.extend_from_slice(&(diff.0 as u32).to_le_bytes()); | |
dfeec247 | 1358 | } |
3157f602 | 1359 | } |
923072b8 | 1360 | _ => unreachable!(), |
3157f602 | 1361 | } |
923072b8 FG |
1362 | s.emit_raw_bytes(&raw_diffs); |
1363 | } | |
1364 | }); | |
3157f602 | 1365 | |
923072b8 FG |
1366 | self.multibyte_chars.encode(s); |
1367 | self.non_narrow_chars.encode(s); | |
1368 | self.name_hash.encode(s); | |
1369 | self.normalized_pos.encode(s); | |
1370 | self.cnum.encode(s); | |
3157f602 XL |
1371 | } |
1372 | } | |
1373 | ||
3dfed10e | 1374 | impl<D: Decoder> Decodable<D> for SourceFile { |
5099ac24 | 1375 | fn decode(d: &mut D) -> SourceFile { |
5e7ed085 FG |
1376 | let name: FileName = Decodable::decode(d); |
1377 | let src_hash: SourceFileHash = Decodable::decode(d); | |
1378 | let start_pos: BytePos = Decodable::decode(d); | |
1379 | let end_pos: BytePos = Decodable::decode(d); | |
923072b8 | 1380 | let lines = { |
5e7ed085 | 1381 | let num_lines: u32 = Decodable::decode(d); |
5e7ed085 FG |
1382 | if num_lines > 0 { |
1383 | // Read the number of bytes used per diff. | |
923072b8 | 1384 | let bytes_per_diff = d.read_u8() as usize; |
5e7ed085 FG |
1385 | |
1386 | // Read the first element. | |
923072b8 FG |
1387 | let line_start: BytePos = Decodable::decode(d); |
1388 | ||
1389 | // Read the difference list. | |
1390 | let num_diffs = num_lines as usize - 1; | |
1391 | let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec(); | |
1392 | SourceFileLines::Diffs(SourceFileDiffs { | |
1393 | line_start, | |
1394 | bytes_per_diff, | |
1395 | num_diffs, | |
1396 | raw_diffs, | |
1397 | }) | |
1398 | } else { | |
1399 | SourceFileLines::Lines(vec![]) | |
5099ac24 | 1400 | } |
5e7ed085 FG |
1401 | }; |
1402 | let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d); | |
1403 | let non_narrow_chars: Vec<NonNarrowChar> = Decodable::decode(d); | |
1404 | let name_hash: u128 = Decodable::decode(d); | |
1405 | let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d); | |
1406 | let cnum: CrateNum = Decodable::decode(d); | |
1407 | SourceFile { | |
1408 | name, | |
1409 | start_pos, | |
1410 | end_pos, | |
1411 | src: None, | |
1412 | src_hash, | |
1413 | // Unused - the metadata decoder will construct | |
1414 | // a new SourceFile, filling in `external_src` properly | |
1415 | external_src: Lock::new(ExternalSource::Unneeded), | |
923072b8 | 1416 | lines: Lock::new(lines), |
5e7ed085 FG |
1417 | multibyte_chars, |
1418 | non_narrow_chars, | |
1419 | normalized_pos, | |
1420 | name_hash, | |
1421 | cnum, | |
1422 | } | |
3157f602 XL |
1423 | } |
1424 | } | |
1425 | ||
b7449926 | 1426 | impl fmt::Debug for SourceFile { |
9fa01778 | 1427 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
17df50a5 | 1428 | write!(fmt, "SourceFile({:?})", self.name) |
3157f602 XL |
1429 | } |
1430 | } | |
1431 | ||
b7449926 | 1432 | impl SourceFile { |
dfeec247 XL |
1433 | pub fn new( |
1434 | name: FileName, | |
dfeec247 XL |
1435 | mut src: String, |
1436 | start_pos: BytePos, | |
ba9703b0 | 1437 | hash_kind: SourceFileHashAlgorithm, |
74b04a01 | 1438 | ) -> Self { |
ba9703b0 XL |
1439 | // Compute the file hash before any normalization. |
1440 | let src_hash = SourceFileHash::new(hash_kind, &src); | |
e74abb32 | 1441 | let normalized_pos = normalize_src(&mut src, start_pos); |
041b39d2 | 1442 | |
ff7c6d11 | 1443 | let name_hash = { |
e74abb32 | 1444 | let mut hasher: StableHasher = StableHasher::new(); |
ff7c6d11 | 1445 | name.hash(&mut hasher); |
e74abb32 | 1446 | hasher.finish::<u128>() |
ff7c6d11 | 1447 | }; |
041b39d2 | 1448 | let end_pos = start_pos.to_usize() + src.len(); |
f035d41b | 1449 | assert!(end_pos <= u32::MAX as usize); |
041b39d2 | 1450 | |
8faf50e0 | 1451 | let (lines, multibyte_chars, non_narrow_chars) = |
a2a8927a | 1452 | analyze_source_file::analyze_source_file(&src, start_pos); |
8faf50e0 | 1453 | |
74b04a01 | 1454 | SourceFile { |
3b2f2976 | 1455 | name, |
0531ce1d | 1456 | src: Some(Lrc::new(src)), |
3b2f2976 | 1457 | src_hash, |
0531ce1d | 1458 | external_src: Lock::new(ExternalSource::Unneeded), |
3b2f2976 | 1459 | start_pos, |
041b39d2 | 1460 | end_pos: Pos::from_usize(end_pos), |
923072b8 | 1461 | lines: Lock::new(SourceFileLines::Lines(lines)), |
8faf50e0 XL |
1462 | multibyte_chars, |
1463 | non_narrow_chars, | |
e74abb32 | 1464 | normalized_pos, |
ff7c6d11 | 1465 | name_hash, |
ba9703b0 | 1466 | cnum: LOCAL_CRATE, |
74b04a01 | 1467 | } |
041b39d2 XL |
1468 | } |
1469 | ||
923072b8 FG |
1470 | pub fn lines<F, R>(&self, f: F) -> R |
1471 | where | |
1472 | F: FnOnce(&[BytePos]) -> R, | |
1473 | { | |
1474 | let mut guard = self.lines.borrow_mut(); | |
1475 | match &*guard { | |
1476 | SourceFileLines::Lines(lines) => f(lines), | |
1477 | SourceFileLines::Diffs(SourceFileDiffs { | |
1478 | mut line_start, | |
1479 | bytes_per_diff, | |
1480 | num_diffs, | |
1481 | raw_diffs, | |
1482 | }) => { | |
1483 | // Convert from "diffs" form to "lines" form. | |
1484 | let num_lines = num_diffs + 1; | |
1485 | let mut lines = Vec::with_capacity(num_lines); | |
1486 | lines.push(line_start); | |
1487 | ||
1488 | assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff); | |
1489 | match bytes_per_diff { | |
1490 | 1 => { | |
1491 | lines.extend(raw_diffs.into_iter().map(|&diff| { | |
1492 | line_start = line_start + BytePos(diff as u32); | |
1493 | line_start | |
1494 | })); | |
1495 | } | |
1496 | 2 => { | |
1497 | lines.extend((0..*num_diffs).map(|i| { | |
1498 | let pos = bytes_per_diff * i; | |
1499 | let bytes = [raw_diffs[pos], raw_diffs[pos + 1]]; | |
1500 | let diff = u16::from_le_bytes(bytes); | |
1501 | line_start = line_start + BytePos(diff as u32); | |
1502 | line_start | |
1503 | })); | |
1504 | } | |
1505 | 4 => { | |
1506 | lines.extend((0..*num_diffs).map(|i| { | |
1507 | let pos = bytes_per_diff * i; | |
1508 | let bytes = [ | |
1509 | raw_diffs[pos], | |
1510 | raw_diffs[pos + 1], | |
1511 | raw_diffs[pos + 2], | |
1512 | raw_diffs[pos + 3], | |
1513 | ]; | |
1514 | let diff = u32::from_le_bytes(bytes); | |
1515 | line_start = line_start + BytePos(diff); | |
1516 | line_start | |
1517 | })); | |
1518 | } | |
1519 | _ => unreachable!(), | |
1520 | } | |
1521 | let res = f(&lines); | |
1522 | *guard = SourceFileLines::Lines(lines); | |
1523 | res | |
1524 | } | |
1525 | } | |
1526 | } | |
1527 | ||
9fa01778 | 1528 | /// Returns the `BytePos` of the beginning of the current line. |
8faf50e0 XL |
1529 | pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { |
1530 | let line_index = self.lookup_line(pos).unwrap(); | |
923072b8 | 1531 | self.lines(|lines| lines[line_index]) |
94b46f34 XL |
1532 | } |
1533 | ||
041b39d2 XL |
1534 | /// Add externally loaded source. |
1535 | /// If the hash of the input doesn't match or no input is supplied via None, | |
1536 | /// it is interpreted as an error and the corresponding enum variant is set. | |
1537 | /// The return value signifies whether some kind of source is present. | |
1538 | pub fn add_external_src<F>(&self, get_src: F) -> bool | |
dfeec247 XL |
1539 | where |
1540 | F: FnOnce() -> Option<String>, | |
041b39d2 | 1541 | { |
ba9703b0 XL |
1542 | if matches!( |
1543 | *self.external_src.borrow(), | |
1544 | ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } | |
1545 | ) { | |
041b39d2 XL |
1546 | let src = get_src(); |
1547 | let mut external_src = self.external_src.borrow_mut(); | |
0531ce1d | 1548 | // Check that no-one else have provided the source while we were getting it |
ba9703b0 XL |
1549 | if let ExternalSource::Foreign { |
1550 | kind: src_kind @ ExternalSourceKind::AbsentOk, .. | |
1551 | } = &mut *external_src | |
1552 | { | |
1553 | if let Some(mut src) = src { | |
1554 | // The src_hash needs to be computed on the pre-normalized src. | |
1555 | if self.src_hash.matches(&src) { | |
1556 | normalize_src(&mut src, BytePos::from_usize(0)); | |
1557 | *src_kind = ExternalSourceKind::Present(Lrc::new(src)); | |
0531ce1d XL |
1558 | return true; |
1559 | } | |
1560 | } else { | |
ba9703b0 | 1561 | *src_kind = ExternalSourceKind::AbsentErr; |
041b39d2 | 1562 | } |
0531ce1d XL |
1563 | |
1564 | false | |
041b39d2 | 1565 | } else { |
0531ce1d | 1566 | self.src.is_some() || external_src.get_source().is_some() |
041b39d2 | 1567 | } |
041b39d2 XL |
1568 | } else { |
1569 | self.src.is_some() || self.external_src.borrow().get_source().is_some() | |
1570 | } | |
1571 | } | |
1572 | ||
9fa01778 | 1573 | /// Gets a line from the list of pre-computed line-beginnings. |
041b39d2 | 1574 | /// The line number here is 0-based. |
9fa01778 | 1575 | pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> { |
041b39d2 XL |
1576 | fn get_until_newline(src: &str, begin: usize) -> &str { |
1577 | // We can't use `lines.get(line_number+1)` because we might | |
1578 | // be parsing when we call this function and thus the current | |
1579 | // line is the last one we have line info for. | |
1580 | let slice = &src[begin..]; | |
1581 | match slice.find('\n') { | |
1582 | Some(e) => &slice[..e], | |
dfeec247 | 1583 | None => slice, |
3157f602 | 1584 | } |
041b39d2 XL |
1585 | } |
1586 | ||
0531ce1d | 1587 | let begin = { |
923072b8 FG |
1588 | let line = self.lines(|lines| lines.get(line_number).copied())?; |
1589 | let begin: BytePos = line - self.start_pos; | |
0531ce1d | 1590 | begin.to_usize() |
041b39d2 | 1591 | }; |
041b39d2 XL |
1592 | |
1593 | if let Some(ref src) = self.src { | |
1594 | Some(Cow::from(get_until_newline(src, begin))) | |
1595 | } else if let Some(src) = self.external_src.borrow().get_source() { | |
1596 | Some(Cow::Owned(String::from(get_until_newline(src, begin)))) | |
1597 | } else { | |
1598 | None | |
3157f602 XL |
1599 | } |
1600 | } | |
1601 | ||
3157f602 | 1602 | pub fn is_real_file(&self) -> bool { |
ff7c6d11 | 1603 | self.name.is_real() |
3157f602 XL |
1604 | } |
1605 | ||
1606 | pub fn is_imported(&self) -> bool { | |
1607 | self.src.is_none() | |
1608 | } | |
1609 | ||
1610 | pub fn count_lines(&self) -> usize { | |
923072b8 | 1611 | self.lines(|lines| lines.len()) |
3157f602 | 1612 | } |
9e0c209e | 1613 | |
9fa01778 | 1614 | /// Finds the line containing the given position. The return value is the |
0731742a | 1615 | /// index into the `lines` array of this `SourceFile`, not the 1-based line |
b7449926 | 1616 | /// number. If the source_file is empty or the position is located before the |
0731742a | 1617 | /// first line, `None` is returned. |
9e0c209e | 1618 | pub fn lookup_line(&self, pos: BytePos) -> Option<usize> { |
923072b8 | 1619 | self.lines(|lines| match lines.binary_search(&pos) { |
136023e0 XL |
1620 | Ok(idx) => Some(idx), |
1621 | Err(0) => None, | |
1622 | Err(idx) => Some(idx - 1), | |
923072b8 | 1623 | }) |
9e0c209e SL |
1624 | } |
1625 | ||
29967ef6 XL |
1626 | pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> { |
1627 | if self.is_empty() { | |
1628 | return self.start_pos..self.end_pos; | |
9e0c209e SL |
1629 | } |
1630 | ||
923072b8 FG |
1631 | self.lines(|lines| { |
1632 | assert!(line_index < lines.len()); | |
1633 | if line_index == (lines.len() - 1) { | |
1634 | lines[line_index]..self.end_pos | |
1635 | } else { | |
1636 | lines[line_index]..lines[line_index + 1] | |
1637 | } | |
1638 | }) | |
9e0c209e | 1639 | } |
ff7c6d11 | 1640 | |
29967ef6 XL |
1641 | /// Returns whether or not the file contains the given `SourceMap` byte |
1642 | /// position. The position one past the end of the file is considered to be | |
1643 | /// contained by the file. This implies that files for which `is_empty` | |
1644 | /// returns true still contain one byte position according to this function. | |
ff7c6d11 XL |
1645 | #[inline] |
1646 | pub fn contains(&self, byte_pos: BytePos) -> bool { | |
1647 | byte_pos >= self.start_pos && byte_pos <= self.end_pos | |
1648 | } | |
e74abb32 | 1649 | |
29967ef6 XL |
1650 | #[inline] |
1651 | pub fn is_empty(&self) -> bool { | |
1652 | self.start_pos == self.end_pos | |
1653 | } | |
1654 | ||
e74abb32 XL |
1655 | /// Calculates the original byte position relative to the start of the file |
1656 | /// based on the given byte position. | |
1657 | pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos { | |
e74abb32 XL |
1658 | // Diff before any records is 0. Otherwise use the previously recorded |
1659 | // diff as that applies to the following characters until a new diff | |
1660 | // is recorded. | |
dfeec247 | 1661 | let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) { |
e74abb32 XL |
1662 | Ok(i) => self.normalized_pos[i].diff, |
1663 | Err(i) if i == 0 => 0, | |
dfeec247 | 1664 | Err(i) => self.normalized_pos[i - 1].diff, |
e74abb32 XL |
1665 | }; |
1666 | ||
1667 | BytePos::from_u32(pos.0 - self.start_pos.0 + diff) | |
1668 | } | |
29967ef6 XL |
1669 | |
1670 | /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. | |
1671 | pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { | |
1672 | // The number of extra bytes due to multibyte chars in the `SourceFile`. | |
1673 | let mut total_extra_bytes = 0; | |
1674 | ||
1675 | for mbc in self.multibyte_chars.iter() { | |
1676 | debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); | |
1677 | if mbc.pos < bpos { | |
1678 | // Every character is at least one byte, so we only | |
1679 | // count the actual extra bytes. | |
1680 | total_extra_bytes += mbc.bytes as u32 - 1; | |
1681 | // We should never see a byte position in the middle of a | |
1682 | // character. | |
1683 | assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); | |
1684 | } else { | |
1685 | break; | |
1686 | } | |
1687 | } | |
1688 | ||
1689 | assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); | |
1690 | CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) | |
1691 | } | |
1692 | ||
1693 | /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a | |
1694 | /// given `BytePos`. | |
1695 | pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { | |
1696 | let chpos = self.bytepos_to_file_charpos(pos); | |
1697 | match self.lookup_line(pos) { | |
1698 | Some(a) => { | |
1699 | let line = a + 1; // Line numbers start at 1 | |
923072b8 | 1700 | let linebpos = self.lines(|lines| lines[a]); |
29967ef6 XL |
1701 | let linechpos = self.bytepos_to_file_charpos(linebpos); |
1702 | let col = chpos - linechpos; | |
1703 | debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); | |
1704 | debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); | |
1705 | debug!("byte is on line: {}", line); | |
1706 | assert!(chpos >= linechpos); | |
1707 | (line, col) | |
1708 | } | |
1709 | None => (0, chpos), | |
1710 | } | |
1711 | } | |
1712 | ||
1713 | /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) | |
1714 | /// column offset when displayed, for a given `BytePos`. | |
1715 | pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { | |
1716 | let (line, col_or_chpos) = self.lookup_file_pos(pos); | |
1717 | if line > 0 { | |
1718 | let col = col_or_chpos; | |
923072b8 | 1719 | let linebpos = self.lines(|lines| lines[line - 1]); |
29967ef6 XL |
1720 | let col_display = { |
1721 | let start_width_idx = self | |
1722 | .non_narrow_chars | |
1723 | .binary_search_by_key(&linebpos, |x| x.pos()) | |
1724 | .unwrap_or_else(|x| x); | |
1725 | let end_width_idx = self | |
1726 | .non_narrow_chars | |
1727 | .binary_search_by_key(&pos, |x| x.pos()) | |
1728 | .unwrap_or_else(|x| x); | |
1729 | let special_chars = end_width_idx - start_width_idx; | |
1730 | let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] | |
1731 | .iter() | |
1732 | .map(|x| x.width()) | |
1733 | .sum(); | |
1734 | col.0 - special_chars + non_narrow | |
1735 | }; | |
1736 | (line, col, col_display) | |
1737 | } else { | |
1738 | let chpos = col_or_chpos; | |
1739 | let col_display = { | |
1740 | let end_width_idx = self | |
1741 | .non_narrow_chars | |
1742 | .binary_search_by_key(&pos, |x| x.pos()) | |
1743 | .unwrap_or_else(|x| x); | |
1744 | let non_narrow: usize = | |
1745 | self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); | |
1746 | chpos.0 - end_width_idx + non_narrow | |
1747 | }; | |
1748 | (0, chpos, col_display) | |
1749 | } | |
1750 | } | |
e74abb32 XL |
1751 | } |
1752 | ||
1753 | /// Normalizes the source code and records the normalizations. | |
1754 | fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> { | |
1755 | let mut normalized_pos = vec![]; | |
1756 | remove_bom(src, &mut normalized_pos); | |
1757 | normalize_newlines(src, &mut normalized_pos); | |
1758 | ||
1759 | // Offset all the positions by start_pos to match the final file positions. | |
1760 | for np in &mut normalized_pos { | |
1761 | np.pos.0 += start_pos.0; | |
1762 | } | |
1763 | ||
1764 | normalized_pos | |
3157f602 XL |
1765 | } |
1766 | ||
9fa01778 | 1767 | /// Removes UTF-8 BOM, if any. |
e74abb32 | 1768 | fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) { |
29967ef6 | 1769 | if src.starts_with('\u{feff}') { |
041b39d2 | 1770 | src.drain(..3); |
e74abb32 XL |
1771 | normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); |
1772 | } | |
1773 | } | |
1774 | ||
e74abb32 XL |
1775 | /// Replaces `\r\n` with `\n` in-place in `src`. |
1776 | /// | |
5869c6ff | 1777 | /// Returns error if there's a lone `\r` in the string. |
e74abb32 XL |
1778 | fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) { |
1779 | if !src.as_bytes().contains(&b'\r') { | |
1780 | return; | |
1781 | } | |
1782 | ||
1783 | // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. | |
1784 | // While we *can* call `as_mut_vec` and do surgery on the live string | |
1785 | // directly, let's rather steal the contents of `src`. This makes the code | |
1786 | // safe even if a panic occurs. | |
1787 | ||
1788 | let mut buf = std::mem::replace(src, String::new()).into_bytes(); | |
1789 | let mut gap_len = 0; | |
1790 | let mut tail = buf.as_mut_slice(); | |
1791 | let mut cursor = 0; | |
1792 | let original_gap = normalized_pos.last().map_or(0, |l| l.diff); | |
1793 | loop { | |
1794 | let idx = match find_crlf(&tail[gap_len..]) { | |
1795 | None => tail.len(), | |
1796 | Some(idx) => idx + gap_len, | |
1797 | }; | |
1798 | tail.copy_within(gap_len..idx, 0); | |
1799 | tail = &mut tail[idx - gap_len..]; | |
1800 | if tail.len() == gap_len { | |
1801 | break; | |
1802 | } | |
1803 | cursor += idx - gap_len; | |
1804 | gap_len += 1; | |
1805 | normalized_pos.push(NormalizedPos { | |
1806 | pos: BytePos::from_usize(cursor + 1), | |
1807 | diff: original_gap + gap_len as u32, | |
1808 | }); | |
1809 | } | |
1810 | ||
1811 | // Account for removed `\r`. | |
1812 | // After `set_len`, `buf` is guaranteed to contain utf-8 again. | |
1813 | let new_len = buf.len() - gap_len; | |
1814 | unsafe { | |
1815 | buf.set_len(new_len); | |
1816 | *src = String::from_utf8_unchecked(buf); | |
1817 | } | |
1818 | ||
1819 | fn find_crlf(src: &[u8]) -> Option<usize> { | |
1820 | let mut search_idx = 0; | |
1821 | while let Some(idx) = find_cr(&src[search_idx..]) { | |
1822 | if src[search_idx..].get(idx + 1) != Some(&b'\n') { | |
1823 | search_idx += idx + 1; | |
1824 | continue; | |
1825 | } | |
1826 | return Some(search_idx + idx); | |
1827 | } | |
1828 | None | |
1829 | } | |
1830 | ||
1831 | fn find_cr(src: &[u8]) -> Option<usize> { | |
1832 | src.iter().position(|&b| b == b'\r') | |
041b39d2 XL |
1833 | } |
1834 | } | |
1835 | ||
3157f602 XL |
1836 | // _____________________________________________________________________________ |
1837 | // Pos, BytePos, CharPos | |
1838 | // | |
1839 | ||
1840 | pub trait Pos { | |
1841 | fn from_usize(n: usize) -> Self; | |
1842 | fn to_usize(&self) -> usize; | |
8faf50e0 XL |
1843 | fn from_u32(n: u32) -> Self; |
1844 | fn to_u32(&self) -> u32; | |
3157f602 XL |
1845 | } |
1846 | ||
1b1a35ee XL |
1847 | macro_rules! impl_pos { |
1848 | ( | |
1849 | $( | |
1850 | $(#[$attr:meta])* | |
1851 | $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); | |
1852 | )* | |
1853 | ) => { | |
1854 | $( | |
1855 | $(#[$attr])* | |
1856 | $vis struct $ident($inner_vis $inner_ty); | |
1857 | ||
1858 | impl Pos for $ident { | |
1859 | #[inline(always)] | |
1860 | fn from_usize(n: usize) -> $ident { | |
1861 | $ident(n as $inner_ty) | |
1862 | } | |
3157f602 | 1863 | |
1b1a35ee XL |
1864 | #[inline(always)] |
1865 | fn to_usize(&self) -> usize { | |
1866 | self.0 as usize | |
1867 | } | |
3157f602 | 1868 | |
1b1a35ee XL |
1869 | #[inline(always)] |
1870 | fn from_u32(n: u32) -> $ident { | |
1871 | $ident(n as $inner_ty) | |
1872 | } | |
83c7162d | 1873 | |
1b1a35ee XL |
1874 | #[inline(always)] |
1875 | fn to_u32(&self) -> u32 { | |
1876 | self.0 as u32 | |
1877 | } | |
1878 | } | |
8faf50e0 | 1879 | |
1b1a35ee XL |
1880 | impl Add for $ident { |
1881 | type Output = $ident; | |
8faf50e0 | 1882 | |
1b1a35ee XL |
1883 | #[inline(always)] |
1884 | fn add(self, rhs: $ident) -> $ident { | |
1885 | $ident(self.0 + rhs.0) | |
1886 | } | |
1887 | } | |
3157f602 | 1888 | |
1b1a35ee XL |
1889 | impl Sub for $ident { |
1890 | type Output = $ident; | |
3157f602 | 1891 | |
1b1a35ee XL |
1892 | #[inline(always)] |
1893 | fn sub(self, rhs: $ident) -> $ident { | |
1894 | $ident(self.0 - rhs.0) | |
1895 | } | |
1896 | } | |
1897 | )* | |
1898 | }; | |
3157f602 XL |
1899 | } |
1900 | ||
1b1a35ee | 1901 | impl_pos! { |
5869c6ff XL |
1902 | /// A byte offset. |
1903 | /// | |
1904 | /// Keep this small (currently 32-bits), as AST contains a lot of them. | |
1b1a35ee XL |
1905 | #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] |
1906 | pub struct BytePos(pub u32); | |
1907 | ||
5869c6ff XL |
1908 | /// A character offset. |
1909 | /// | |
1910 | /// Because of multibyte UTF-8 characters, a byte offset | |
1911 | /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] | |
1b1a35ee XL |
1912 | /// values to `CharPos` values as necessary. |
1913 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] | |
1914 | pub struct CharPos(pub usize); | |
3157f602 XL |
1915 | } |
1916 | ||
923072b8 FG |
1917 | impl<S: Encoder> Encodable<S> for BytePos { |
1918 | fn encode(&self, s: &mut S) { | |
1919 | s.emit_u32(self.0); | |
3157f602 XL |
1920 | } |
1921 | } | |
1922 | ||
923072b8 | 1923 | impl<D: Decoder> Decodable<D> for BytePos { |
5099ac24 FG |
1924 | fn decode(d: &mut D) -> BytePos { |
1925 | BytePos(d.read_u32()) | |
3157f602 XL |
1926 | } |
1927 | } | |
1928 | ||
3157f602 | 1929 | // _____________________________________________________________________________ |
48663c56 | 1930 | // Loc, SourceFileAndLine, SourceFileAndBytePos |
3157f602 XL |
1931 | // |
1932 | ||
0731742a | 1933 | /// A source code location used for error reporting. |
5bcae85e | 1934 | #[derive(Debug, Clone)] |
3157f602 | 1935 | pub struct Loc { |
0731742a | 1936 | /// Information about the original source. |
b7449926 | 1937 | pub file: Lrc<SourceFile>, |
0731742a | 1938 | /// The (1-based) line number. |
3157f602 | 1939 | pub line: usize, |
0731742a | 1940 | /// The (0-based) column offset. |
abe05a73 | 1941 | pub col: CharPos, |
0731742a | 1942 | /// The (0-based) column offset when displayed. |
abe05a73 | 1943 | pub col_display: usize, |
3157f602 XL |
1944 | } |
1945 | ||
0731742a | 1946 | // Used to be structural records. |
3157f602 | 1947 | #[derive(Debug)] |
dfeec247 XL |
1948 | pub struct SourceFileAndLine { |
1949 | pub sf: Lrc<SourceFile>, | |
3c0e092e | 1950 | /// Index of line, starting from 0. |
dfeec247 XL |
1951 | pub line: usize, |
1952 | } | |
3157f602 | 1953 | #[derive(Debug)] |
dfeec247 XL |
1954 | pub struct SourceFileAndBytePos { |
1955 | pub sf: Lrc<SourceFile>, | |
1956 | pub pos: BytePos, | |
1957 | } | |
3157f602 XL |
1958 | |
1959 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] | |
1960 | pub struct LineInfo { | |
1961 | /// Index of line, starting from 0. | |
1962 | pub line_index: usize, | |
1963 | ||
1964 | /// Column in line where span begins, starting from 0. | |
1965 | pub start_col: CharPos, | |
1966 | ||
1967 | /// Column in line where span ends, starting from 0, exclusive. | |
1968 | pub end_col: CharPos, | |
1969 | } | |
1970 | ||
1971 | pub struct FileLines { | |
b7449926 | 1972 | pub file: Lrc<SourceFile>, |
dfeec247 | 1973 | pub lines: Vec<LineInfo>, |
3157f602 XL |
1974 | } |
1975 | ||
c295e0f8 | 1976 | pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_))); |
3157f602 XL |
1977 | |
1978 | // _____________________________________________________________________________ | |
a1dfa0c6 | 1979 | // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions |
3157f602 XL |
1980 | // |
1981 | ||
1982 | pub type FileLinesResult = Result<FileLines, SpanLinesError>; | |
1983 | ||
1984 | #[derive(Clone, PartialEq, Eq, Debug)] | |
1985 | pub enum SpanLinesError { | |
3157f602 XL |
1986 | DistinctSources(DistinctSources), |
1987 | } | |
1988 | ||
1989 | #[derive(Clone, PartialEq, Eq, Debug)] | |
1990 | pub enum SpanSnippetError { | |
1991 | IllFormedSpan(Span), | |
1992 | DistinctSources(DistinctSources), | |
a1dfa0c6 | 1993 | MalformedForSourcemap(MalformedSourceMapPositions), |
dfeec247 | 1994 | SourceNotAvailable { filename: FileName }, |
3157f602 XL |
1995 | } |
1996 | ||
1997 | #[derive(Clone, PartialEq, Eq, Debug)] | |
1998 | pub struct DistinctSources { | |
ff7c6d11 | 1999 | pub begin: (FileName, BytePos), |
dfeec247 | 2000 | pub end: (FileName, BytePos), |
3157f602 XL |
2001 | } |
2002 | ||
2003 | #[derive(Clone, PartialEq, Eq, Debug)] | |
a1dfa0c6 | 2004 | pub struct MalformedSourceMapPositions { |
ff7c6d11 | 2005 | pub name: FileName, |
3157f602 XL |
2006 | pub source_len: usize, |
2007 | pub begin_pos: BytePos, | |
dfeec247 | 2008 | pub end_pos: BytePos, |
3157f602 XL |
2009 | } |
2010 | ||
416331ca | 2011 | /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. |
dc9dc135 XL |
2012 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
2013 | pub struct InnerSpan { | |
2014 | pub start: usize, | |
2015 | pub end: usize, | |
2016 | } | |
2017 | ||
2018 | impl InnerSpan { | |
2019 | pub fn new(start: usize, end: usize) -> InnerSpan { | |
2020 | InnerSpan { start, end } | |
2021 | } | |
2022 | } | |
2023 | ||
60c5eb7d | 2024 | /// Requirements for a `StableHashingContext` to be used in this crate. |
5869c6ff XL |
2025 | /// |
2026 | /// This is a hack to allow using the [`HashStable_Generic`] derive macro | |
2027 | /// instead of implementing everything in rustc_middle. | |
60c5eb7d | 2028 | pub trait HashStableContext { |
136023e0 | 2029 | fn def_path_hash(&self, def_id: DefId) -> DefPathHash; |
3dfed10e | 2030 | fn hash_spans(&self) -> bool; |
5099ac24 FG |
2031 | /// Accesses `sess.opts.debugging_opts.incremental_ignore_spans` since |
2032 | /// we don't have easy access to a `Session` | |
2033 | fn debug_opts_incremental_ignore_spans(&self) -> bool; | |
c295e0f8 | 2034 | fn def_span(&self, def_id: LocalDefId) -> Span; |
5869c6ff XL |
2035 | fn span_data_to_lines_and_cols( |
2036 | &mut self, | |
2037 | span: &SpanData, | |
2038 | ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>; | |
5099ac24 | 2039 | fn hashing_controls(&self) -> HashingControls; |
60c5eb7d XL |
2040 | } |
2041 | ||
2042 | impl<CTX> HashStable<CTX> for Span | |
dfeec247 XL |
2043 | where |
2044 | CTX: HashStableContext, | |
60c5eb7d XL |
2045 | { |
2046 | /// Hashes a span in a stable way. We can't directly hash the span's `BytePos` | |
2047 | /// fields (that would be similar to hashing pointers, since those are just | |
2048 | /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) | |
2049 | /// triple, which stays the same even if the containing `SourceFile` has moved | |
2050 | /// within the `SourceMap`. | |
5869c6ff | 2051 | /// |
60c5eb7d XL |
2052 | /// Also note that we are hashing byte offsets for the column, not unicode |
2053 | /// codepoint offsets. For the purpose of the hash that's sufficient. | |
2054 | /// Also, hashing filenames is expensive so we avoid doing it twice when the | |
2055 | /// span starts and ends in the same file, which is almost always the case. | |
2056 | fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { | |
2057 | const TAG_VALID_SPAN: u8 = 0; | |
2058 | const TAG_INVALID_SPAN: u8 = 1; | |
c295e0f8 | 2059 | const TAG_RELATIVE_SPAN: u8 = 2; |
60c5eb7d XL |
2060 | |
2061 | if !ctx.hash_spans() { | |
dfeec247 | 2062 | return; |
60c5eb7d XL |
2063 | } |
2064 | ||
c295e0f8 XL |
2065 | let span = self.data_untracked(); |
2066 | span.ctxt.hash_stable(ctx, hasher); | |
2067 | span.parent.hash_stable(ctx, hasher); | |
6a06907d | 2068 | |
c295e0f8 | 2069 | if span.is_dummy() { |
29967ef6 | 2070 | Hash::hash(&TAG_INVALID_SPAN, hasher); |
3dfed10e | 2071 | return; |
60c5eb7d XL |
2072 | } |
2073 | ||
c295e0f8 XL |
2074 | if let Some(parent) = span.parent { |
2075 | let def_span = ctx.def_span(parent).data_untracked(); | |
2076 | if def_span.contains(span) { | |
2077 | // This span is enclosed in a definition: only hash the relative position. | |
2078 | Hash::hash(&TAG_RELATIVE_SPAN, hasher); | |
2079 | (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); | |
2080 | (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); | |
2081 | return; | |
2082 | } | |
2083 | } | |
2084 | ||
60c5eb7d XL |
2085 | // If this is not an empty or invalid span, we want to hash the last |
2086 | // position that belongs to it, as opposed to hashing the first | |
2087 | // position past it. | |
5e7ed085 FG |
2088 | let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else { |
2089 | Hash::hash(&TAG_INVALID_SPAN, hasher); | |
2090 | return; | |
29967ef6 XL |
2091 | }; |
2092 | ||
2093 | Hash::hash(&TAG_VALID_SPAN, hasher); | |
60c5eb7d XL |
2094 | // We truncate the stable ID hash and line and column numbers. The chances |
2095 | // of causing a collision this way should be minimal. | |
5869c6ff | 2096 | Hash::hash(&(file.name_hash as u64), hasher); |
29967ef6 XL |
2097 | |
2098 | // Hash both the length and the end location (line/column) of a span. If we | |
2099 | // hash only the length, for example, then two otherwise equal spans with | |
2100 | // different end locations will have the same hash. This can cause a problem | |
2101 | // during incremental compilation wherein a previous result for a query that | |
2102 | // depends on the end location of a span will be incorrectly reused when the | |
2103 | // end location of the span it depends on has changed (see issue #74890). A | |
2104 | // similar analysis applies if some query depends specifically on the length | |
2105 | // of the span, but we only hash the end location. So hash both. | |
2106 | ||
2107 | let col_lo_trunc = (col_lo.0 as u64) & 0xFF; | |
2108 | let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; | |
2109 | let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; | |
2110 | let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; | |
2111 | let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; | |
2112 | let len = (span.hi - span.lo).0; | |
2113 | Hash::hash(&col_line, hasher); | |
2114 | Hash::hash(&len, hasher); | |
3dfed10e XL |
2115 | } |
2116 | } |