Skip to content

Include scope names in diagnostics #49898

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
11 changes: 9 additions & 2 deletions src/librustc_driver/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,11 @@ pub fn compile_input(
)?
};

// Let diagnostics access the AST for allowing to show function names in messages.
let expanded_crate = Lrc::new(expanded_crate);
sess.diagnostic().set_ast(
Box::new(syntax::diagnostics::ast::ContextResolver::new(expanded_crate.clone())));

let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);

// Ensure the source file isn't accidentally overwritten during compilation.
Expand Down Expand Up @@ -257,7 +262,7 @@ pub fn compile_input(
&hir_map,
&analysis,
&resolutions,
&expanded_crate,
&*expanded_crate,
&hir_map.krate(),
&outputs,
&crate_name
Expand All @@ -267,8 +272,10 @@ pub fn compile_input(
}

let opt_crate = if control.keep_ast {
Some(&expanded_crate)
Some(&*expanded_crate)
} else {
// AST will be kept for scope naming in diagnostic, should
// depricate keep_ast?
drop(expanded_crate);
None
};
Expand Down
38 changes: 38 additions & 0 deletions src/librustc_errors/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ use std::cmp::min;
use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter};
use termcolor::{WriteColor, Color, Buffer};
use unicode_width;
use SpanContextResolver;
use SpanContextKind;
use SpanContext;
use std::cell::RefCell;

const ANONYMIZED_LINE_NUM: &str = "LL";

Expand Down Expand Up @@ -81,6 +85,7 @@ impl Emitter for EmitterWriter {
self.emit_messages_default(&db.level,
&db.styled_message(),
&db.code,
&db.handler.context_resolver,
&primary_span,
&children,
&suggestions);
Expand Down Expand Up @@ -958,6 +963,7 @@ impl EmitterWriter {
msp: &MultiSpan,
msg: &Vec<(String, Style)>,
code: &Option<DiagnosticId>,
cr: &RefCell<Option<Box<SpanContextResolver>>>,
level: &Level,
max_line_num_len: usize,
is_secondary: bool)
Expand Down Expand Up @@ -1042,6 +1048,18 @@ impl EmitterWriter {
cm.doctest_offset_line(loc.line),
loc.col.0 + 1),
Style::LineAndColumn);
if let Some(ref primary_span) = msp.primary_span().as_ref() {
if primary_span != &&DUMMY_SP {
if let &Some(ref rc) = &*cr.borrow() {
let context = rc.span_to_context(**primary_span);
if let Some(context) = context {
repr_styled_context(buffer_msg_line_offset,
&mut buffer, context);
}
}
}
}

for _ in 0..max_line_num_len {
buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
}
Expand Down Expand Up @@ -1282,6 +1300,7 @@ impl EmitterWriter {
level: &Level,
message: &Vec<(String, Style)>,
code: &Option<DiagnosticId>,
cr: &RefCell<Option<Box<SpanContextResolver>>>,
span: &MultiSpan,
children: &Vec<SubDiagnostic>,
suggestions: &[CodeSuggestion]) {
Expand All @@ -1294,6 +1313,7 @@ impl EmitterWriter {
match self.emit_message_default(span,
message,
code,
cr,
level,
max_line_num_len,
false) {
Expand All @@ -1315,6 +1335,7 @@ impl EmitterWriter {
match self.emit_message_default(&span,
&child.styled_message(),
&None,
cr,
&child.level,
max_line_num_len,
true) {
Expand Down Expand Up @@ -1396,6 +1417,23 @@ fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
}

fn repr_styled_context(line_offset: usize, buffer: &mut StyledBuffer, context: SpanContext)
{
let kind_str = match context.kind {
SpanContextKind::Enum => "enum",
SpanContextKind::Module => "mod",
SpanContextKind::Function => "fn",
SpanContextKind::Impl => "impl",
SpanContextKind::Method => "fn",
SpanContextKind::Struct => "struct",
SpanContextKind::Trait => "trait",
SpanContextKind::Union => "union",
};

buffer.append(line_offset, &format!(": in {}", kind_str), Style::NoStyle);
buffer.append(line_offset, &format!(" {}", context.path), Style::HeaderMsg);
}

fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
lvl: &Level,
dst: &mut Destination,
Expand Down
36 changes: 35 additions & 1 deletion src/librustc_errors/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::stable_hasher::StableHasher;

use std::borrow::Cow;
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::{error, fmt};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
Expand Down Expand Up @@ -286,6 +286,9 @@ pub struct Handler {
// this handler. These hashes is used to avoid emitting the same error
// twice.
emitted_diagnostics: Lock<FxHashSet<u128>>,

// Callback to the Span AST resolver
context_resolver: RefCell<Option<Box<SpanContextResolver>>>,
}

fn default_track_diagnostic(_: &Diagnostic) {}
Expand All @@ -300,6 +303,32 @@ pub struct HandlerFlags {
pub external_macro_backtrace: bool,
}

pub enum SpanContextKind {
Enum,
Function,
Impl,
Method,
Struct,
Trait,
Union,
Module,
}

pub struct SpanContext {
kind: SpanContextKind,
path: String,
}

impl SpanContext {
pub fn new(kind: SpanContextKind, path: String) -> Self {
Self { kind, path }
}
}

pub trait SpanContextResolver {
fn span_to_context(&self, sp: Span) -> Option<SpanContext>;
}

impl Handler {
pub fn with_tty_emitter(color_config: ColorConfig,
can_emit_warnings: bool,
Expand Down Expand Up @@ -347,9 +376,14 @@ impl Handler {
taught_diagnostics: Lock::new(FxHashSet()),
emitted_diagnostic_codes: Lock::new(FxHashSet()),
emitted_diagnostics: Lock::new(FxHashSet()),
context_resolver: RefCell::new(None),
}
}

pub fn set_ast(&self, scr: Box<SpanContextResolver>) {
*self.context_resolver.borrow_mut() = Some(scr);
}

pub fn set_continue_after_error(&self, continue_after_error: bool) {
self.continue_after_error.set(continue_after_error);
}
Expand Down
109 changes: 109 additions & 0 deletions src/libsyntax/diagnostics/ast.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use ast::*;
use errors::{SpanContextResolver, SpanContextKind, SpanContext};
use rustc_data_structures::sync::Lrc;
use syntax_pos::Span;
use visit::{self, Visitor, FnKind};

pub struct ContextResolver {
krate: Lrc<Crate>
}

impl ContextResolver {
pub fn new(krate: Lrc<Crate>) -> Self {
Self { krate }
}
}

struct SpanResolver {
idents: Vec<Ident>,
kind: Option<SpanContextKind>,
span: Span,
}

impl<'ast> Visitor<'ast> for SpanResolver {
fn visit_trait_item(&mut self, ti: &'ast TraitItem) {
if ti.span.proper_contains(self.span) {
self.idents.push(ti.ident);
self.kind = Some(SpanContextKind::Trait);
visit::walk_trait_item(self, ti)
}
}

fn visit_impl_item(&mut self, ii: &'ast ImplItem) {
if ii.span.proper_contains(self.span) {
self.idents.push(ii.ident);
self.kind = Some(SpanContextKind::Impl);
visit::walk_impl_item(self, ii)
}
}

fn visit_item(&mut self, i: &'ast Item) {
if i.span.proper_contains(self.span) {
let kind = match i.node {
ItemKind::Enum(..) => Some(SpanContextKind::Enum),
ItemKind::Struct(..) => Some(SpanContextKind::Struct),
ItemKind::Union(..) => Some(SpanContextKind::Union),
ItemKind::Trait(..) => Some(SpanContextKind::Trait),
ItemKind::Mod(..) => Some(SpanContextKind::Module),
_ => None,
};

if kind.is_some() {
self.idents.push(i.ident);
self.kind = kind;
}

visit::walk_item(self, i);
}
}

fn visit_fn(&mut self, fk: FnKind<'ast>, fd: &'ast FnDecl, s: Span, _: NodeId) {
if s.proper_contains(self.span) {
match fk {
FnKind::ItemFn(ref ident, ..) => {
self.idents.push(*ident);
self.kind = Some(SpanContextKind::Function);
}
FnKind::Method(ref ident, ..) => {
self.idents.push(*ident);
self.kind = Some(SpanContextKind::Method);
}
_ => {}
}

visit::walk_fn(self, fk, fd, s)
}
}
}

impl SpanContextResolver for ContextResolver {
fn span_to_context(&self, sp: Span) -> Option<SpanContext> {
let mut sr = SpanResolver {
idents: Vec::new(),
span: sp,
kind: None,
};
visit::walk_crate(&mut sr, &*self.krate);

let SpanResolver { kind, idents, .. } = sr;

match kind {
None => None,
Some(kind) => {
let path = idents.iter().map(
|x| x.to_string()).collect::<Vec<String>>().join("::");
Some(SpanContext::new(kind, path))
}
}
}
}
1 change: 1 addition & 0 deletions src/libsyntax/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ pub mod diagnostics {
pub mod macros;
pub mod plugin;
pub mod metadata;
pub mod ast;
}

// NB: This module needs to be declared first so diagnostics are
Expand Down
6 changes: 6 additions & 0 deletions src/libsyntax_pos/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,12 @@ impl Span {
span.lo <= other.lo && other.hi <= span.hi
}

pub fn proper_contains(self, other: Span) -> bool {
let span = self.data();
let other = other.data();
span.lo < other.lo && other.hi < span.hi
}

/// Return true if the spans are equal with regards to the source text.
///
/// Use this instead of `==` when either span could be generated code,
Expand Down
Loading