From a06baa56b95674fc626b3c3fd680d6a65357fe60 Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sun, 22 Dec 2019 17:42:04 -0500 Subject: Format the world --- src/libsyntax_pos/analyze_source_file.rs | 42 ++-- src/libsyntax_pos/analyze_source_file/tests.rs | 47 ++-- src/libsyntax_pos/caching_source_map_view.rs | 27 ++- src/libsyntax_pos/edition.rs | 20 +- src/libsyntax_pos/hygiene.rs | 154 ++++++++----- src/libsyntax_pos/lib.rs | 298 ++++++++++++------------ src/libsyntax_pos/source_map.rs | 301 ++++++++++++------------- src/libsyntax_pos/source_map/tests.rs | 37 ++- src/libsyntax_pos/span_encoding.rs | 4 +- src/libsyntax_pos/symbol.rs | 55 ++--- src/libsyntax_pos/tests.rs | 9 +- 11 files changed, 502 insertions(+), 492 deletions(-) (limited to 'src/libsyntax_pos') diff --git a/src/libsyntax_pos/analyze_source_file.rs b/src/libsyntax_pos/analyze_source_file.rs index e01a14f14a8..b4beb3dc376 100644 --- a/src/libsyntax_pos/analyze_source_file.rs +++ b/src/libsyntax_pos/analyze_source_file.rs @@ -1,5 +1,5 @@ -use unicode_width::UnicodeWidthChar; use super::*; +use unicode_width::UnicodeWidthChar; #[cfg(test)] mod tests; @@ -11,19 +11,20 @@ mod tests; /// is detected at runtime. pub fn analyze_source_file( src: &str, - source_file_start_pos: BytePos) - -> (Vec, Vec, Vec) -{ + source_file_start_pos: BytePos, +) -> (Vec, Vec, Vec) { let mut lines = vec![source_file_start_pos]; let mut multi_byte_chars = vec![]; let mut non_narrow_chars = vec![]; // Calls the right implementation, depending on hardware support available. - analyze_source_file_dispatch(src, - source_file_start_pos, - &mut lines, - &mut multi_byte_chars, - &mut non_narrow_chars); + analyze_source_file_dispatch( + src, + source_file_start_pos, + &mut lines, + &mut multi_byte_chars, + &mut non_narrow_chars, + ); // The code above optimistically registers a new line *after* each \n // it encounters. If that point is already outside the source_file, remove @@ -203,14 +204,14 @@ cfg_if::cfg_if! { // `scan_len` determines the number of bytes in `src` to scan. Note that the // function can read past `scan_len` if a multi-byte character start within the // range but extends past it. The overflow is returned by the function. -fn analyze_source_file_generic(src: &str, - scan_len: usize, - output_offset: BytePos, - lines: &mut Vec, - multi_byte_chars: &mut Vec, - non_narrow_chars: &mut Vec) - -> usize -{ +fn analyze_source_file_generic( + src: &str, + scan_len: usize, + output_offset: BytePos, + lines: &mut Vec, + multi_byte_chars: &mut Vec, + non_narrow_chars: &mut Vec, +) -> usize { assert!(src.len() >= scan_len); let mut i = 0; let src_bytes = src.as_bytes(); @@ -252,11 +253,8 @@ fn analyze_source_file_generic(src: &str, let pos = BytePos::from_usize(i) + output_offset; if char_len > 1 { - assert!(char_len >=2 && char_len <= 4); - let mbc = MultiByteChar { - pos, - bytes: char_len as u8, - }; + assert!(char_len >= 2 && char_len <= 4); + let mbc = MultiByteChar { pos, bytes: char_len as u8 }; multi_byte_chars.push(mbc); } diff --git a/src/libsyntax_pos/analyze_source_file/tests.rs b/src/libsyntax_pos/analyze_source_file/tests.rs index fd485a7f3a9..cb418a4bdaf 100644 --- a/src/libsyntax_pos/analyze_source_file/tests.rs +++ b/src/libsyntax_pos/analyze_source_file/tests.rs @@ -6,40 +6,31 @@ macro_rules! test { source_file_start_pos: $source_file_start_pos:expr, lines: $lines:expr, multi_byte_chars: $multi_byte_chars:expr, - non_narrow_chars: $non_narrow_chars:expr,) => ( + non_narrow_chars: $non_narrow_chars:expr,) => { + #[test] + fn $test_name() { + let (lines, multi_byte_chars, non_narrow_chars) = + analyze_source_file($text, BytePos($source_file_start_pos)); - #[test] - fn $test_name() { + let expected_lines: Vec = $lines.into_iter().map(|pos| BytePos(pos)).collect(); - let (lines, multi_byte_chars, non_narrow_chars) = - analyze_source_file($text, BytePos($source_file_start_pos)); + assert_eq!(lines, expected_lines); - let expected_lines: Vec = $lines - .into_iter() - .map(|pos| BytePos(pos)) - .collect(); + let expected_mbcs: Vec = $multi_byte_chars + .into_iter() + .map(|(pos, bytes)| MultiByteChar { pos: BytePos(pos), bytes }) + .collect(); - assert_eq!(lines, expected_lines); + assert_eq!(multi_byte_chars, expected_mbcs); - let expected_mbcs: Vec = $multi_byte_chars - .into_iter() - .map(|(pos, bytes)| MultiByteChar { - pos: BytePos(pos), - bytes, - }) - .collect(); + let expected_nncs: Vec = $non_narrow_chars + .into_iter() + .map(|(pos, width)| NonNarrowChar::new(BytePos(pos), width)) + .collect(); - assert_eq!(multi_byte_chars, expected_mbcs); - - let expected_nncs: Vec = $non_narrow_chars - .into_iter() - .map(|(pos, width)| { - NonNarrowChar::new(BytePos(pos), width) - }) - .collect(); - - assert_eq!(non_narrow_chars, expected_nncs); - }) + assert_eq!(non_narrow_chars, expected_nncs); + } + }; } test!( diff --git a/src/libsyntax_pos/caching_source_map_view.rs b/src/libsyntax_pos/caching_source_map_view.rs index 82371730876..c329f2225b0 100644 --- a/src/libsyntax_pos/caching_source_map_view.rs +++ b/src/libsyntax_pos/caching_source_map_view.rs @@ -1,6 +1,6 @@ -use rustc_data_structures::sync::Lrc; use crate::source_map::SourceMap; use crate::{BytePos, SourceFile}; +use rustc_data_structures::sync::Lrc; #[derive(Clone)] struct CacheEntry { @@ -39,9 +39,10 @@ impl<'cm> CachingSourceMapView<'cm> { } } - pub fn byte_pos_to_line_and_col(&mut self, - pos: BytePos) - -> Option<(Lrc, usize, BytePos)> { + pub fn byte_pos_to_line_and_col( + &mut self, + pos: BytePos, + ) -> Option<(Lrc, usize, BytePos)> { self.time_stamp += 1; // Check if the position is in one of the cached lines @@ -49,15 +50,17 @@ impl<'cm> CachingSourceMapView<'cm> { if pos >= cache_entry.line_start && pos < cache_entry.line_end { cache_entry.time_stamp = self.time_stamp; - return Some((cache_entry.file.clone(), - cache_entry.line_number, - pos - cache_entry.line_start)); + return Some(( + cache_entry.file.clone(), + cache_entry.line_number, + pos - cache_entry.line_start, + )); } } // No cache hit ... let mut oldest = 0; - for index in 1 .. self.line_cache.len() { + for index in 1..self.line_cache.len() { if self.line_cache[index].time_stamp < self.line_cache[oldest].time_stamp { oldest = index; } @@ -96,8 +99,10 @@ impl<'cm> CachingSourceMapView<'cm> { cache_entry.line_end = line_bounds.1; cache_entry.time_stamp = self.time_stamp; - return Some((cache_entry.file.clone(), - cache_entry.line_number, - pos - cache_entry.line_start)); + return Some(( + cache_entry.file.clone(), + cache_entry.line_number, + pos - cache_entry.line_start, + )); } } diff --git a/src/libsyntax_pos/edition.rs b/src/libsyntax_pos/edition.rs index 727aad546f5..3017191563b 100644 --- a/src/libsyntax_pos/edition.rs +++ b/src/libsyntax_pos/edition.rs @@ -1,20 +1,28 @@ -use crate::symbol::{Symbol, sym}; +use crate::symbol::{sym, Symbol}; use std::fmt; use std::str::FromStr; use rustc_macros::HashStable_Generic; /// The edition of the compiler (RFC 2052) -#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Debug, - RustcEncodable, RustcDecodable, Eq, HashStable_Generic)] +#[derive( + Clone, + Copy, + Hash, + PartialEq, + PartialOrd, + Debug, + RustcEncodable, + RustcDecodable, + Eq, + HashStable_Generic +)] pub enum Edition { // editions must be kept in order, oldest to newest - /// The 2015 edition Edition2015, /// The 2018 edition Edition2018, - // when adding new editions, be sure to update: // // - Update the `ALL_EDITIONS` const @@ -69,7 +77,7 @@ impl FromStr for Edition { match s { "2015" => Ok(Edition::Edition2015), "2018" => Ok(Edition::Edition2018), - _ => Err(()) + _ => Err(()), } } } diff --git a/src/libsyntax_pos/hygiene.rs b/src/libsyntax_pos/hygiene.rs index 3c1d19256e9..fd1f07c743b 100644 --- a/src/libsyntax_pos/hygiene.rs +++ b/src/libsyntax_pos/hygiene.rs @@ -25,15 +25,15 @@ // because getting it wrong can lead to nested `HygieneData::with` calls that // trigger runtime aborts. (Fortunately these are obvious and easy to fix.) -use crate::GLOBALS; -use crate::{Span, DUMMY_SP}; use crate::edition::Edition; use crate::symbol::{kw, sym, Symbol}; +use crate::GLOBALS; +use crate::{Span, DUMMY_SP}; -use rustc_macros::HashStable_Generic; -use rustc_serialize::{Encodable, Decodable, Encoder, Decoder}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; +use rustc_macros::HashStable_Generic; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::fmt; /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks". @@ -59,8 +59,18 @@ pub struct ExpnId(u32); /// A property of a macro expansion that determines how identifiers /// produced by that expansion are resolved. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, - RustcEncodable, RustcDecodable, HashStable_Generic)] +#[derive( + Copy, + Clone, + PartialEq, + Eq, + PartialOrd, + Hash, + Debug, + RustcEncodable, + RustcDecodable, + HashStable_Generic +)] pub enum Transparency { /// Identifier produced by a transparent expansion is always resolved at call-site. /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this. @@ -176,8 +186,7 @@ impl HygieneData { } fn expn_data(&self, expn_id: ExpnId) -> &ExpnData { - self.expn_data[expn_id.0 as usize].as_ref() - .expect("no expansion data for an expansion ID") + self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID") } fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool { @@ -243,7 +252,10 @@ impl HygieneData { } fn apply_mark( - &mut self, ctxt: SyntaxContext, expn_id: ExpnId, transparency: Transparency + &mut self, + ctxt: SyntaxContext, + expn_id: ExpnId, + transparency: Transparency, ) -> SyntaxContext { assert_ne!(expn_id, ExpnId::root()); if transparency == Transparency::Opaque { @@ -277,7 +289,10 @@ impl HygieneData { } fn apply_mark_internal( - &mut self, ctxt: SyntaxContext, expn_id: ExpnId, transparency: Transparency + &mut self, + ctxt: SyntaxContext, + expn_id: ExpnId, + transparency: Transparency, ) -> SyntaxContext { let syntax_context_data = &mut self.syntax_context_data; let mut opaque = syntax_context_data[ctxt.0 as usize].opaque; @@ -286,38 +301,41 @@ impl HygieneData { if transparency >= Transparency::Opaque { let parent = opaque; - opaque = *self.syntax_context_map.entry((parent, expn_id, transparency)) - .or_insert_with(|| { - let new_opaque = SyntaxContext(syntax_context_data.len() as u32); - syntax_context_data.push(SyntaxContextData { - outer_expn: expn_id, - outer_transparency: transparency, - parent, - opaque: new_opaque, - opaque_and_semitransparent: new_opaque, - dollar_crate_name: kw::DollarCrate, + opaque = *self + .syntax_context_map + .entry((parent, expn_id, transparency)) + .or_insert_with(|| { + let new_opaque = SyntaxContext(syntax_context_data.len() as u32); + syntax_context_data.push(SyntaxContextData { + outer_expn: expn_id, + outer_transparency: transparency, + parent, + opaque: new_opaque, + opaque_and_semitransparent: new_opaque, + dollar_crate_name: kw::DollarCrate, + }); + new_opaque }); - new_opaque - }); } if transparency >= Transparency::SemiTransparent { let parent = opaque_and_semitransparent; - opaque_and_semitransparent = - *self.syntax_context_map.entry((parent, expn_id, transparency)) - .or_insert_with(|| { - let new_opaque_and_semitransparent = - SyntaxContext(syntax_context_data.len() as u32); - syntax_context_data.push(SyntaxContextData { - outer_expn: expn_id, - outer_transparency: transparency, - parent, - opaque, - opaque_and_semitransparent: new_opaque_and_semitransparent, - dollar_crate_name: kw::DollarCrate, + opaque_and_semitransparent = *self + .syntax_context_map + .entry((parent, expn_id, transparency)) + .or_insert_with(|| { + let new_opaque_and_semitransparent = + SyntaxContext(syntax_context_data.len() as u32); + syntax_context_data.push(SyntaxContextData { + outer_expn: expn_id, + outer_transparency: transparency, + parent, + opaque, + opaque_and_semitransparent: new_opaque_and_semitransparent, + dollar_crate_name: kw::DollarCrate, + }); + new_opaque_and_semitransparent }); - new_opaque_and_semitransparent - }); } let parent = ctxt; @@ -347,19 +365,26 @@ pub fn walk_chain(span: Span, to: SyntaxContext) -> Span { pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) { // The new contexts that need updating are at the end of the list and have `$crate` as a name. - let (len, to_update) = HygieneData::with(|data| ( - data.syntax_context_data.len(), - data.syntax_context_data.iter().rev() - .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate).count() - )); + let (len, to_update) = HygieneData::with(|data| { + ( + data.syntax_context_data.len(), + data.syntax_context_data + .iter() + .rev() + .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate) + .count(), + ) + }); // The callback must be called from outside of the `HygieneData` lock, // since it will try to acquire it too. - let range_to_update = len - to_update .. len; + let range_to_update = len - to_update..len; let names: Vec<_> = range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect(); - HygieneData::with(|data| range_to_update.zip(names.into_iter()).for_each(|(idx, name)| { - data.syntax_context_data[idx].dollar_crate_name = name; - })) + HygieneData::with(|data| { + range_to_update.zip(names.into_iter()).for_each(|(idx, name)| { + data.syntax_context_data[idx].dollar_crate_name = name; + }) + }) } pub fn debug_hygiene_data(verbose: bool) -> String { @@ -383,10 +408,7 @@ pub fn debug_hygiene_data(verbose: bool) -> String { data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| { s.push_str(&format!( "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})", - id, - ctxt.parent, - ctxt.outer_expn, - ctxt.outer_transparency, + id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency, )); }); s @@ -524,8 +546,11 @@ impl SyntaxContext { /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope)); /// } /// ``` - pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) - -> Option> { + pub fn reverse_glob_adjust( + &mut self, + expn_id: ExpnId, + glob_span: Span, + ) -> Option> { HygieneData::with(|data| { if data.adjust(self, expn_id).is_some() { return None; @@ -605,7 +630,9 @@ impl Span { } pub fn fresh_expansion_with_transparency( - self, expn_data: ExpnData, transparency: Transparency + self, + expn_data: ExpnData, + transparency: Transparency, ) -> Span { HygieneData::with(|data| { let expn_id = data.fresh_expn(Some(expn_data)); @@ -671,8 +698,12 @@ impl ExpnData { } } - pub fn allow_unstable(kind: ExpnKind, call_site: Span, edition: Edition, - allow_internal_unstable: Lrc<[Symbol]>) -> ExpnData { + pub fn allow_unstable( + kind: ExpnKind, + call_site: Span, + edition: Edition, + allow_internal_unstable: Lrc<[Symbol]>, + ) -> ExpnData { ExpnData { allow_internal_unstable: Some(allow_internal_unstable), ..ExpnData::default(kind, call_site, edition) @@ -695,7 +726,7 @@ pub enum ExpnKind { /// Transform done by the compiler on the AST. AstPass(AstPass), /// Desugaring done by the compiler during HIR lowering. - Desugaring(DesugaringKind) + Desugaring(DesugaringKind), } impl ExpnKind { @@ -710,8 +741,17 @@ impl ExpnKind { } /// The kind of macro invocation or definition. -#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, - Hash, Debug, HashStable_Generic)] +#[derive( + Clone, + Copy, + PartialEq, + Eq, + RustcEncodable, + RustcDecodable, + Hash, + Debug, + HashStable_Generic +)] pub enum MacroKind { /// A bang macro `foo!()`. Bang, diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 66f25770722..4af552c6561 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -5,7 +5,6 @@ //! This API is completely unstable and subject to change. #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] - #![feature(const_fn)] #![feature(crate_visibility_modifier)] #![feature(nll)] @@ -14,38 +13,38 @@ #![feature(specialization)] #![feature(step_trait)] -use rustc_serialize::{Encodable, Decodable, Encoder, Decoder}; use rustc_macros::HashStable_Generic; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -pub mod source_map; mod caching_source_map_view; +pub mod source_map; pub use self::caching_source_map_view::CachingSourceMapView; pub mod edition; use edition::Edition; pub mod hygiene; -pub use hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind, MacroKind, DesugaringKind}; use hygiene::Transparency; +pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, MacroKind, SyntaxContext}; mod span_encoding; pub use span_encoding::{Span, DUMMY_SP}; pub mod symbol; -pub use symbol::{Symbol, sym}; +pub use symbol::{sym, Symbol}; mod analyze_source_file; pub mod fatal_error; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::sync::{Lrc, Lock}; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::sync::{Lock, Lrc}; use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::cmp::{self, Ordering}; use std::fmt; -use std::hash::{Hasher, Hash}; +use std::hash::{Hash, Hasher}; use std::ops::{Add, Sub}; use std::path::PathBuf; @@ -71,8 +70,18 @@ impl Globals { scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals); /// Differentiates between real files and common virtual files. -#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, - RustcDecodable, RustcEncodable, HashStable_Generic)] +#[derive( + Debug, + Eq, + PartialEq, + Clone, + Ord, + PartialOrd, + Hash, + RustcDecodable, + RustcEncodable, + HashStable_Generic +)] pub enum FileName { Real(PathBuf), /// A macro. This includes the full name of the macro, so that there are no clashes. @@ -103,8 +112,7 @@ impl std::fmt::Display for FileName { QuoteExpansion(_) => write!(fmt, ""), MacroExpansion(_) => write!(fmt, ""), Anon(_) => write!(fmt, ""), - ProcMacroSourceCode(_) => - write!(fmt, ""), + ProcMacroSourceCode(_) => write!(fmt, ""), CfgSpec(_) => write!(fmt, ""), CliCrateAttr(_) => write!(fmt, ""), Custom(ref s) => write!(fmt, "<{}>", s), @@ -125,30 +133,30 @@ impl FileName { use FileName::*; match *self { Real(_) => true, - Macros(_) | - Anon(_) | - MacroExpansion(_) | - ProcMacroSourceCode(_) | - CfgSpec(_) | - CliCrateAttr(_) | - Custom(_) | - QuoteExpansion(_) | - DocTest(_, _) => false, + Macros(_) + | Anon(_) + | MacroExpansion(_) + | ProcMacroSourceCode(_) + | CfgSpec(_) + | CliCrateAttr(_) + | Custom(_) + | QuoteExpansion(_) + | DocTest(_, _) => false, } } pub fn is_macros(&self) -> bool { use FileName::*; match *self { - Real(_) | - Anon(_) | - MacroExpansion(_) | - ProcMacroSourceCode(_) | - CfgSpec(_) | - CliCrateAttr(_) | - Custom(_) | - QuoteExpansion(_) | - DocTest(_, _) => false, + Real(_) + | Anon(_) + | MacroExpansion(_) + | ProcMacroSourceCode(_) + | CfgSpec(_) + | CliCrateAttr(_) + | Custom(_) + | QuoteExpansion(_) + | DocTest(_, _) => false, Macros(_) => true, } } @@ -189,7 +197,7 @@ impl FileName { FileName::CliCrateAttr(hasher.finish()) } - pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{ + pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName { FileName::DocTest(path, line) } } @@ -351,11 +359,7 @@ impl Span { pub fn trim_start(self, other: Span) -> Option { let span = self.data(); let other = other.data(); - if span.hi > other.hi { - Some(span.with_lo(cmp::max(span.lo, other.hi))) - } else { - None - } + if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None } } /// Returns the source span -- this is either the supplied span, or the span for @@ -406,9 +410,9 @@ impl Span { /// `#[allow_internal_unstable]`). pub fn allows_unstable(&self, feature: Symbol) -> bool { self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| { - features.iter().any(|&f| { - f == feature || f == sym::allow_internal_unstable_backcompat_hack - }) + features + .iter() + .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack) }) } @@ -425,7 +429,7 @@ impl Span { pub fn desugaring_kind(&self) -> Option { match self.ctxt().outer_expn_data().kind { ExpnKind::Desugaring(k) => Some(k), - _ => None + _ => None, } } @@ -454,7 +458,7 @@ impl Span { MacroKind::Bang => ("", "!"), MacroKind::Attr => ("#[", "]"), MacroKind::Derive => ("#[derive(", ")]"), - } + }, }; result.push(MacroBacktrace { call_site: expn_data.call_site, @@ -516,9 +520,11 @@ impl Span { pub fn from_inner(self, inner: InnerSpan) -> Span { let span = self.data(); - Span::new(span.lo + BytePos::from_usize(inner.start), - span.lo + BytePos::from_usize(inner.end), - span.ctxt) + Span::new( + span.lo + BytePos::from_usize(inner.start), + span.lo + BytePos::from_usize(inner.end), + span.ctxt, + ) } /// Equivalent of `Span::def_site` from the proc macro API, @@ -585,8 +591,11 @@ impl Span { } #[inline] - pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) - -> Option> { + pub fn reverse_glob_adjust( + &mut self, + expn_id: ExpnId, + glob_span: Span, + ) -> Option> { let mut span = self.data(); let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); *self = Span::new(span.lo, span.hi, span.ctxt); @@ -629,13 +638,9 @@ impl rustc_serialize::UseSpecializedEncodable for Span { fn default_encode(&self, s: &mut S) -> Result<(), S::Error> { let span = self.data(); s.emit_struct("Span", 2, |s| { - s.emit_struct_field("lo", 0, |s| { - span.lo.encode(s) - })?; + s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?; - s.emit_struct_field("hi", 1, |s| { - span.hi.encode(s) - }) + s.emit_struct_field("hi", 1, |s| span.hi.encode(s)) }) } } @@ -673,24 +678,15 @@ impl fmt::Debug for SpanData { impl MultiSpan { #[inline] pub fn new() -> MultiSpan { - MultiSpan { - primary_spans: vec![], - span_labels: vec![] - } + MultiSpan { primary_spans: vec![], span_labels: vec![] } } pub fn from_span(primary_span: Span) -> MultiSpan { - MultiSpan { - primary_spans: vec![primary_span], - span_labels: vec![] - } + MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } } pub fn from_spans(vec: Vec) -> MultiSpan { - MultiSpan { - primary_spans: vec, - span_labels: vec![] - } + MultiSpan { primary_spans: vec, span_labels: vec![] } } pub fn push_span_label(&mut self, span: Span, label: String) { @@ -750,21 +746,19 @@ impl MultiSpan { pub fn span_labels(&self) -> Vec { let is_primary = |span| self.primary_spans.contains(&span); - let mut span_labels = self.span_labels.iter().map(|&(span, ref label)| - SpanLabel { + let mut span_labels = self + .span_labels + .iter() + .map(|&(span, ref label)| SpanLabel { span, is_primary: is_primary(span), - label: Some(label.clone()) - } - ).collect::>(); + label: Some(label.clone()), + }) + .collect::>(); for &span in &self.primary_spans { if !span_labels.iter().any(|sl| sl.span == span) { - span_labels.push(SpanLabel { - span, - is_primary: true, - label: None - }); + span_labels.push(SpanLabel { span, is_primary: true, label: None }); } } @@ -822,9 +816,7 @@ impl NonNarrowChar { /// Returns the absolute offset of the character in the `SourceMap`. pub fn pos(&self) -> BytePos { match *self { - NonNarrowChar::ZeroWidth(p) | - NonNarrowChar::Wide(p) | - NonNarrowChar::Tab(p) => p, + NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p, } } @@ -962,17 +954,13 @@ impl Encodable for SourceFile { let max_line_length = if lines.len() == 1 { 0 } else { - lines.windows(2) - .map(|w| w[1] - w[0]) - .map(|bp| bp.to_usize()) - .max() - .unwrap() + lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap() }; let bytes_per_diff: u8 = match max_line_length { - 0 ..= 0xFF => 1, - 0x100 ..= 0xFFFF => 2, - _ => 4 + 0..=0xFF => 1, + 0x100..=0xFFFF => 2, + _ => 4, }; // Encode the number of bytes used per diff. @@ -981,31 +969,34 @@ impl Encodable for SourceFile { // Encode the first element. lines[0].encode(s)?; - let diff_iter = (&lines[..]).windows(2) - .map(|w| (w[1] - w[0])); + let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0])); match bytes_per_diff { - 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? }, - 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? }, - 4 => for diff in diff_iter { diff.0.encode(s)? }, - _ => unreachable!() + 1 => { + for diff in diff_iter { + (diff.0 as u8).encode(s)? + } + } + 2 => { + for diff in diff_iter { + (diff.0 as u16).encode(s)? + } + } + 4 => { + for diff in diff_iter { + diff.0.encode(s)? + } + } + _ => unreachable!(), } } Ok(()) })?; - s.emit_struct_field("multibyte_chars", 6, |s| { - self.multibyte_chars.encode(s) - })?; - s.emit_struct_field("non_narrow_chars", 7, |s| { - self.non_narrow_chars.encode(s) - })?; - s.emit_struct_field("name_hash", 8, |s| { - self.name_hash.encode(s) - })?; - s.emit_struct_field("normalized_pos", 9, |s| { - self.normalized_pos.encode(s) - }) + s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?; + s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?; + s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?; + s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s)) }) } } @@ -1016,8 +1007,7 @@ impl Decodable for SourceFile { let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?; let name_was_remapped: bool = d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?; - let src_hash: u128 = - d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?; + let src_hash: u128 = d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?; let start_pos: BytePos = d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?; let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?; @@ -1038,7 +1028,7 @@ impl Decodable for SourceFile { 1 => d.read_u8()? as u32, 2 => d.read_u16()? as u32, 4 => d.read_u32()?, - _ => unreachable!() + _ => unreachable!(), }; line_start = line_start + BytePos(diff); @@ -1053,8 +1043,7 @@ impl Decodable for SourceFile { d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?; let non_narrow_chars: Vec = d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?; - let name_hash: u128 = - d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?; + let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?; let normalized_pos: Vec = d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?; Ok(SourceFile { @@ -1087,11 +1076,13 @@ impl fmt::Debug for SourceFile { } impl SourceFile { - pub fn new(name: FileName, - name_was_remapped: bool, - unmapped_path: FileName, - mut src: String, - start_pos: BytePos) -> Result { + pub fn new( + name: FileName, + name_was_remapped: bool, + unmapped_path: FileName, + mut src: String, + start_pos: BytePos, + ) -> Result { let normalized_pos = normalize_src(&mut src, start_pos); let src_hash = { @@ -1141,7 +1132,8 @@ impl SourceFile { /// it is interpreted as an error and the corresponding enum variant is set. /// The return value signifies whether some kind of source is present. pub fn add_external_src(&self, get_src: F) -> bool - where F: FnOnce() -> Option + where + F: FnOnce() -> Option, { if *self.external_src.borrow() == ExternalSource::AbsentOk { let src = get_src(); @@ -1179,7 +1171,7 @@ impl SourceFile { let slice = &src[begin..]; match slice.find('\n') { Some(e) => &slice[..e], - None => slice + None => slice, } } @@ -1228,11 +1220,7 @@ impl SourceFile { let line_index = lookup_line(&self.lines[..], pos); assert!(line_index < self.lines.len() as isize); - if line_index >= 0 { - Some(line_index as usize) - } else { - None - } + if line_index >= 0 { Some(line_index as usize) } else { None } } pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) { @@ -1256,15 +1244,13 @@ impl SourceFile { /// Calculates the original byte position relative to the start of the file /// based on the given byte position. pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos { - // Diff before any records is 0. Otherwise use the previously recorded // diff as that applies to the following characters until a new diff // is recorded. - let diff = match self.normalized_pos.binary_search_by( - |np| np.pos.cmp(&pos)) { + let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) { Ok(i) => self.normalized_pos[i].diff, Err(i) if i == 0 => 0, - Err(i) => self.normalized_pos[i-1].diff, + Err(i) => self.normalized_pos[i - 1].diff, }; BytePos::from_u32(pos.0 - self.start_pos.0 + diff) @@ -1293,7 +1279,6 @@ fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { } } - /// Replaces `\r\n` with `\n` in-place in `src`. /// /// Returns error if there's a lone `\r` in the string @@ -1382,16 +1367,24 @@ pub struct CharPos(pub usize); impl Pos for BytePos { #[inline(always)] - fn from_usize(n: usize) -> BytePos { BytePos(n as u32) } + fn from_usize(n: usize) -> BytePos { + BytePos(n as u32) + } #[inline(always)] - fn to_usize(&self) -> usize { self.0 as usize } + fn to_usize(&self) -> usize { + self.0 as usize + } #[inline(always)] - fn from_u32(n: u32) -> BytePos { BytePos(n) } + fn from_u32(n: u32) -> BytePos { + BytePos(n) + } #[inline(always)] - fn to_u32(&self) -> u32 { self.0 } + fn to_u32(&self) -> u32 { + self.0 + } } impl Add for BytePos { @@ -1426,16 +1419,24 @@ impl Decodable for BytePos { impl Pos for CharPos { #[inline(always)] - fn from_usize(n: usize) -> CharPos { CharPos(n) } + fn from_usize(n: usize) -> CharPos { + CharPos(n) + } #[inline(always)] - fn to_usize(&self) -> usize { self.0 } + fn to_usize(&self) -> usize { + self.0 + } #[inline(always)] - fn from_u32(n: u32) -> CharPos { CharPos(n as usize) } + fn from_u32(n: u32) -> CharPos { + CharPos(n as usize) + } #[inline(always)] - fn to_u32(&self) -> u32 { self.0 as u32} + fn to_u32(&self) -> u32 { + self.0 as u32 + } } impl Add for CharPos { @@ -1475,9 +1476,15 @@ pub struct Loc { // Used to be structural records. #[derive(Debug)] -pub struct SourceFileAndLine { pub sf: Lrc, pub line: usize } +pub struct SourceFileAndLine { + pub sf: Lrc, + pub line: usize, +} #[derive(Debug)] -pub struct SourceFileAndBytePos { pub sf: Lrc, pub pos: BytePos } +pub struct SourceFileAndBytePos { + pub sf: Lrc, + pub pos: BytePos, +} #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct LineInfo { @@ -1493,7 +1500,7 @@ pub struct LineInfo { pub struct FileLines { pub file: Lrc, - pub lines: Vec + pub lines: Vec, } thread_local!(pub static SPAN_DEBUG: Cell) -> fmt::Result> = @@ -1527,13 +1534,13 @@ pub enum SpanSnippetError { IllFormedSpan(Span), DistinctSources(DistinctSources), MalformedForSourcemap(MalformedSourceMapPositions), - SourceNotAvailable { filename: FileName } + SourceNotAvailable { filename: FileName }, } #[derive(Clone, PartialEq, Eq, Debug)] pub struct DistinctSources { pub begin: (FileName, BytePos), - pub end: (FileName, BytePos) + pub end: (FileName, BytePos), } #[derive(Clone, PartialEq, Eq, Debug)] @@ -1541,7 +1548,7 @@ pub struct MalformedSourceMapPositions { pub name: FileName, pub source_len: usize, pub begin_pos: BytePos, - pub end_pos: BytePos + pub end_pos: BytePos, } /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. @@ -1563,7 +1570,7 @@ impl InnerSpan { fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize { match lines.binary_search(&pos) { Ok(line) => line as isize, - Err(line) => line as isize - 1 + Err(line) => line as isize - 1, } } @@ -1572,12 +1579,15 @@ fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize { /// instead of implementing everything in librustc. pub trait HashStableContext { fn hash_spans(&self) -> bool; - fn byte_pos_to_line_and_col(&mut self, byte: BytePos) - -> Option<(Lrc, usize, BytePos)>; + fn byte_pos_to_line_and_col( + &mut self, + byte: BytePos, + ) -> Option<(Lrc, usize, BytePos)>; } impl HashStable for Span - where CTX: HashStableContext +where + CTX: HashStableContext, { /// Hashes a span in a stable way. We can't directly hash the span's `BytePos` /// fields (that would be similar to hashing pointers, since those are just @@ -1595,7 +1605,7 @@ impl HashStable for Span const TAG_NO_EXPANSION: u8 = 1; if !ctx.hash_spans() { - return + return; } if *self == DUMMY_SP { diff --git a/src/libsyntax_pos/source_map.rs b/src/libsyntax_pos/source_map.rs index b597fad080f..0b9b9fe7887 100644 --- a/src/libsyntax_pos/source_map.rs +++ b/src/libsyntax_pos/source_map.rs @@ -7,20 +7,20 @@ //! within the `SourceMap`, which upon request can be converted to line and column //! information, source code snippets, etc. +pub use crate::hygiene::{ExpnData, ExpnKind}; pub use crate::*; -pub use crate::hygiene::{ExpnKind, ExpnData}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::StableHasher; -use rustc_data_structures::sync::{Lrc, Lock, LockGuard, MappedLockGuard}; +use rustc_data_structures::sync::{Lock, LockGuard, Lrc, MappedLockGuard}; use std::cmp; use std::hash::Hash; use std::path::{Path, PathBuf}; +use log::debug; use std::env; use std::fs; use std::io; -use log::debug; #[cfg(test)] mod tests; @@ -31,8 +31,8 @@ mod tests; pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span { let expn_data1 = sp.ctxt().outer_expn_data(); let expn_data2 = enclosing_sp.ctxt().outer_expn_data(); - if expn_data1.is_root() || - !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site { + if expn_data1.is_root() || !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site + { sp } else { original_sp(expn_data1.call_site, enclosing_sp) @@ -46,7 +46,7 @@ pub struct Spanned { } pub fn respan(sp: Span, t: T) -> Spanned { - Spanned {node: t, span: sp} + Spanned { node: t, span: sp } } pub fn dummy_spanned(t: T) -> Spanned { @@ -81,9 +81,7 @@ impl FileLoader for RealFileLoader { if path.is_absolute() { Some(path.to_path_buf()) } else { - env::current_dir() - .ok() - .map(|cwd| cwd.join(path)) + env::current_dir().ok().map(|cwd| cwd.join(path)) } } @@ -100,14 +98,18 @@ pub struct StableSourceFileId(u128); impl StableSourceFileId { pub fn new(source_file: &SourceFile) -> StableSourceFileId { - StableSourceFileId::new_from_pieces(&source_file.name, - source_file.name_was_remapped, - source_file.unmapped_path.as_ref()) + StableSourceFileId::new_from_pieces( + &source_file.name, + source_file.name_was_remapped, + source_file.unmapped_path.as_ref(), + ) } - pub fn new_from_pieces(name: &FileName, - name_was_remapped: bool, - unmapped_path: Option<&FileName>) -> StableSourceFileId { + pub fn new_from_pieces( + name: &FileName, + name_was_remapped: bool, + unmapped_path: Option<&FileName>, + ) -> StableSourceFileId { let mut hasher = StableHasher::new(); name.hash(&mut hasher); @@ -125,7 +127,7 @@ impl StableSourceFileId { #[derive(Default)] pub(super) struct SourceMapFiles { source_files: Vec>, - stable_id_to_source_file: FxHashMap> + stable_id_to_source_file: FxHashMap>, } pub struct SourceMap { @@ -138,21 +140,14 @@ pub struct SourceMap { impl SourceMap { pub fn new(path_mapping: FilePathMapping) -> SourceMap { - SourceMap { - files: Default::default(), - file_loader: Box::new(RealFileLoader), - path_mapping, - } + SourceMap { files: Default::default(), file_loader: Box::new(RealFileLoader), path_mapping } } - pub fn with_file_loader(file_loader: Box, - path_mapping: FilePathMapping) - -> SourceMap { - SourceMap { - files: Default::default(), - file_loader, - path_mapping, - } + pub fn with_file_loader( + file_loader: Box, + path_mapping: FilePathMapping, + ) -> SourceMap { + SourceMap { files: Default::default(), file_loader, path_mapping } } pub fn path_mapping(&self) -> &FilePathMapping { @@ -183,8 +178,7 @@ impl SourceMap { // loaded as a binary via `include_bytes!` and as proper `SourceFile` // via `mod`, so we try to use real file contents and not just an // empty string. - let text = std::str::from_utf8(&bytes).unwrap_or("") - .to_string(); + let text = std::str::from_utf8(&bytes).unwrap_or("").to_string(); self.new_source_file(path.to_owned().into(), text); Ok(bytes) } @@ -193,8 +187,10 @@ impl SourceMap { LockGuard::map(self.files.borrow(), |files| &mut files.source_files) } - pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) -> - Option> { + pub fn source_file_by_stable_id( + &self, + stable_id: StableSourceFileId, + ) -> Option> { self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone()) } @@ -211,17 +207,16 @@ impl SourceMap { /// If a file already exists in the `SourceMap` with the same ID, that file is returned /// unmodified. pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { - self.try_new_source_file(filename, src) - .unwrap_or_else(|OffsetOverflowError| { - eprintln!("fatal error: rustc does not support files larger than 4GB"); - crate::fatal_error::FatalError.raise() - }) + self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| { + eprintln!("fatal error: rustc does not support files larger than 4GB"); + crate::fatal_error::FatalError.raise() + }) } fn try_new_source_file( &self, filename: FileName, - src: String + src: String, ) -> Result, OffsetOverflowError> { let start_pos = self.next_start_pos(); @@ -236,13 +231,12 @@ impl SourceMap { FileName::Real(filename) => { let (filename, was_remapped) = self.path_mapping.map_prefix(filename); (FileName::Real(filename), was_remapped) - }, + } other => (other, false), }; - let file_id = StableSourceFileId::new_from_pieces(&filename, - was_remapped, - Some(&unmapped_path)); + let file_id = + StableSourceFileId::new_from_pieces(&filename, was_remapped, Some(&unmapped_path)); let lrc_sf = match self.source_file_by_stable_id(file_id) { Some(lrc_sf) => lrc_sf, @@ -324,18 +318,16 @@ impl SourceMap { let mut files = self.files.borrow_mut(); files.source_files.push(source_file.clone()); - files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file), - source_file.clone()); + files + .stable_id_to_source_file + .insert(StableSourceFileId::new(&source_file), source_file.clone()); source_file } pub fn mk_substr_filename(&self, sp: Span) -> String { let pos = self.lookup_char_pos(sp.lo()); - format!("<{}:{}:{}>", - pos.file.name, - pos.line, - pos.col.to_usize() + 1) + format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_usize() + 1) } // If there is a doctest offset, applies it to the line. @@ -346,10 +338,10 @@ impl SourceMap { orig + *offset as usize } else { orig - (-(*offset)) as usize - } - }, - _ => orig - } + }; + } + _ => orig, + }; } /// Looks up source information about a `BytePos`. @@ -372,25 +364,17 @@ impl SourceMap { .binary_search_by_key(&pos, |x| x.pos()) .unwrap_or_else(|x| x); let special_chars = end_width_idx - start_width_idx; - let non_narrow: usize = f - .non_narrow_chars[start_width_idx..end_width_idx] + let non_narrow: usize = f.non_narrow_chars[start_width_idx..end_width_idx] .into_iter() .map(|x| x.width()) .sum(); col.0 - special_chars + non_narrow }; - debug!("byte pos {:?} is on the line at byte pos {:?}", - pos, linebpos); - debug!("char pos {:?} is on the line at char pos {:?}", - chpos, linechpos); + debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); + debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); debug!("byte is on line: {}", line); assert!(chpos >= linechpos); - Loc { - file: f, - line, - col, - col_display, - } + Loc { file: f, line, col, col_display } } Err(f) => { let col_display = { @@ -398,19 +382,11 @@ impl SourceMap { .non_narrow_chars .binary_search_by_key(&pos, |x| x.pos()) .unwrap_or_else(|x| x); - let non_narrow: usize = f - .non_narrow_chars[0..end_width_idx] - .into_iter() - .map(|x| x.width()) - .sum(); + let non_narrow: usize = + f.non_narrow_chars[0..end_width_idx].into_iter().map(|x| x.width()).sum(); chpos.0 - end_width_idx + non_narrow }; - Loc { - file: f, - line: 0, - col: chpos, - col_display, - } + Loc { file: f, line: 0, col: chpos, col_display } } } } @@ -423,7 +399,7 @@ impl SourceMap { match f.lookup_line(pos) { Some(line) => Ok(SourceFileAndLine { sf: f, line }), - None => Err(f) + None => Err(f), } } @@ -442,11 +418,11 @@ impl SourceMap { let lhs_end = match self.lookup_line(sp_lhs.hi()) { Ok(x) => x, - Err(_) => return None + Err(_) => return None, }; let rhs_begin = match self.lookup_line(sp_rhs.lo()) { Ok(x) => x, - Err(_) => return None + Err(_) => return None, }; // If we must cross lines to merge, don't merge. @@ -469,7 +445,8 @@ impl SourceMap { let lo = self.lookup_char_pos(sp.lo()); let hi = self.lookup_char_pos(sp.hi()); - format!("{}:{}:{}: {}:{}", + format!( + "{}:{}:{}: {}:{}", lo.file.name, lo.line, lo.col.to_usize() + 1, @@ -483,7 +460,10 @@ impl SourceMap { } pub fn span_to_unmapped_path(&self, sp: Span) -> FileName { - self.lookup_char_pos(sp.lo()).file.unmapped_path.clone() + self.lookup_char_pos(sp.lo()) + .file + .unmapped_path + .clone() .expect("`SourceMap::span_to_unmapped_path` called for imported `SourceFile`?") } @@ -519,56 +499,47 @@ impl SourceMap { // and to the end of the line. Be careful because the line // numbers in Loc are 1-based, so we subtract 1 to get 0-based // lines. - for line_index in lo.line-1 .. hi.line-1 { - let line_len = lo.file.get_line(line_index) - .map(|s| s.chars().count()) - .unwrap_or(0); - lines.push(LineInfo { line_index, - start_col, - end_col: CharPos::from_usize(line_len) }); + for line_index in lo.line - 1..hi.line - 1 { + let line_len = lo.file.get_line(line_index).map(|s| s.chars().count()).unwrap_or(0); + lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) }); start_col = CharPos::from_usize(0); } // For the last line, it extends from `start_col` to `hi.col`: - lines.push(LineInfo { line_index: hi.line - 1, - start_col, - end_col: hi.col }); + lines.push(LineInfo { line_index: hi.line - 1, start_col, end_col: hi.col }); - Ok(FileLines {file: lo.file, lines}) + Ok(FileLines { file: lo.file, lines }) } /// Extracts the source surrounding the given `Span` using the `extract_source` function. The /// extract function takes three arguments: a string slice containing the source, an index in /// the slice for the beginning of the span and an index in the slice for the end of the span. fn span_to_source(&self, sp: Span, extract_source: F) -> Result - where F: Fn(&str, usize, usize) -> Result + where + F: Fn(&str, usize, usize) -> Result, { let local_begin = self.lookup_byte_offset(sp.lo()); let local_end = self.lookup_byte_offset(sp.hi()); if local_begin.sf.start_pos != local_end.sf.start_pos { return Err(SpanSnippetError::DistinctSources(DistinctSources { - begin: (local_begin.sf.name.clone(), - local_begin.sf.start_pos), - end: (local_end.sf.name.clone(), - local_end.sf.start_pos) + begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos), + end: (local_end.sf.name.clone(), local_end.sf.start_pos), })); } else { self.ensure_source_file_source_present(local_begin.sf.clone()); let start_index = local_begin.pos.to_usize(); let end_index = local_end.pos.to_usize(); - let source_len = (local_begin.sf.end_pos - - local_begin.sf.start_pos).to_usize(); + let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize(); if start_index > end_index || end_index > source_len { - return Err(SpanSnippetError::MalformedForSourcemap( - MalformedSourceMapPositions { - name: local_begin.sf.name.clone(), - source_len, - begin_pos: local_begin.pos, - end_pos: local_end.pos, - })); + return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions { + name: local_begin.sf.name.clone(), + source_len, + begin_pos: local_begin.pos, + end_pos: local_end.pos, + })); } if let Some(ref src) = local_begin.sf.src { @@ -577,7 +548,7 @@ impl SourceMap { return extract_source(src, start_index, end_index); } else { return Err(SpanSnippetError::SourceNotAvailable { - filename: local_begin.sf.name.clone() + filename: local_begin.sf.name.clone(), }); } } @@ -585,25 +556,30 @@ impl SourceMap { /// Returns the source snippet as `String` corresponding to the given `Span`. pub fn span_to_snippet(&self, sp: Span) -> Result { - self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index) - .map(|s| s.to_string()) - .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))) + self.span_to_source(sp, |src, start_index, end_index| { + src.get(start_index..end_index) + .map(|s| s.to_string()) + .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)) + }) } pub fn span_to_margin(&self, sp: Span) -> Option { match self.span_to_prev_source(sp) { Err(_) => None, - Ok(source) => source.split('\n').last().map(|last_line| { - last_line.len() - last_line.trim_start().len() - }) + Ok(source) => source + .split('\n') + .last() + .map(|last_line| last_line.len() - last_line.trim_start().len()), } } /// Returns the source snippet as `String` before the given `Span`. pub fn span_to_prev_source(&self, sp: Span) -> Result { - self.span_to_source(sp, |src, start_index, _| src.get(..start_index) - .map(|s| s.to_string()) - .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))) + self.span_to_source(sp, |src, start_index, _| { + src.get(..start_index) + .map(|s| s.to_string()) + .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)) + }) } /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span @@ -679,11 +655,7 @@ impl SourceMap { whitespace_found = true; } - if whitespace_found && !c.is_whitespace() { - false - } else { - true - } + if whitespace_found && !c.is_whitespace() { false } else { true } }) } @@ -697,13 +669,11 @@ impl SourceMap { /// Given a `Span`, gets a shorter one until `predicate` yields `false`. pub fn span_take_while

(&self, sp: Span, predicate: P) -> Span - where P: for <'r> FnMut(&'r char) -> bool + where + P: for<'r> FnMut(&'r char) -> bool, { if let Ok(snippet) = self.span_to_snippet(sp) { - let offset = snippet.chars() - .take_while(predicate) - .map(|c| c.len_utf8()) - .sum::(); + let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::(); sp.with_hi(BytePos(sp.lo().0 + (offset as u32))) } else { @@ -743,8 +713,8 @@ impl SourceMap { // If the width is 1, then the next span should point to the same `lo` and `hi`. However, // in the case of a multibyte character, where the width != 1, the next span should // span multiple bytes to include the whole character. - let end_of_next_point = start_of_next_point.checked_add( - width - 1).unwrap_or(start_of_next_point); + let end_of_next_point = + start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point); let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point)); Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt()) @@ -760,8 +730,10 @@ impl SourceMap { let local_begin = self.lookup_byte_offset(sp.lo); let local_end = self.lookup_byte_offset(sp.hi); - debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`", - local_begin, local_end); + debug!( + "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`", + local_begin, local_end + ); if local_begin.sf.start_pos != local_end.sf.start_pos { debug!("find_width_of_character_at_span: begin and end are in different files"); @@ -770,13 +742,16 @@ impl SourceMap { let start_index = local_begin.pos.to_usize(); let end_index = local_end.pos.to_usize(); - debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`", - start_index, end_index); + debug!( + "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`", + start_index, end_index + ); // Disregard indexes that are at the start or end of their spans, they can't fit bigger // characters. - if (!forwards && end_index == usize::min_value()) || - (forwards && start_index == usize::max_value()) { + if (!forwards && end_index == usize::min_value()) + || (forwards && start_index == usize::max_value()) + { debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte"); return 1; } @@ -822,11 +797,7 @@ impl SourceMap { } debug!("find_width_of_character_at_span: final target=`{:?}`", target); - if forwards { - (target - end_index) as u32 - } else { - (end_index - target) as u32 - } + if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 } } pub fn get_source_file(&self, filename: &FileName) -> Option> { @@ -843,7 +814,7 @@ impl SourceMap { let idx = self.lookup_source_file_idx(bpos); let sf = (*self.files.borrow().source_files)[idx].clone(); let offset = bpos - sf.start_pos; - SourceFileAndBytePos {sf, pos: offset} + SourceFileAndBytePos { sf, pos: offset } } /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. @@ -874,7 +845,10 @@ impl SourceMap { // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`. pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize { - self.files.borrow().source_files.binary_search_by_key(&pos, |key| key.start_pos) + self.files + .borrow() + .source_files + .binary_search_by_key(&pos, |key| key.start_pos) .unwrap_or_else(|p| p - 1) } @@ -882,14 +856,16 @@ impl SourceMap { self.files().iter().fold(0, |a, f| a + f.count_lines()) } - pub fn generate_fn_name_span(&self, span: Span) -> Option { let prev_span = self.span_extend_to_prev_str(span, "fn", true); - self.span_to_snippet(prev_span).map(|snippet| { - let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_') - .expect("no label after fn"); - prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32)) - }).ok() + self.span_to_snippet(prev_span) + .map(|snippet| { + let len = snippet + .find(|c: char| !c.is_alphanumeric() && c != '_') + .expect("no label after fn"); + prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32)) + }) + .ok() } /// Takes the span of a type parameter in a function signature and try to generate a span for @@ -917,7 +893,8 @@ impl SourceMap { if sugg_span != span { if let Ok(snippet) = self.span_to_snippet(sugg_span) { // Consume the function name. - let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_') + let mut offset = snippet + .find(|c: char| !c.is_alphanumeric() && c != '_') .expect("no label after fn"); // Consume the generics part of the function signature. @@ -927,7 +904,11 @@ impl SourceMap { match c { '<' => bracket_counter += 1, '>' => bracket_counter -= 1, - '(' => if bracket_counter == 0 { break; } + '(' => { + if bracket_counter == 0 { + break; + } + } _ => {} } offset += c.len_utf8(); @@ -944,8 +925,8 @@ impl SourceMap { } else { format!("{}<", &snippet[..offset]) }; - new_snippet.push_str( - &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string())); + new_snippet + .push_str(&self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string())); new_snippet.push('>'); return Some((sugg_span, new_snippet)); @@ -955,12 +936,10 @@ impl SourceMap { None } pub fn ensure_source_file_source_present(&self, source_file: Lrc) -> bool { - source_file.add_external_src( - || match source_file.name { - FileName::Real(ref name) => self.file_loader.read_file(name).ok(), - _ => None, - } - ) + source_file.add_external_src(|| match source_file.name { + FileName::Real(ref name) => self.file_loader.read_file(name).ok(), + _ => None, + }) } pub fn call_span_if_macro(&self, sp: Span) -> Span { if self.span_to_filename(sp.clone()).is_macros() { @@ -980,15 +959,11 @@ pub struct FilePathMapping { impl FilePathMapping { pub fn empty() -> FilePathMapping { - FilePathMapping { - mapping: vec![] - } + FilePathMapping { mapping: vec![] } } pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping { - FilePathMapping { - mapping, - } + FilePathMapping { mapping } } /// Applies any path prefix substitution as defined by the mapping. diff --git a/src/libsyntax_pos/source_map/tests.rs b/src/libsyntax_pos/source_map/tests.rs index 15254336bbf..79df1884f0d 100644 --- a/src/libsyntax_pos/source_map/tests.rs +++ b/src/libsyntax_pos/source_map/tests.rs @@ -4,18 +4,9 @@ use rustc_data_structures::sync::Lrc; fn init_source_map() -> SourceMap { let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file( - PathBuf::from("blork.rs").into(), - "first line.\nsecond line".to_string(), - ); - sm.new_source_file( - PathBuf::from("empty.rs").into(), - String::new(), - ); - sm.new_source_file( - PathBuf::from("blork2.rs").into(), - "first line.\nsecond line".to_string(), - ); + sm.new_source_file(PathBuf::from("blork.rs").into(), "first line.\nsecond line".to_string()); + sm.new_source_file(PathBuf::from("empty.rs").into(), String::new()); + sm.new_source_file(PathBuf::from("blork2.rs").into(), "first line.\nsecond line".to_string()); sm } @@ -68,10 +59,14 @@ fn t5() { fn init_source_map_mbc() -> SourceMap { let sm = SourceMap::new(FilePathMapping::empty()); // "€" is a three-byte UTF8 char. - sm.new_source_file(PathBuf::from("blork.rs").into(), - "fir€st €€€€ line.\nsecond line".to_string()); - sm.new_source_file(PathBuf::from("blork2.rs").into(), - "first line€€.\n€ second line".to_string()); + sm.new_source_file( + PathBuf::from("blork.rs").into(), + "fir€st €€€€ line.\nsecond line".to_string(), + ); + sm.new_source_file( + PathBuf::from("blork2.rs").into(), + "first line€€.\n€ second line".to_string(), + ); sm } @@ -112,7 +107,7 @@ fn t7() { fn span_from_selection(input: &str, selection: &str) -> Span { assert_eq!(input.len(), selection.len()); let left_index = selection.find('~').unwrap() as u32; - let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index); + let right_index = selection.rfind('~').map(|x| x as u32).unwrap_or(left_index); Span::with_root_ctxt(BytePos(left_index), BytePos(right_index + 1)) } @@ -134,8 +129,8 @@ fn span_to_snippet_and_lines_spanning_multiple_lines() { let expected = vec![ LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) }, LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) }, - LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) } - ]; + LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }, + ]; assert_eq!(lines.lines, expected); } @@ -154,7 +149,7 @@ fn t8() { fn t9() { let sm = init_source_map(); let span = Span::with_root_ctxt(BytePos(12), BytePos(23)); - let sstr = sm.span_to_string(span); + let sstr = sm.span_to_string(span); assert_eq!(sstr, "blork.rs:2:1: 2:12"); } @@ -163,7 +158,7 @@ fn t9() { #[test] fn span_merging_fail() { let sm = SourceMap::new(FilePathMapping::empty()); - let inputtext = "bbbb BB\ncc CCC\n"; + let inputtext = "bbbb BB\ncc CCC\n"; let selection1 = " ~~\n \n"; let selection2 = " \n ~~~\n"; sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned()); diff --git a/src/libsyntax_pos/span_encoding.rs b/src/libsyntax_pos/span_encoding.rs index 525ec136232..d769cf83a03 100644 --- a/src/libsyntax_pos/span_encoding.rs +++ b/src/libsyntax_pos/span_encoding.rs @@ -4,9 +4,9 @@ // The encoding format for inline spans were obtained by optimizing over crates in rustc/libstd. // See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28 +use crate::hygiene::SyntaxContext; use crate::GLOBALS; use crate::{BytePos, SpanData}; -use crate::hygiene::SyntaxContext; use rustc_data_structures::fx::FxHashMap; @@ -61,7 +61,7 @@ use rustc_data_structures::fx::FxHashMap; pub struct Span { base_or_index: u32, len_or_tag: u16, - ctxt_or_zero: u16 + ctxt_or_zero: u16, } const LEN_TAG: u16 = 0b1000_0000_0000_0000; diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index d3e80fc4fdd..7e0308ee356 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -4,13 +4,13 @@ use arena::DroplessArena; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; use rustc_index::vec::Idx; use rustc_macros::{symbols, HashStable_Generic}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_serialize::{UseSpecializedDecodable, UseSpecializedEncodable}; -use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHasher}; -use std::cmp::{PartialEq, PartialOrd, Ord}; +use std::cmp::{Ord, PartialEq, PartialOrd}; use std::fmt; use std::hash::{Hash, Hasher}; use std::str; @@ -894,12 +894,8 @@ impl fmt::Display for Ident { impl UseSpecializedEncodable for Ident { fn default_encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_struct("Ident", 2, |s| { - s.emit_struct_field("name", 0, |s| { - self.name.encode(s) - })?; - s.emit_struct_field("span", 1, |s| { - self.span.encode(s) - }) + s.emit_struct_field("name", 0, |s| self.name.encode(s))?; + s.emit_struct_field("span", 1, |s| self.span.encode(s)) }) } } @@ -944,18 +940,14 @@ impl Symbol { /// Access the symbol's chars. This is a slowish operation because it /// requires locking the symbol interner. pub fn with R, R>(self, f: F) -> R { - with_interner(|interner| { - f(interner.get(self)) - }) + with_interner(|interner| f(interner.get(self))) } /// Convert to a `SymbolStr`. This is a slowish operation because it /// requires locking the symbol interner. pub fn as_str(self) -> SymbolStr { with_interner(|interner| unsafe { - SymbolStr { - string: std::mem::transmute::<&str, &str>(interner.get(self)) - } + SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) } }) } @@ -1030,14 +1022,11 @@ impl Interner { // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be // UTF-8. - let string: &str = unsafe { - str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) - }; + let string: &str = + unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) }; // It is safe to extend the arena allocation to `'static` because we only access // these while the arena is still alive. - let string: &'static str = unsafe { - &*(string as *const str) - }; + let string: &'static str = unsafe { &*(string as *const str) }; self.strings.push(string); self.names.insert(string, name); name @@ -1058,8 +1047,8 @@ pub mod kw { // This module has a very short name because it's used a lot. pub mod sym { - use std::convert::TryInto; use super::Symbol; + use std::convert::TryInto; symbols!(); @@ -1091,12 +1080,12 @@ impl Symbol { /// A keyword or reserved identifier that can be used as a path segment. pub fn is_path_segment_keyword(self) -> bool { - self == kw::Super || - self == kw::SelfLower || - self == kw::SelfUpper || - self == kw::Crate || - self == kw::PathRoot || - self == kw::DollarCrate + self == kw::Super + || self == kw::SelfLower + || self == kw::SelfUpper + || self == kw::Crate + || self == kw::PathRoot + || self == kw::DollarCrate } /// Returns `true` if the symbol is `true` or `false`. @@ -1120,15 +1109,15 @@ impl Ident { /// Returns `true` if the token is a keyword used in the language. pub fn is_used_keyword(self) -> bool { // Note: `span.edition()` is relatively expensive, don't call it unless necessary. - self.name >= kw::As && self.name <= kw::While || - self.name.is_used_keyword_2018() && self.span.rust_2018() + self.name >= kw::As && self.name <= kw::While + || self.name.is_used_keyword_2018() && self.span.rust_2018() } /// Returns `true` if the token is a keyword reserved for possible future use. pub fn is_unused_keyword(self) -> bool { // Note: `span.edition()` is relatively expensive, don't call it unless necessary. - self.name >= kw::Abstract && self.name <= kw::Yield || - self.name.is_unused_keyword_2018() && self.span.rust_2018() + self.name >= kw::Abstract && self.name <= kw::Yield + || self.name.is_unused_keyword_2018() && self.span.rust_2018() } /// Returns `true` if the token is either a special identifier or a keyword. @@ -1187,7 +1176,9 @@ impl !Sync for SymbolStr {} impl std::ops::Deref for SymbolStr { type Target = str; #[inline] - fn deref(&self) -> &str { self.string } + fn deref(&self) -> &str { + self.string + } } impl fmt::Debug for SymbolStr { diff --git a/src/libsyntax_pos/tests.rs b/src/libsyntax_pos/tests.rs index 87cc3505e38..3c8eb8bcd31 100644 --- a/src/libsyntax_pos/tests.rs +++ b/src/libsyntax_pos/tests.rs @@ -2,12 +2,11 @@ use super::*; #[test] fn test_lookup_line() { - let lines = &[BytePos(3), BytePos(17), BytePos(28)]; assert_eq!(lookup_line(lines, BytePos(0)), -1); - assert_eq!(lookup_line(lines, BytePos(3)), 0); - assert_eq!(lookup_line(lines, BytePos(4)), 0); + assert_eq!(lookup_line(lines, BytePos(3)), 0); + assert_eq!(lookup_line(lines, BytePos(4)), 0); assert_eq!(lookup_line(lines, BytePos(16)), 0); assert_eq!(lookup_line(lines, BytePos(17)), 1); @@ -23,9 +22,7 @@ fn test_normalize_newlines() { let mut actual = before.to_string(); let mut actual_positions = vec![]; normalize_newlines(&mut actual, &mut actual_positions); - let actual_positions : Vec<_> = actual_positions - .into_iter() - .map(|nc| nc.pos.0).collect(); + let actual_positions: Vec<_> = actual_positions.into_iter().map(|nc| nc.pos.0).collect(); assert_eq!(actual.as_str(), after); assert_eq!(actual_positions, expected_positions); } -- cgit 1.4.1-3-g733a5