Skip to content

Commit ac5f595

Browse files
committed
Auto merge of #24884 - michaelsproul:extended-errors, r=nrc
I've been working on improving the diagnostic registration system so that it can: * Check uniqueness of error codes *across the whole compiler*. The current method using `errorck.py` is prone to failure as it relies on simple text search - I found that it breaks when referencing an error's ident within a string (e.g. `"See also E0303"`). * Provide JSON output of error metadata, to eventually facilitate HTML output, as well as tracking of which errors need descriptions. The current schema is: ``` <error code>: { "description": <long description>, "use_site": { "filename": <filename where error is used>, "line": <line in file where error is used> } } ``` [Here's][metadata-dump] a pretty-printed sample dump for `librustc`. One thing to note is that I had to move the diagnostics arrays out of the diagnostics modules. I really wanted to be able to capture error usage information, which only becomes available as a crate is compiled. Hence all invocations of `__build_diagnostics_array!` have been moved to the ends of their respective `lib.rs` files. I tried to avoid moving the array by making a plugin that expands to nothing but couldn't invoke it in item position and gave up on hackily generating a fake item. I also briefly considered using a lint, but it seemed like it would impossible to get access to the data stored in the thread-local storage. The next step will be to generate a web page that lists each error with its rendered description and use site. Simple mapping and filtering of the metadata files also allows us to work out which error numbers are absent, which errors are unused and which need descriptions. [metadata-dump]: https://gist.github.com/michaelsproul/3246846ff1bea71bd049
2 parents 5449f5d + d27230b commit ac5f595

File tree

13 files changed

+244
-46
lines changed

13 files changed

+244
-46
lines changed

src/librustc/diagnostics.rs

-2
Original file line numberDiff line numberDiff line change
@@ -550,5 +550,3 @@ register_diagnostics! {
550550
E0316, // nested quantification of lifetimes
551551
E0370 // discriminant overflow
552552
}
553-
554-
__build_diagnostic_array! { DIAGNOSTICS }

src/librustc/lib.rs

+6
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,9 @@ pub mod lib {
161161
mod rustc {
162162
pub use lint;
163163
}
164+
165+
// Build the diagnostics array at the end so that the metadata includes error use sites.
166+
#[cfg(stage0)]
167+
__build_diagnostic_array! { DIAGNOSTICS }
168+
#[cfg(not(stage0))]
169+
__build_diagnostic_array! { librustc, DIAGNOSTICS }

src/librustc_borrowck/diagnostics.rs

-2
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,3 @@
1313
register_diagnostics! {
1414
E0373 // closure may outlive current fn, but it borrows {}, which is owned by current fn
1515
}
16-
17-
__build_diagnostic_array! { DIAGNOSTICS }

src/librustc_borrowck/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,8 @@ pub mod diagnostics;
4646
mod borrowck;
4747

4848
pub mod graphviz;
49+
50+
#[cfg(stage0)]
51+
__build_diagnostic_array! { DIAGNOSTICS }
52+
#[cfg(not(stage0))]
53+
__build_diagnostic_array! { librustc_borrowck, DIAGNOSTICS }

src/librustc_driver/lib.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -853,9 +853,10 @@ pub fn diagnostics_registry() -> diagnostics::registry::Registry {
853853
use syntax::diagnostics::registry::Registry;
854854

855855
let all_errors = Vec::new() +
856-
&rustc::diagnostics::DIAGNOSTICS[..] +
857-
&rustc_typeck::diagnostics::DIAGNOSTICS[..] +
858-
&rustc_resolve::diagnostics::DIAGNOSTICS[..];
856+
&rustc::DIAGNOSTICS[..] +
857+
&rustc_typeck::DIAGNOSTICS[..] +
858+
&rustc_borrowck::DIAGNOSTICS[..] +
859+
&rustc_resolve::DIAGNOSTICS[..];
859860

860861
Registry::new(&*all_errors)
861862
}

src/librustc_resolve/diagnostics.rs

-2
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,3 @@ register_diagnostics! {
2828
E0364, // item is private
2929
E0365 // item is private
3030
}
31-
32-
__build_diagnostic_array! { DIAGNOSTICS }

src/librustc_resolve/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -3706,3 +3706,8 @@ pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
37063706
},
37073707
}
37083708
}
3709+
3710+
#[cfg(stage0)]
3711+
__build_diagnostic_array! { DIAGNOSTICS }
3712+
#[cfg(not(stage0))]
3713+
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }

src/librustc_typeck/diagnostics.rs

-2
Original file line numberDiff line numberDiff line change
@@ -188,5 +188,3 @@ register_diagnostics! {
188188
E0371, // impl Trait for Trait is illegal
189189
E0372 // impl Trait for Trait where Trait is not object safe
190190
}
191-
192-
__build_diagnostic_array! { DIAGNOSTICS }

src/librustc_typeck/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -343,3 +343,8 @@ pub fn check_crate(tcx: &ty::ctxt, trait_map: ty::TraitMap) {
343343
check_for_entry_fn(&ccx);
344344
tcx.sess.abort_if_errors();
345345
}
346+
347+
#[cfg(stage0)]
348+
__build_diagnostic_array! { DIAGNOSTICS }
349+
#[cfg(not(stage0))]
350+
__build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }

src/libsyntax/diagnostics/metadata.rs

+155
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
//! This module contains utilities for outputting metadata for diagnostic errors.
12+
//!
13+
//! Each set of errors is mapped to a metadata file by a name, which is
14+
//! currently always a crate name.
15+
16+
use std::collections::BTreeMap;
17+
use std::env;
18+
use std::path::PathBuf;
19+
use std::fs::{read_dir, create_dir_all, OpenOptions, File};
20+
use std::io::{Read, Write};
21+
use std::error::Error;
22+
use rustc_serialize::json::{self, as_json};
23+
24+
use codemap::Span;
25+
use ext::base::ExtCtxt;
26+
use diagnostics::plugin::{ErrorMap, ErrorInfo};
27+
28+
pub use self::Uniqueness::*;
29+
30+
// Default metadata directory to use for extended error JSON.
31+
const ERROR_METADATA_DIR_DEFAULT: &'static str = "tmp/extended-errors";
32+
33+
// The name of the environment variable that sets the metadata dir.
34+
const ERROR_METADATA_VAR: &'static str = "ERROR_METADATA_DIR";
35+
36+
/// JSON encodable/decodable version of `ErrorInfo`.
37+
#[derive(PartialEq, RustcDecodable, RustcEncodable)]
38+
pub struct ErrorMetadata {
39+
pub description: Option<String>,
40+
pub use_site: Option<ErrorLocation>
41+
}
42+
43+
/// Mapping from error codes to metadata that can be (de)serialized.
44+
pub type ErrorMetadataMap = BTreeMap<String, ErrorMetadata>;
45+
46+
/// JSON encodable error location type with filename and line number.
47+
#[derive(PartialEq, RustcDecodable, RustcEncodable)]
48+
pub struct ErrorLocation {
49+
pub filename: String,
50+
pub line: usize
51+
}
52+
53+
impl ErrorLocation {
54+
/// Create an error location from a span.
55+
pub fn from_span(ecx: &ExtCtxt, sp: Span) -> ErrorLocation {
56+
let loc = ecx.codemap().lookup_char_pos_adj(sp.lo);
57+
ErrorLocation {
58+
filename: loc.filename,
59+
line: loc.line
60+
}
61+
}
62+
}
63+
64+
/// Type for describing the uniqueness of a set of error codes, as returned by `check_uniqueness`.
65+
pub enum Uniqueness {
66+
/// All errors in the set checked are unique according to the metadata files checked.
67+
Unique,
68+
/// One or more errors in the set occur in another metadata file.
69+
/// This variant contains the first duplicate error code followed by the name
70+
/// of the metadata file where the duplicate appears.
71+
Duplicate(String, String)
72+
}
73+
74+
/// Get the directory where metadata files should be stored.
75+
pub fn get_metadata_dir() -> PathBuf {
76+
match env::var(ERROR_METADATA_VAR) {
77+
Ok(v) => From::from(v),
78+
Err(_) => From::from(ERROR_METADATA_DIR_DEFAULT)
79+
}
80+
}
81+
82+
/// Get the path where error metadata for the set named by `name` should be stored.
83+
fn get_metadata_path(name: &str) -> PathBuf {
84+
get_metadata_dir().join(format!("{}.json", name))
85+
}
86+
87+
/// Check that the errors in `err_map` aren't present in any metadata files in the
88+
/// metadata directory except the metadata file corresponding to `name`.
89+
pub fn check_uniqueness(name: &str, err_map: &ErrorMap) -> Result<Uniqueness, Box<Error>> {
90+
let metadata_dir = get_metadata_dir();
91+
let metadata_path = get_metadata_path(name);
92+
93+
// Create the error directory if it does not exist.
94+
try!(create_dir_all(&metadata_dir));
95+
96+
// Check each file in the metadata directory.
97+
for entry in try!(read_dir(&metadata_dir)) {
98+
let path = try!(entry).path();
99+
100+
// Skip any existing file for this set.
101+
if path == metadata_path {
102+
continue;
103+
}
104+
105+
// Read the metadata file into a string.
106+
let mut metadata_str = String::new();
107+
try!(
108+
File::open(&path).and_then(|mut f|
109+
f.read_to_string(&mut metadata_str))
110+
);
111+
112+
// Parse the JSON contents.
113+
let metadata: ErrorMetadataMap = try!(json::decode(&metadata_str));
114+
115+
// Check for duplicates.
116+
for err in err_map.keys() {
117+
let err_code = err.as_str();
118+
if metadata.contains_key(err_code) {
119+
return Ok(Duplicate(
120+
err_code.to_string(),
121+
path.to_string_lossy().into_owned()
122+
));
123+
}
124+
}
125+
}
126+
127+
Ok(Unique)
128+
}
129+
130+
/// Write metadata for the errors in `err_map` to disk, to a file corresponding to `name`.
131+
pub fn output_metadata(ecx: &ExtCtxt, name: &str, err_map: &ErrorMap)
132+
-> Result<(), Box<Error>>
133+
{
134+
let metadata_path = get_metadata_path(name);
135+
136+
// Open the dump file.
137+
let mut dump_file = try!(OpenOptions::new()
138+
.write(true)
139+
.create(true)
140+
.open(&metadata_path)
141+
);
142+
143+
// Construct a serializable map.
144+
let json_map = err_map.iter().map(|(k, &ErrorInfo { description, use_site })| {
145+
let key = k.as_str().to_string();
146+
let value = ErrorMetadata {
147+
description: description.map(|n| n.as_str().to_string()),
148+
use_site: use_site.map(|sp| ErrorLocation::from_span(ecx, sp))
149+
};
150+
(key, value)
151+
}).collect::<ErrorMetadataMap>();
152+
153+
try!(write!(&mut dump_file, "{}", as_json(&json_map)));
154+
Ok(())
155+
}

src/libsyntax/diagnostics/plugin.rs

+62-34
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use std::collections::BTreeMap;
1414
use ast;
1515
use ast::{Ident, Name, TokenTree};
1616
use codemap::Span;
17+
use diagnostics::metadata::{check_uniqueness, output_metadata, Duplicate};
1718
use ext::base::{ExtCtxt, MacEager, MacResult};
1819
use ext::build::AstBuilder;
1920
use parse::token;
@@ -24,32 +25,28 @@ use util::small_vector::SmallVector;
2425
const MAX_DESCRIPTION_WIDTH: usize = 80;
2526

2627
thread_local! {
27-
static REGISTERED_DIAGNOSTICS: RefCell<BTreeMap<Name, Option<Name>>> = {
28+
static REGISTERED_DIAGNOSTICS: RefCell<ErrorMap> = {
2829
RefCell::new(BTreeMap::new())
2930
}
3031
}
31-
thread_local! {
32-
static USED_DIAGNOSTICS: RefCell<BTreeMap<Name, Span>> = {
33-
RefCell::new(BTreeMap::new())
34-
}
32+
33+
/// Error information type.
34+
pub struct ErrorInfo {
35+
pub description: Option<Name>,
36+
pub use_site: Option<Span>
3537
}
3638

39+
/// Mapping from error codes to metadata.
40+
pub type ErrorMap = BTreeMap<Name, ErrorInfo>;
41+
3742
fn with_registered_diagnostics<T, F>(f: F) -> T where
38-
F: FnOnce(&mut BTreeMap<Name, Option<Name>>) -> T,
43+
F: FnOnce(&mut ErrorMap) -> T,
3944
{
4045
REGISTERED_DIAGNOSTICS.with(move |slot| {
4146
f(&mut *slot.borrow_mut())
4247
})
4348
}
4449

45-
fn with_used_diagnostics<T, F>(f: F) -> T where
46-
F: FnOnce(&mut BTreeMap<Name, Span>) -> T,
47-
{
48-
USED_DIAGNOSTICS.with(move |slot| {
49-
f(&mut *slot.borrow_mut())
50-
})
51-
}
52-
5350
pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
5451
span: Span,
5552
token_tree: &[TokenTree])
@@ -58,23 +55,26 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
5855
(1, Some(&ast::TtToken(_, token::Ident(code, _)))) => code,
5956
_ => unreachable!()
6057
};
61-
with_used_diagnostics(|diagnostics| {
62-
match diagnostics.insert(code.name, span) {
63-
Some(previous_span) => {
58+
59+
with_registered_diagnostics(|diagnostics| {
60+
match diagnostics.get_mut(&code.name) {
61+
// Previously used errors.
62+
Some(&mut ErrorInfo { description: _, use_site: Some(previous_span) }) => {
6463
ecx.span_warn(span, &format!(
6564
"diagnostic code {} already used", &token::get_ident(code)
6665
));
6766
ecx.span_note(previous_span, "previous invocation");
68-
},
69-
None => ()
70-
}
71-
()
72-
});
73-
with_registered_diagnostics(|diagnostics| {
74-
if !diagnostics.contains_key(&code.name) {
75-
ecx.span_err(span, &format!(
76-
"used diagnostic code {} not registered", &token::get_ident(code)
77-
));
67+
}
68+
// Newly used errors.
69+
Some(ref mut info) => {
70+
info.use_site = Some(span);
71+
}
72+
// Unregistered errors.
73+
None => {
74+
ecx.span_err(span, &format!(
75+
"used diagnostic code {} not registered", &token::get_ident(code)
76+
));
77+
}
7878
}
7979
});
8080
MacEager::expr(ecx.expr_tuple(span, Vec::new()))
@@ -116,10 +116,14 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt,
116116
token::get_ident(*code), MAX_DESCRIPTION_WIDTH
117117
));
118118
}
119-
raw_msg
120119
});
120+
// Add the error to the map.
121121
with_registered_diagnostics(|diagnostics| {
122-
if diagnostics.insert(code.name, description).is_some() {
122+
let info = ErrorInfo {
123+
description: description,
124+
use_site: None
125+
};
126+
if diagnostics.insert(code.name, info).is_some() {
123127
ecx.span_err(span, &format!(
124128
"diagnostic code {} already registered", &token::get_ident(*code)
125129
));
@@ -143,19 +147,43 @@ pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt,
143147
span: Span,
144148
token_tree: &[TokenTree])
145149
-> Box<MacResult+'cx> {
146-
let name = match (token_tree.len(), token_tree.get(0)) {
147-
(1, Some(&ast::TtToken(_, token::Ident(ref name, _)))) => name,
150+
assert_eq!(token_tree.len(), 3);
151+
let (crate_name, name) = match (&token_tree[0], &token_tree[2]) {
152+
(
153+
// Crate name.
154+
&ast::TtToken(_, token::Ident(ref crate_name, _)),
155+
// DIAGNOSTICS ident.
156+
&ast::TtToken(_, token::Ident(ref name, _))
157+
) => (crate_name.as_str(), name),
148158
_ => unreachable!()
149159
};
150160

161+
// Check uniqueness of errors and output metadata.
162+
with_registered_diagnostics(|diagnostics| {
163+
match check_uniqueness(crate_name, &*diagnostics) {
164+
Ok(Duplicate(err, location)) => {
165+
ecx.span_err(span, &format!(
166+
"error {} from `{}' also found in `{}'",
167+
err, crate_name, location
168+
));
169+
},
170+
Ok(_) => (),
171+
Err(e) => panic!("{}", e.description())
172+
}
173+
174+
output_metadata(&*ecx, crate_name, &*diagnostics).ok().expect("metadata output error");
175+
});
176+
177+
// Construct the output expression.
151178
let (count, expr) =
152179
with_registered_diagnostics(|diagnostics| {
153180
let descriptions: Vec<P<ast::Expr>> =
154-
diagnostics.iter().filter_map(|(code, description)| {
155-
description.map(|description| {
181+
diagnostics.iter().filter_map(|(code, info)| {
182+
info.description.map(|description| {
156183
ecx.expr_tuple(span, vec![
157184
ecx.expr_str(span, token::get_name(*code)),
158-
ecx.expr_str(span, token::get_name(description))])
185+
ecx.expr_str(span, token::get_name(description))
186+
])
159187
})
160188
}).collect();
161189
(descriptions.len(), ecx.expr_vec(span, descriptions))

src/libsyntax/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ pub mod diagnostics {
7070
pub mod macros;
7171
pub mod plugin;
7272
pub mod registry;
73+
pub mod metadata;
7374
}
7475

7576
pub mod syntax {

0 commit comments

Comments
 (0)