From 89f892e74a399940fbb480a14f082611cbf05bac Mon Sep 17 00:00:00 2001 From: klensy Date: Sun, 7 Aug 2022 03:09:26 +0300 Subject: [PATCH 1/4] newtype over 1-based line number instead of usize --- .../rustc_builtin_macros/src/source_util.rs | 2 +- .../rustc_codegen_cranelift/src/common.rs | 2 +- .../src/debuginfo/line_info.rs | 2 +- compiler/rustc_codegen_cranelift/src/lib.rs | 2 +- compiler/rustc_codegen_ssa/src/mir/block.rs | 4 +-- .../src/interpret/eval_context.rs | 2 +- .../interpret/intrinsics/caller_location.rs | 4 +-- compiler/rustc_errors/src/emitter.rs | 36 +++++++++---------- compiler/rustc_errors/src/json.rs | 6 ++-- compiler/rustc_errors/src/lib.rs | 6 ++-- .../rustc_expand/src/proc_macro_server.rs | 6 ++-- .../src/infer/error_reporting/mod.rs | 2 +- compiler/rustc_middle/src/mir/spanview.rs | 10 ++++-- .../rustc_mir_transform/src/coverage/mod.rs | 4 +-- compiler/rustc_save_analysis/src/lib.rs | 4 +-- compiler/rustc_span/src/lib.rs | 24 ++++++++----- compiler/rustc_span/src/source_map.rs | 14 ++++---- compiler/rustc_span/src/source_map/tests.rs | 4 +-- src/librustdoc/doctest.rs | 2 +- src/librustdoc/html/render/context.rs | 6 ++-- src/librustdoc/json/conversions.rs | 4 +-- .../internal_lints/metadata_collector.rs | 4 +-- src/tools/clippy/clippy_utils/src/sugg.rs | 2 +- src/tools/rustfmt/src/parse/session.rs | 10 ++++-- 24 files changed, 91 insertions(+), 71 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index 8bf3a0799b638..b00348de7276a 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -30,7 +30,7 @@ pub fn expand_line( let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.source_map().lookup_char_pos(topmost.lo()); - base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32)) + base::MacEager::expr(cx.expr_u32(topmost, loc.line.to_u32())) } /* column!(): expands to the current column number */ diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index f9dc1b5169e1a..c2307fe51e709 100644 --- a/compiler/rustc_codegen_cranelift/src/common.rs +++ b/compiler/rustc_codegen_cranelift/src/common.rs @@ -349,7 +349,7 @@ impl<'tcx> FunctionCx<'_, '_, 'tcx> { rustc_span::symbol::Symbol::intern( &caller.file.name.prefer_remapped().to_string_lossy(), ), - caller.line as u32, + caller.line.to_u32(), caller.col_display as u32 + 1, )); crate::constant::codegen_const_value(fx, const_loc, fx.tcx.caller_location_ty()) diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs index bbcb9591373dd..8fc88f6a02f9b 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs @@ -109,7 +109,7 @@ impl<'tcx> DebugContext<'tcx> { let entry = self.dwarf.unit.get_mut(entry_id); entry.set(gimli::DW_AT_decl_file, AttributeValue::FileIndex(Some(file_id))); - entry.set(gimli::DW_AT_decl_line, AttributeValue::Udata(loc.line as u64)); + entry.set(gimli::DW_AT_decl_line, AttributeValue::Udata(loc.line.to_usize() as u64)); entry.set(gimli::DW_AT_decl_column, AttributeValue::Udata(loc.col.to_usize() as u64)); } diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index bb0793b1deb2e..73cc849d35c0b 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -71,7 +71,7 @@ mod value_and_place; mod vtable; mod prelude { - pub(crate) use rustc_span::{FileNameDisplayPreference, Span}; + pub(crate) use rustc_span::{FileNameDisplayPreference, Pos, Span}; pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE}; pub(crate) use rustc_middle::bug; diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 3eee58d9d1c84..fdda43fab2c24 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -19,7 +19,7 @@ use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; use rustc_middle::ty::{self, Instance, Ty, TypeVisitable}; use rustc_span::source_map::Span; -use rustc_span::{sym, Symbol}; +use rustc_span::{sym, Pos, Symbol}; use rustc_symbol_mangling::typeid::typeid_for_fnabi; use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode}; use rustc_target::abi::{self, HasDataLayout, WrappingRange}; @@ -1290,7 +1290,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo()); let const_loc = tcx.const_caller_location(( Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()), - caller.line as u32, + caller.line.to_u32(), caller.col_display as u32 + 1, )); OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty()) diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 150d6589b0807..8ecb8eda79999 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -270,7 +270,7 @@ impl<'tcx> fmt::Display for FrameInfo<'tcx> { f, " at {}:{}:{}", sm.filename_for_diagnostics(&lo.file.name), - lo.line, + lo.line.to_usize(), lo.col.to_usize() + 1 )?; } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs index 5864b92155287..3c9669bae0b34 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs @@ -5,7 +5,7 @@ use rustc_hir::lang_items::LangItem; use rustc_middle::mir::TerminatorKind; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::subst::Subst; -use rustc_span::{Span, Symbol}; +use rustc_span::{Pos, Span, Symbol}; use crate::interpret::{ intrinsics::{InterpCx, Machine}, @@ -118,7 +118,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); ( Symbol::intern(&caller.file.name.prefer_remapped().to_string_lossy()), - u32::try_from(caller.line).unwrap(), + caller.line.to_u32(), u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(), ) } diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 61d953cd6f1cc..758e0032bb974 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -10,7 +10,7 @@ use Destination::*; use rustc_span::source_map::SourceMap; -use rustc_span::{FileLines, SourceFile, Span}; +use rustc_span::{FileLines, Pos, SourceFile, Span}; use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString}; use crate::styled_buffer::StyledBuffer; @@ -1293,14 +1293,14 @@ impl EmitterWriter { for primary_span in msp.primary_spans() { if will_be_emitted(*primary_span) { let hi = sm.lookup_char_pos(primary_span.hi()); - max = (hi.line).max(max); + max = (hi.line.to_usize()).max(max); } } if !self.short_message { for span_label in msp.span_labels() { if will_be_emitted(span_label.span) { let hi = sm.lookup_char_pos(span_label.span.hi()); - max = (hi.line).max(max); + max = (hi.line.to_usize()).max(max); } } } @@ -1498,7 +1498,7 @@ impl EmitterWriter { &format!( "{}:{}:{}", sm.filename_for_diagnostics(&loc.file.name), - sm.doctest_offset_line(&loc.file.name, loc.line), + sm.doctest_offset_line(&loc.file.name, loc.line.to_usize()), loc.col.0 + 1, ), Style::LineAndColumn, @@ -1512,7 +1512,7 @@ impl EmitterWriter { &format!( "{}:{}:{}: ", sm.filename_for_diagnostics(&loc.file.name), - sm.doctest_offset_line(&loc.file.name, loc.line), + sm.doctest_offset_line(&loc.file.name, loc.line.to_usize()), loc.col.0 + 1, ), Style::LineAndColumn, @@ -1795,7 +1795,7 @@ impl EmitterWriter { &format!( "{}:{}:{}", sm.filename_for_diagnostics(&loc.file.name), - sm.doctest_offset_line(&loc.file.name, loc.line), + sm.doctest_offset_line(&loc.file.name, loc.line.to_usize()), loc.col.0 + 1, ), Style::LineAndColumn, @@ -1832,27 +1832,27 @@ impl EmitterWriter { if lines.clone().next().is_none() { // Account for a suggestion to completely remove a line(s) with whitespace (#94192). let line_end = sm.lookup_char_pos(parts[0].span.hi()).line; - for line in line_start..=line_end { + for line in line_start.to_usize()..=line_end.to_usize() { buffer.puts( - row_num - 1 + line - line_start, + row_num - 1 + line - line_start.to_usize(), 0, &self.maybe_anonymized(line), Style::LineNumber, ); buffer.puts( - row_num - 1 + line - line_start, + row_num - 1 + line - line_start.to_usize(), max_line_num_len + 1, "- ", Style::Removal, ); buffer.puts( - row_num - 1 + line - line_start, + row_num - 1 + line - line_start.to_usize(), max_line_num_len + 3, &normalize_whitespace(&*file_lines.file.get_line(line - 1).unwrap()), Style::Removal, ); } - row_num += line_end - line_start; + row_num += line_end.to_usize() - line_start.to_usize(); } let mut unhighlighted_lines = Vec::new(); for (line_pos, (line, highlight_parts)) in lines.by_ref().zip(highlights).enumerate() { @@ -1877,7 +1877,7 @@ impl EmitterWriter { &Vec::new(), p, l, - line_start, + line_start.to_usize(), show_code_change, max_line_num_len, &file_lines, @@ -1902,7 +1902,7 @@ impl EmitterWriter { &Vec::new(), p, l, - line_start, + line_start.to_usize(), show_code_change, max_line_num_len, &file_lines, @@ -1920,7 +1920,7 @@ impl EmitterWriter { &Vec::new(), p, l, - line_start, + line_start.to_usize(), show_code_change, max_line_num_len, &file_lines, @@ -1936,7 +1936,7 @@ impl EmitterWriter { highlight_parts, line_pos, line, - line_start, + line_start.to_usize(), show_code_change, max_line_num_len, &file_lines, @@ -2275,8 +2275,8 @@ impl FileWithAnnotatedLines { if lo.line != hi.line { let ml = MultilineAnnotation { depth: 1, - line_start: lo.line, - line_end: hi.line, + line_start: lo.line.to_usize(), + line_end: hi.line.to_usize(), start_col: lo.col_display, end_col: hi.col_display, is_primary: span_label.is_primary, @@ -2298,7 +2298,7 @@ impl FileWithAnnotatedLines { .map(|m| emitter.translate_message(m, args).to_string()), annotation_type: AnnotationType::Singleline, }; - add_annotation_to_file(&mut output, lo.file, lo.line, ann); + add_annotation_to_file(&mut output, lo.file, lo.line.to_usize(), ann); }; } } diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index b8cd334b4c6c6..6a00c9f292d99 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -22,7 +22,7 @@ use rustc_lint_defs::Applicability; use rustc_data_structures::sync::Lrc; use rustc_error_messages::FluentArgs; use rustc_span::hygiene::ExpnData; -use rustc_span::Span; +use rustc_span::{Pos, Span}; use std::io::{self, Write}; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -453,8 +453,8 @@ impl DiagnosticSpan { file_name: je.sm.filename_for_diagnostics(&start.file.name).to_string(), byte_start: start.file.original_relative_byte_pos(span.lo()).0, byte_end: start.file.original_relative_byte_pos(span.hi()).0, - line_start: start.line, - line_end: end.line, + line_start: start.line.to_usize(), + line_end: end.line.to_usize(), column_start: start.col.0 + 1, column_end: end.col.0 + 1, is_primary, diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 15c1858023de7..13f80cb25981f 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -284,14 +284,14 @@ impl CodeSuggestion { count -= 1; } // push lines between the previous and current span (if any) - for idx in prev_hi.line..(cur_lo.line - 1) { + for idx in prev_hi.line.to_usize()..(cur_lo.line.to_usize() - 1) { if let Some(line) = sf.get_line(idx) { buf.push_str(line.as_ref()); buf.push('\n'); highlights.push(std::mem::take(&mut line_highlight)); } } - if let Some(cur_line) = sf.get_line(cur_lo.line - 1) { + if let Some(cur_line) = sf.get_line(cur_lo.line.to_usize() - 1) { let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) { Some((i, _)) => i, None => cur_line.len(), @@ -324,7 +324,7 @@ impl CodeSuggestion { acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize; } prev_hi = cur_hi; - prev_line = sf.get_line(prev_hi.line - 1); + prev_line = sf.get_line(prev_hi.line.to_usize() - 1); for line in part.snippet.split('\n').skip(1) { acc = 0; highlights.push(std::mem::take(&mut line_highlight)); diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 7d9a4aed0bf54..3f103b8bd41ce 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -632,12 +632,14 @@ impl server::Span for Rustc<'_, '_> { fn start(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess().source_map().lookup_char_pos(span.lo()); - LineColumn { line: loc.line, column: loc.col.to_usize() } + //FIXME: LineColumn.column is 1-based, but loc.col is 0-based + LineColumn { line: loc.line.to_usize(), column: loc.col.to_usize() } } fn end(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess().source_map().lookup_char_pos(span.hi()); - LineColumn { line: loc.line, column: loc.col.to_usize() } + //FIXME: and here + LineColumn { line: loc.line.to_usize(), column: loc.col.to_usize() } } fn before(&mut self, span: Self::Span) -> Self::Span { diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 20864c657ffd7..e74b04be74fa7 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1658,7 +1658,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { format!( " (opaque type at <{}:{}:{}>)", sm.filename_for_diagnostics(&pos.file.name), - pos.line, + pos.line.to_usize(), pos.col.to_usize() + 1, ) } diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs index 4418b848e512a..52bf52bd56454 100644 --- a/compiler/rustc_middle/src/mir/spanview.rs +++ b/compiler/rustc_middle/src/mir/spanview.rs @@ -165,7 +165,7 @@ where write!( w, r#"
{}"#, - start.line - 1, + start.line.to_usize() - 1, indent_to_initial_start_col, )?; span_viewables.sort_unstable_by(|a, b| { @@ -234,7 +234,13 @@ pub fn source_range_no_file<'tcx>(tcx: TyCtxt<'tcx>, span: Span) -> String { let source_map = tcx.sess.source_map(); let start = source_map.lookup_char_pos(span.lo()); let end = source_map.lookup_char_pos(span.hi()); - format!("{}:{}-{}:{}", start.line, start.col.to_usize() + 1, end.line, end.col.to_usize() + 1) + format!( + "{}:{}-{}:{}", + start.line.to_usize(), + start.col.to_usize() + 1, + end.line.to_usize(), + end.col.to_usize() + 1 + ) } pub fn statement_kind_name(statement: &Statement<'_>) -> &'static str { diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 2619626a5675f..eddc2d9dedf37 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -522,8 +522,8 @@ fn make_code_region( } else { source_file.lookup_file_pos(span.hi()) }; - let start_line = source_map.doctest_offset_line(&source_file.name, start_line); - let end_line = source_map.doctest_offset_line(&source_file.name, end_line); + let start_line = source_map.doctest_offset_line(&source_file.name, start_line.to_usize()); + let end_line = source_map.doctest_offset_line(&source_file.name, end_line.to_usize()); CodeRegion { file_name, start_line: start_line as u32, diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index a1a2040bbca14..5b988010ddf82 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -83,8 +83,8 @@ impl<'tcx> SaveContext<'tcx> { file_name: start.file.name.prefer_remapped().to_string().into(), byte_start: span.lo().0, byte_end: span.hi().0, - line_start: Row::new_one_indexed(start.line as u32), - line_end: Row::new_one_indexed(end.line as u32), + line_start: Row::new_one_indexed(start.line.to_u32()), + line_end: Row::new_one_indexed(end.line.to_u32()), column_start: Column::new_one_indexed(start.col.0 as u32 + 1), column_end: Column::new_one_indexed(end.col.0 as u32 + 1), } diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index cf30692815147..86d4cdaac0ff7 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1692,31 +1692,31 @@ impl SourceFile { /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a /// given `BytePos`. - pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { + pub fn lookup_file_pos(&self, pos: BytePos) -> (LineNum, CharPos) { let chpos = self.bytepos_to_file_charpos(pos); match self.lookup_line(pos) { Some(a) => { - let line = a + 1; // Line numbers start at 1 + let line = LineNum(u32::try_from(a).unwrap() + 1); // Line numbers start at 1 let linebpos = self.lines(|lines| lines[a]); let linechpos = self.bytepos_to_file_charpos(linebpos); let col = 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); + debug!("byte is on line: {}", line.to_usize()); assert!(chpos >= linechpos); (line, col) } - None => (0, chpos), + None => (LineNum(0), chpos), } } /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) /// column offset when displayed, for a given `BytePos`. - pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { + pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (LineNum, CharPos, usize) { let (line, col_or_chpos) = self.lookup_file_pos(pos); - if line > 0 { + if line.to_usize() > 0 { let col = col_or_chpos; - let linebpos = self.lines(|lines| lines[line - 1]); + let linebpos = self.lines(|lines| lines[line.to_usize() - 1]); let col_display = { let start_width_idx = self .non_narrow_chars @@ -1745,7 +1745,7 @@ impl SourceFile { self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); chpos.0 - end_width_idx + non_narrow }; - (0, chpos, col_display) + (LineNum(0), chpos, col_display) } } } @@ -1912,6 +1912,12 @@ impl_pos! { /// values to `CharPos` values as necessary. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct CharPos(pub usize); + + /// A Line number + /// + /// 1-based + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] + pub struct LineNum(u32); } impl Encodable for BytePos { @@ -1936,7 +1942,7 @@ pub struct Loc { /// Information about the original source. pub file: Lrc, /// The (1-based) line number. - pub line: usize, + pub line: LineNum, /// The (0-based) column offset. pub col: CharPos, /// The (0-based) column offset when displayed. diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 28381157d50a9..09d94ed73c15c 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -451,9 +451,9 @@ impl SourceMap { format!( "{}:{}:{}: {}:{}", lo.file.name.display(filename_display_pref), - lo.line, + lo.line.to_usize(), lo.col.to_usize() + 1, - hi.line, + hi.line.to_usize(), hi.col.to_usize() + 1, ) } @@ -477,8 +477,8 @@ impl SourceMap { return self.span_to_embeddable_string(sp); } - let lo_line = lo.line.saturating_sub(offset.line); - let hi_line = hi.line.saturating_sub(offset.line); + let lo_line = lo.line.to_usize().saturating_sub(offset.line.to_usize()); + let hi_line = hi.line.to_usize().saturating_sub(offset.line.to_usize()); format!( "{}:+{}:{}: +{}:{}", @@ -546,7 +546,7 @@ impl SourceMap { return Ok(FileLines { file: lo.file, lines: Vec::new() }); } - let mut lines = Vec::with_capacity(hi.line - lo.line + 1); + let mut lines = Vec::with_capacity(hi.line.to_usize() - lo.line.to_usize() + 1); // The span starts partway through the first line, // but after that it starts from offset 0. @@ -559,8 +559,8 @@ impl SourceMap { // // FIXME: now that we handle DUMMY_SP up above, we should consider // asserting that the line numbers here are all indeed 1-based. - let hi_line = hi.line.saturating_sub(1); - for line_index in lo.line.saturating_sub(1)..hi_line { + let hi_line = hi.line.to_usize().saturating_sub(1); + for line_index in lo.line.to_usize().saturating_sub(1)..hi_line { let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count()); lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) }); start_col = CharPos::from_usize(0); diff --git a/compiler/rustc_span/src/source_map/tests.rs b/compiler/rustc_span/src/source_map/tests.rs index be827cea8744b..3a46c7d04ae4e 100644 --- a/compiler/rustc_span/src/source_map/tests.rs +++ b/compiler/rustc_span/src/source_map/tests.rs @@ -91,12 +91,12 @@ fn t5() { let loc1 = sm.lookup_char_pos(BytePos(22)); assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into()); - assert_eq!(loc1.line, 2); + assert_eq!(loc1.line.to_usize(), 2); assert_eq!(loc1.col, CharPos(10)); let loc2 = sm.lookup_char_pos(BytePos(25)); assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into()); - assert_eq!(loc2.line, 1); + assert_eq!(loc2.line.to_usize(), 1); assert_eq!(loc2.col, CharPos(0)); } diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 35964e3ba38e4..12b35e174c450 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -1142,7 +1142,7 @@ impl Tester for Collector { if let Some(ref source_map) = self.source_map { let line = self.position.lo().to_usize(); let line = source_map.lookup_char_pos(BytePos(line as u32)).line; - if line > 0 { line - 1 } else { line } + if line.to_usize() > 0 { line.to_usize() - 1 } else { line.to_usize() } } else { 0 } diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 2ed7a6f1bb144..010e8e990e376 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::edition::Edition; use rustc_span::source_map::FileName; -use rustc_span::{sym, Symbol}; +use rustc_span::{sym, Pos, Symbol}; use super::print_item::{full_path, item_path, print_item}; use super::search_index::build_index; @@ -357,9 +357,9 @@ impl<'tcx> Context<'tcx> { format!( "#{}", if loline == hiline { - loline.to_string() + loline.to_usize().to_string() } else { - format!("{}-{}", loline, hiline) + format!("{}-{}", loline.to_usize(), hiline.to_usize()) } ) } else { diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 4c21fd553289b..44e1d2b5b6ae9 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -77,8 +77,8 @@ impl JsonRenderer<'_> { let lo = span.lo(self.sess()); Some(Span { filename: local_path, - begin: (lo.line, lo.col.to_usize()), - end: (hi.line, hi.col.to_usize()), + begin: (lo.line.to_usize(), lo.col.to_usize()), + end: (hi.line.to_usize(), hi.col.to_usize()), }) } else { None diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs index 92934c16d4b40..dc918de160bcc 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/metadata_collector.rs @@ -23,7 +23,7 @@ use rustc_lint::{CheckLintNameResult, LateContext, LateLintPass, LintContext, Li use rustc_middle::hir::nested_filter; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::symbol::Ident; -use rustc_span::{sym, Loc, Span, Symbol}; +use rustc_span::{sym, Loc, Pos, Span, Symbol}; use serde::{ser::SerializeStruct, Serialize, Serializer}; use std::collections::BinaryHeap; use std::fmt; @@ -474,7 +474,7 @@ impl SerializableSpan { Self { path: format!("{}", loc.file.name.prefer_remapped()), - line: loc.line, + line: loc.line.to_usize(), } } } diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index bad291dfc2513..6fb7776d73bde 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -657,7 +657,7 @@ fn astbinop2assignop(op: ast::BinOp) -> AssocOp { fn indentation(cx: &T, span: Span) -> Option { let lo = cx.sess().source_map().lookup_char_pos(span.lo()); lo.file - .get_line(lo.line - 1 /* line numbers in `Loc` are 1-based */) + .get_line(lo.line.to_usize() - 1 /* line numbers in `Loc` are 1-based */) .and_then(|line| { if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') { // We can mix char and byte positions here because we only consider `[ \t]`. diff --git a/src/tools/rustfmt/src/parse/session.rs b/src/tools/rustfmt/src/parse/session.rs index 23db542191036..fe6e5261502c2 100644 --- a/src/tools/rustfmt/src/parse/session.rs +++ b/src/tools/rustfmt/src/parse/session.rs @@ -7,7 +7,7 @@ use rustc_errors::{ColorConfig, Diagnostic, Handler, Level as DiagnosticLevel}; use rustc_session::parse::ParseSess as RawParseSess; use rustc_span::{ source_map::{FilePathMapping, SourceMap}, - symbol, BytePos, Span, + symbol, BytePos, Pos, Span, }; use crate::config::file_lines::LineRange; @@ -233,7 +233,13 @@ impl ParseSess { } pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize { - self.parse_sess.source_map().lookup_char_pos(pos).line + //FIXME: this returns 1-based line number conveted into usize. + //Should it's base type be used instead? + self.parse_sess + .source_map() + .lookup_char_pos(pos) + .line + .to_usize() } // TODO(calebcartwright): Preemptive, currently unused addition From 41ba864809aec1d1ae2af0d6b2da2bd56141211d Mon Sep 17 00:00:00 2001 From: klensy Date: Tue, 9 Aug 2022 19:46:25 +0300 Subject: [PATCH 2/4] CharPos: usize -> u32, as BytePos is u32 --- compiler/rustc_ast/src/util/comments.rs | 3 ++- compiler/rustc_errors/src/emitter.rs | 6 +++--- compiler/rustc_errors/src/json.rs | 8 ++++---- compiler/rustc_errors/src/lib.rs | 7 ++++--- compiler/rustc_mir_transform/src/coverage/mod.rs | 5 ++--- compiler/rustc_save_analysis/src/lib.rs | 4 ++-- compiler/rustc_span/src/lib.rs | 12 +++++++----- compiler/rustc_span/src/source_map.rs | 2 +- src/tools/clippy/clippy_lints/src/formatting.rs | 4 ++-- src/tools/clippy/clippy_utils/src/sugg.rs | 2 +- 10 files changed, 28 insertions(+), 25 deletions(-) diff --git a/compiler/rustc_ast/src/util/comments.rs b/compiler/rustc_ast/src/util/comments.rs index c96474ccb428a..cb7ff46f9dc2f 100644 --- a/compiler/rustc_ast/src/util/comments.rs +++ b/compiler/rustc_ast/src/util/comments.rs @@ -225,7 +225,8 @@ pub fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec SaveContext<'tcx> { byte_end: span.hi().0, line_start: Row::new_one_indexed(start.line.to_u32()), line_end: Row::new_one_indexed(end.line.to_u32()), - column_start: Column::new_one_indexed(start.col.0 as u32 + 1), - column_end: Column::new_one_indexed(end.col.0 as u32 + 1), + column_start: Column::new_one_indexed(start.col.to_u32() + 1), + column_end: Column::new_one_indexed(end.col.to_u32() + 1), } } diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 86d4cdaac0ff7..b94aee1ec43a6 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1687,7 +1687,7 @@ impl SourceFile { } assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); - CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) + CharPos(bpos.to_u32() - self.start_pos.to_u32() - total_extra_bytes) } /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a @@ -1712,7 +1712,7 @@ impl SourceFile { /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) /// column offset when displayed, for a given `BytePos`. - pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (LineNum, CharPos, usize) { + pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (LineNum, CharPos, u32) { let (line, col_or_chpos) = self.lookup_file_pos(pos); if line.to_usize() > 0 { let col = col_or_chpos; @@ -1731,7 +1731,8 @@ impl SourceFile { .iter() .map(|x| x.width()) .sum(); - col.0 - special_chars + non_narrow + col.to_u32() - u32::try_from(special_chars).unwrap() + + u32::try_from(non_narrow).unwrap() }; (line, col, col_display) } else { @@ -1743,7 +1744,8 @@ impl SourceFile { .unwrap_or_else(|x| x); let non_narrow: usize = self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); - chpos.0 - end_width_idx + non_narrow + chpos.to_u32() - u32::try_from(end_width_idx).unwrap() + + u32::try_from(non_narrow).unwrap() }; (LineNum(0), chpos, col_display) } @@ -1911,7 +1913,7 @@ impl_pos! { /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] /// values to `CharPos` values as necessary. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] - pub struct CharPos(pub usize); + pub struct CharPos(u32); /// A Line number /// diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 09d94ed73c15c..bcf485306b633 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -428,7 +428,7 @@ impl SourceMap { pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { let sf = self.lookup_source_file(pos); let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos); - Loc { file: sf, line, col, col_display } + Loc { file: sf, line, col, col_display: col_display as usize } } // If the corresponding `SourceFile` is empty, does not return a line number. diff --git a/src/tools/clippy/clippy_lints/src/formatting.rs b/src/tools/clippy/clippy_lints/src/formatting.rs index db0166da57f0e..cc43a35ac51bf 100644 --- a/src/tools/clippy/clippy_lints/src/formatting.rs +++ b/src/tools/clippy/clippy_lints/src/formatting.rs @@ -5,7 +5,7 @@ use rustc_ast::ast::{BinOpKind, Block, Expr, ExprKind, StmtKind, UnOp}; use rustc_lint::{EarlyContext, EarlyLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::source_map::Span; +use rustc_span::source_map::{Pos, Span}; declare_clippy_lint! { /// ### What it does @@ -264,7 +264,7 @@ fn has_unary_equivalent(bin_op: BinOpKind) -> bool { } fn indentation(cx: &EarlyContext<'_>, span: Span) -> usize { - cx.sess().source_map().lookup_char_pos(span.lo()).col.0 + cx.sess().source_map().lookup_char_pos(span.lo()).col.to_usize() } /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index 6fb7776d73bde..3f39766867647 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -661,7 +661,7 @@ fn indentation(cx: &T, span: Span) -> Option { .and_then(|line| { if let Some((pos, _)) = line.char_indices().find(|&(_, c)| c != ' ' && c != '\t') { // We can mix char and byte positions here because we only consider `[ \t]`. - if lo.col == CharPos(pos) { + if lo.col == CharPos::from_usize(pos) { Some(line[..pos].into()) } else { None From 6169a1aaf387ee5339f160941d2fe627b1d51f5a Mon Sep 17 00:00:00 2001 From: klensy Date: Tue, 9 Aug 2022 21:12:10 +0300 Subject: [PATCH 3/4] use fallible convertions for Pos trait --- compiler/rustc_span/src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index b94aee1ec43a6..3fbef46a1884b 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1860,22 +1860,22 @@ macro_rules! impl_pos { impl Pos for $ident { #[inline(always)] fn from_usize(n: usize) -> $ident { - $ident(n as $inner_ty) + $ident(<$inner_ty>::try_from(n).unwrap()) } #[inline(always)] fn to_usize(&self) -> usize { - self.0 as usize + self.0.try_into().unwrap() } #[inline(always)] fn from_u32(n: u32) -> $ident { - $ident(n as $inner_ty) + $ident(<$inner_ty>::try_from(n).unwrap()) } #[inline(always)] fn to_u32(&self) -> u32 { - self.0 as u32 + self.0.try_into().unwrap() } } From a0f38f3414dc8343b06fd34c471894e298fdb5f4 Mon Sep 17 00:00:00 2001 From: klensy Date: Fri, 12 Aug 2022 15:50:52 +0300 Subject: [PATCH 4/4] proc_macro_server: fix 0-based to 1-based num convertion --- compiler/rustc_expand/src/proc_macro_server.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 3f103b8bd41ce..c336558f8d133 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -633,13 +633,13 @@ impl server::Span for Rustc<'_, '_> { fn start(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess().source_map().lookup_char_pos(span.lo()); //FIXME: LineColumn.column is 1-based, but loc.col is 0-based - LineColumn { line: loc.line.to_usize(), column: loc.col.to_usize() } + LineColumn { line: loc.line.to_usize(), column: loc.col.to_usize() + 1 } } fn end(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess().source_map().lookup_char_pos(span.hi()); //FIXME: and here - LineColumn { line: loc.line.to_usize(), column: loc.col.to_usize() } + LineColumn { line: loc.line.to_usize(), column: loc.col.to_usize() + 1 } } fn before(&mut self, span: Self::Span) -> Self::Span {