Skip to content

Commit 096d72a

Browse files
committed
Add metadata output to the diagnostics system.
Diagnostic errors are now checked for uniqueness across the compiler and error metadata is written to JSON files.
1 parent 54d6509 commit 096d72a

File tree

12 files changed

+243
-45
lines changed

12 files changed

+243
-45
lines changed

src/librustc/diagnostics.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -517,5 +517,3 @@ register_diagnostics! {
517517
E0316, // nested quantification of lifetimes
518518
E0370 // discriminant overflow
519519
}
520-
521-
__build_diagnostic_array! { DIAGNOSTICS }

src/librustc/lib.rs

Lines changed: 6 additions & 0 deletions
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

Lines changed: 0 additions & 2 deletions
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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,8 @@ pub mod diagnostics;
4747
mod borrowck;
4848

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

src/librustc_driver/lib.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -854,9 +854,10 @@ pub fn diagnostics_registry() -> diagnostics::registry::Registry {
854854
use syntax::diagnostics::registry::Registry;
855855

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

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

src/librustc_resolve/diagnostics.rs

Lines changed: 0 additions & 2 deletions
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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3580,3 +3580,8 @@ pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
35803580
},
35813581
}
35823582
}
3583+
3584+
#[cfg(stage0)]
3585+
__build_diagnostic_array! { DIAGNOSTICS }
3586+
#[cfg(not(stage0))]
3587+
__build_diagnostic_array! { librustc_resolve, DIAGNOSTICS }

src/librustc_typeck/diagnostics.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,5 +183,3 @@ register_diagnostics! {
183183
E0371, // impl Trait for Trait is illegal
184184
E0372 // impl Trait for Trait where Trait is not object safe
185185
}
186-
187-
__build_diagnostic_array! { DIAGNOSTICS }

src/librustc_typeck/lib.rs

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

src/libsyntax/diagnostics/metadata.rs

Lines changed: 155 additions & 0 deletions
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

Lines changed: 62 additions & 34 deletions
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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ pub mod diagnostics {
6969
pub mod macros;
7070
pub mod plugin;
7171
pub mod registry;
72+
pub mod metadata;
7273
}
7374

7475
pub mod syntax {

0 commit comments

Comments
 (0)