Skip to content
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

Migrate rustc_interface diagnostics #100808

Merged
merged 6 commits into from
Aug 25, 2022
Merged
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions compiler/rustc_error_messages/locales/en-US/interface.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,40 @@ interface_ferris_identifier =

interface_emoji_identifier =
identifiers cannot contain emoji: `{$ident}`

interface_mixed_bin_crate =
cannot mix `bin` crate type with others

interface_mixed_proc_macro_crate =
cannot mix `proc-macro` crate type with others

interface_proc_macro_doc_without_arg =
Trying to document proc macro crate without passing '--crate-type proc-macro to rustdoc
.warn = The generated documentation may be incorrect

interface_error_writing_dependencies =
error writing dependencies to `{$path}`: {$error}

interface_input_file_would_be_overwritten =
the input file "{$path}" would be overwritten by the generated executable

interface_generated_file_conflicts_with_directory =
the generated executable for the input file "{$input_path}" conflicts with the existing directory "{$dir_path}"

interface_temps_dir_error =
failed to find or create the directory specified by `--temps-dir`

interface_out_dir_error =
failed to find or create the directory specified by `--out-dir`

interface_cant_emit_mir =
could not emit MIR: {$error}

interface_rustc_error_fatal =
fatal error triggered by #[rustc_error]

interface_rustc_error_unexpected_annotation =
unexpected annotation used with `#[rustc_error(...)]!

interface_failed_writing_file =
failed to write file {$path}: {$error}"
14 changes: 14 additions & 0 deletions compiler/rustc_errors/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use rustc_span::{edition::Edition, Span, DUMMY_SP};
use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

/// Error type for `Diagnostic`'s `suggestions` field, indicating that
/// `.disable_suggestions()` was called on the `Diagnostic`.
Expand Down Expand Up @@ -83,6 +84,7 @@ into_diagnostic_arg_using_display!(
u64,
i128,
u128,
std::io::Error,
std::num::NonZeroU32,
hir::Target,
Edition,
Expand Down Expand Up @@ -124,6 +126,18 @@ impl IntoDiagnosticArg for String {
}
}

impl<'a> IntoDiagnosticArg for &'a Path {
fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
}
}

impl IntoDiagnosticArg for PathBuf {
fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
}
}

impl IntoDiagnosticArg for usize {
fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
DiagnosticArgValue::Number(self)
Expand Down
89 changes: 89 additions & 0 deletions compiler/rustc_interface/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use rustc_macros::SessionDiagnostic;
use rustc_span::{Span, Symbol};

use std::io;
use std::path::Path;

#[derive(SessionDiagnostic)]
#[diag(interface::ferris_identifier)]
pub struct FerrisIdentifier {
#[primary_span]
pub spans: Vec<Span>,
#[suggestion(code = "ferris", applicability = "maybe-incorrect")]
pub first_span: Span,
}

#[derive(SessionDiagnostic)]
#[diag(interface::emoji_identifier)]
pub struct EmojiIdentifier {
#[primary_span]
pub spans: Vec<Span>,
pub ident: Symbol,
}

#[derive(SessionDiagnostic)]
#[diag(interface::mixed_bin_crate)]
pub struct MixedBinCrate;

#[derive(SessionDiagnostic)]
#[diag(interface::mixed_proc_macro_crate)]
pub struct MixedProcMacroCrate;

#[derive(SessionDiagnostic)]
#[diag(interface::proc_macro_doc_without_arg)]
pub struct ProcMacroDocWithoutArg;

#[derive(SessionDiagnostic)]
#[diag(interface::error_writing_dependencies)]
pub struct ErrorWritingDependencies<'a> {
pub path: &'a Path,
pub error: io::Error,
}

#[derive(SessionDiagnostic)]
#[diag(interface::input_file_would_be_overwritten)]
pub struct InputFileWouldBeOverWritten<'a> {
pub path: &'a Path,
}

#[derive(SessionDiagnostic)]
#[diag(interface::generated_file_conflicts_with_directory)]
pub struct GeneratedFileConflictsWithDirectory<'a> {
pub input_path: &'a Path,
pub dir_path: &'a Path,
}

#[derive(SessionDiagnostic)]
#[diag(interface::temps_dir_error)]
pub struct TempsDirError;

#[derive(SessionDiagnostic)]
#[diag(interface::out_dir_error)]
pub struct OutDirError;

#[derive(SessionDiagnostic)]
#[diag(interface::cant_emit_mir)]
pub struct CantEmitMIR {
pub error: io::Error,
}

#[derive(SessionDiagnostic)]
#[diag(interface::rustc_error_fatal)]
pub struct RustcErrorFatal {
#[primary_span]
pub span: Span,
}

#[derive(SessionDiagnostic)]
#[diag(interface::rustc_error_unexpected_annotation)]
pub struct RustcErrorUnexpectedAnnotation {
#[primary_span]
pub span: Span,
}

#[derive(SessionDiagnostic)]
#[diag(interface::failed_writing_file)]
pub struct FailedWritingFile<'a> {
pub path: &'a Path,
pub error: io::Error,
}
3 changes: 3 additions & 0 deletions compiler/rustc_interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
#![feature(once_cell)]
#![recursion_limit = "256"]
#![allow(rustc::potential_query_instability)]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]

mod callbacks;
mod errors;
pub mod interface;
mod passes;
mod proc_macro_decls;
Expand Down
71 changes: 20 additions & 51 deletions compiler/rustc_interface/src/passes.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
use crate::errors::{
CantEmitMIR, EmojiIdentifier, ErrorWritingDependencies, FerrisIdentifier,
GeneratedFileConflictsWithDirectory, InputFileWouldBeOverWritten, MixedBinCrate,
MixedProcMacroCrate, OutDirError, ProcMacroDocWithoutArg, TempsDirError,
};
use crate::interface::{Compiler, Result};
use crate::proc_macro_decls;
use crate::util;
Expand All @@ -13,7 +18,6 @@ use rustc_expand::base::{ExtCtxt, LintStoreExpand, ResolverExpand};
use rustc_hir::def_id::StableCrateId;
use rustc_hir::definitions::Definitions;
use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore};
use rustc_macros::SessionDiagnostic;
use rustc_metadata::creader::CStore;
use rustc_middle::arena::Arena;
use rustc_middle::dep_graph::DepGraph;
Expand All @@ -31,7 +35,7 @@ use rustc_session::output::filename_for_input;
use rustc_session::search_paths::PathKind;
use rustc_session::{Limit, Session};
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{FileName, Span};
use rustc_span::FileName;
use rustc_trait_selection::traits;
use rustc_typeck as typeck;
use tracing::{info, warn};
Expand Down Expand Up @@ -264,23 +268,6 @@ impl LintStoreExpand for LintStoreExpandImpl<'_> {
}
}

#[derive(SessionDiagnostic)]
#[diag(interface::ferris_identifier)]
struct FerrisIdentifier {
#[primary_span]
spans: Vec<Span>,
#[suggestion(code = "ferris", applicability = "maybe-incorrect")]
first_span: Span,
}

#[derive(SessionDiagnostic)]
#[diag(interface::emoji_identifier)]
struct EmojiIdentifier {
#[primary_span]
spans: Vec<Span>,
ident: Symbol,
}

/// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins,
/// syntax expansion, secondary `cfg` expansion, synthesis of a test
/// harness if one is to be provided, injection of a dependency on the
Expand Down Expand Up @@ -392,10 +379,10 @@ pub fn configure_and_expand(

if crate_types.len() > 1 {
if is_executable_crate {
sess.err("cannot mix `bin` crate type with others");
sess.emit_err(MixedBinCrate);
}
if is_proc_macro_crate {
sess.err("cannot mix `proc-macro` crate type with others");
sess.emit_err(MixedProcMacroCrate);
}
}

Expand All @@ -406,13 +393,7 @@ pub fn configure_and_expand(
// However, we do emit a warning, to let such users know that they should
// start passing '--crate-type proc-macro'
if has_proc_macro_decls && sess.opts.actually_rustdoc && !is_proc_macro_crate {
let mut msg = sess.diagnostic().struct_warn(
"Trying to document proc macro crate \
without passing '--crate-type proc-macro to rustdoc",
);

msg.warn("The generated documentation may be incorrect");
msg.emit();
sess.emit_warning(ProcMacroDocWithoutArg);
} else {
krate = sess.time("maybe_create_a_macro_crate", || {
let is_test_crate = sess.opts.test;
Expand Down Expand Up @@ -666,11 +647,9 @@ fn write_out_deps(
.emit_artifact_notification(&deps_filename, "dep-info");
}
}
Err(e) => sess.fatal(&format!(
"error writing dependencies to `{}`: {}",
deps_filename.display(),
e
)),
Err(error) => {
sess.emit_fatal(ErrorWritingDependencies { path: &deps_filename, error });
}
}
}

Expand Down Expand Up @@ -700,29 +679,20 @@ pub fn prepare_outputs(
if let Some(ref input_path) = compiler.input_path {
if sess.opts.will_create_output_file() {
if output_contains_path(&output_paths, input_path) {
let reported = sess.err(&format!(
"the input file \"{}\" would be overwritten by the generated \
executable",
input_path.display()
));
let reported = sess.emit_err(InputFileWouldBeOverWritten { path: input_path });
return Err(reported);
}
if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
let reported = sess.err(&format!(
"the generated executable for the input file \"{}\" conflicts with the \
existing directory \"{}\"",
input_path.display(),
dir_path.display()
));
if let Some(ref dir_path) = output_conflicts_with_dir(&output_paths) {
let reported =
sess.emit_err(GeneratedFileConflictsWithDirectory { input_path, dir_path });
return Err(reported);
}
}
}

if let Some(ref dir) = compiler.temps_dir {
if fs::create_dir_all(dir).is_err() {
let reported =
sess.err("failed to find or create the directory specified by `--temps-dir`");
let reported = sess.emit_err(TempsDirError);
return Err(reported);
}
}
Expand All @@ -735,8 +705,7 @@ pub fn prepare_outputs(
if !only_dep_info {
if let Some(ref dir) = compiler.output_dir {
if fs::create_dir_all(dir).is_err() {
let reported =
sess.err("failed to find or create the directory specified by `--out-dir`");
let reported = sess.emit_err(OutDirError);
return Err(reported);
}
}
Expand Down Expand Up @@ -1019,8 +988,8 @@ pub fn start_codegen<'tcx>(
info!("Post-codegen\n{:?}", tcx.debug_stats());

if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
if let Err(e) = rustc_mir_transform::dump_mir::emit_mir(tcx, outputs) {
tcx.sess.err(&format!("could not emit MIR: {}", e));
if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx, outputs) {
tcx.sess.emit_err(CantEmitMIR { error });
tcx.sess.abort_if_errors();
}
}
Expand Down
18 changes: 7 additions & 11 deletions compiler/rustc_interface/src/queries.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::errors::{FailedWritingFile, RustcErrorFatal, RustcErrorUnexpectedAnnotation};
use crate::interface::{Compiler, Result};
use crate::passes::{self, BoxedResolver, QueryContext};

Expand Down Expand Up @@ -274,18 +275,14 @@ impl<'tcx> Queries<'tcx> {

// Bare `#[rustc_error]`.
None => {
tcx.sess.span_fatal(
tcx.def_span(def_id),
"fatal error triggered by #[rustc_error]",
);
tcx.sess.emit_fatal(RustcErrorFatal { span: tcx.def_span(def_id) });
}

// Some other attribute.
Some(_) => {
tcx.sess.span_warn(
tcx.def_span(def_id),
"unexpected annotation used with `#[rustc_error(...)]!",
);
tcx.sess.emit_warning(RustcErrorUnexpectedAnnotation {
span: tcx.def_span(def_id),
});
}
}
}
Expand Down Expand Up @@ -360,9 +357,8 @@ impl Linker {
if sess.opts.unstable_opts.no_link {
let encoded = CodegenResults::serialize_rlink(&codegen_results);
let rlink_file = self.prepare_outputs.with_extension(config::RLINK_EXT);
std::fs::write(&rlink_file, encoded).map_err(|err| {
sess.fatal(&format!("failed to write file {}: {}", rlink_file.display(), err));
})?;
std::fs::write(&rlink_file, encoded)
.map_err(|error| sess.emit_fatal(FailedWritingFile { path: &rlink_file, error }))?;
return Ok(());
}

Expand Down