forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirty_clean.rs
635 lines (553 loc) · 20.5 KB
/
dirty_clean.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// Copyright 2014 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.
//! Debugging code to test fingerprints computed for query results.
//! For each node marked with `#[rustc_clean]` or `#[rustc_dirty]`,
//! we will compare the fingerprint from the current and from the previous
//! compilation session as appropriate:
//!
//! - `#[rustc_clean(cfg="rev2", except="TypeckTables")]` if we are
//! in `#[cfg(rev2)]`, then the fingerprints associated with
//! `DepNode::TypeckTables(X)` must be DIFFERENT (`X` is the def-id of the
//! current node).
//! - `#[rustc_clean(cfg="rev2")]` same as above, except that the
//! fingerprints must be the SAME (along with all other fingerprints).
//!
//! Errors are reported if we are in the suitable configuration but
//! the required condition is not met.
//!
use std::collections::HashSet;
use std::iter::FromIterator;
use std::vec::Vec;
use rustc::dep_graph::{DepNode, label_strs};
use rustc::hir;
use rustc::hir::{Item_ as HirItem, ImplItemKind, TraitItemKind};
use rustc::hir::map::Node as HirNode;
use rustc::hir::def_id::DefId;
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::hir::intravisit;
use rustc::ich::{ATTR_DIRTY, ATTR_CLEAN};
use syntax::ast::{self, Attribute, NestedMetaItem};
use rustc_data_structures::fx::FxHashSet;
use syntax_pos::Span;
use rustc::ty::TyCtxt;
const EXCEPT: &str = "except";
const LABEL: &str = "label";
const CFG: &str = "cfg";
// Base and Extra labels to build up the labels
/// For typedef, constants, and statics
const BASE_CONST: &[&str] = &[
label_strs::TypeOfItem,
];
/// DepNodes for functions + methods
const BASE_FN: &[&str] = &[
// Callers will depend on the signature of these items, so we better test
label_strs::FnSignature,
label_strs::GenericsOfItem,
label_strs::PredicatesOfItem,
label_strs::TypeOfItem,
// And a big part of compilation (that we eventually want to cache) is type inference
// information:
label_strs::TypeckTables,
];
/// DepNodes for Hir, which is pretty much everything
const BASE_HIR: &[&str] = &[
// Hir and HirBody should be computed for all nodes
label_strs::Hir,
label_strs::HirBody,
];
/// `impl` implementation of struct/trait
const BASE_IMPL: &[&str] = &[
label_strs::AssociatedItemDefIds,
label_strs::GenericsOfItem,
label_strs::ImplTraitRef,
];
/// DepNodes for MirValidated/Optimized, which is relevant in "executable"
/// code, i.e. functions+methods
const BASE_MIR: &[&str] = &[
label_strs::MirOptimized,
label_strs::MirValidated,
];
/// Struct, Enum and Union DepNodes
///
/// Note that changing the type of a field does not change the type of the struct or enum, but
/// adding/removing fields or changing a fields name or visibility does.
const BASE_STRUCT: &[&str] = &[
label_strs::GenericsOfItem,
label_strs::PredicatesOfItem,
label_strs::TypeOfItem,
];
/// Trait Definition DepNodes
const BASE_TRAIT_DEF: &[&str] = &[
label_strs::AssociatedItemDefIds,
label_strs::GenericsOfItem,
label_strs::ObjectSafety,
label_strs::PredicatesOfItem,
label_strs::SpecializationGraph,
label_strs::TraitDefOfItem,
label_strs::TraitImpls,
];
/// extra DepNodes for methods (+fn)
const EXTRA_ASSOCIATED: &[&str] = &[
label_strs::AssociatedItems,
];
const EXTRA_TRAIT: &[&str] = &[
label_strs::TraitOfItem,
];
// Fully Built Labels
const LABELS_CONST: &[&[&str]] = &[
BASE_HIR,
BASE_CONST,
];
/// Constant/Typedef in an impl
const LABELS_CONST_IN_IMPL: &[&[&str]] = &[
BASE_HIR,
BASE_CONST,
EXTRA_ASSOCIATED,
];
/// Trait-Const/Typedef DepNodes
const LABELS_CONST_IN_TRAIT: &[&[&str]] = &[
BASE_HIR,
BASE_CONST,
EXTRA_ASSOCIATED,
EXTRA_TRAIT,
];
/// Function DepNode
const LABELS_FN: &[&[&str]] = &[
BASE_HIR,
BASE_MIR,
BASE_FN,
];
/// Method DepNodes
const LABELS_FN_IN_IMPL: &[&[&str]] = &[
BASE_HIR,
BASE_MIR,
BASE_FN,
EXTRA_ASSOCIATED,
];
/// Trait-Method DepNodes
const LABELS_FN_IN_TRAIT: &[&[&str]] = &[
BASE_HIR,
BASE_MIR,
BASE_FN,
EXTRA_ASSOCIATED,
EXTRA_TRAIT,
];
/// For generic cases like inline-assemply/mod/etc
const LABELS_HIR_ONLY: &[&[&str]] = &[
BASE_HIR,
];
/// Impl DepNodes
const LABELS_IMPL: &[&[&str]] = &[
BASE_HIR,
BASE_IMPL,
];
/// Abstract Data Type (Struct, Enum, Unions) DepNodes
const LABELS_ADT: &[&[&str]] = &[
BASE_HIR,
BASE_STRUCT,
];
/// Trait Definition DepNodes
#[allow(dead_code)]
const LABELS_TRAIT: &[&[&str]] = &[
BASE_HIR,
BASE_TRAIT_DEF,
];
// FIXME: Struct/Enum/Unions Fields (there is currently no way to attach these)
//
// Fields are kind of separate from their containers, as they can change independently from
// them. We should at least check
//
// TypeOfItem for these.
type Labels = HashSet<String>;
/// Represents the requested configuration by rustc_clean/dirty
struct Assertion {
clean: Labels,
dirty: Labels,
}
impl Assertion {
fn from_clean_labels(labels: Labels) -> Assertion {
Assertion {
clean: labels,
dirty: Labels::new(),
}
}
fn from_dirty_labels(labels: Labels) -> Assertion {
Assertion {
clean: Labels::new(),
dirty: labels,
}
}
}
pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
// can't add `#[rustc_dirty]` etc without opting in to this feature
if !tcx.sess.features.borrow().rustc_attrs {
return;
}
let _ignore = tcx.dep_graph.in_ignore();
let krate = tcx.hir.krate();
let mut dirty_clean_visitor = DirtyCleanVisitor {
tcx,
checked_attrs: FxHashSet(),
};
krate.visit_all_item_likes(&mut dirty_clean_visitor);
let mut all_attrs = FindAllAttrs {
tcx,
attr_names: vec![ATTR_DIRTY, ATTR_CLEAN],
found_attrs: vec![],
};
intravisit::walk_crate(&mut all_attrs, krate);
// Note that we cannot use the existing "unused attribute"-infrastructure
// here, since that is running before trans. This is also the reason why
// all trans-specific attributes are `Whitelisted` in syntax::feature_gate.
all_attrs.report_unchecked_attrs(&dirty_clean_visitor.checked_attrs);
}
pub struct DirtyCleanVisitor<'a, 'tcx:'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
checked_attrs: FxHashSet<ast::AttrId>,
}
impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> {
/// Possibly "deserialize" the attribute into a clean/dirty assertion
fn assertion_maybe(&mut self, item_id: ast::NodeId, attr: &Attribute)
-> Option<Assertion>
{
let is_clean = if attr.check_name(ATTR_DIRTY) {
false
} else if attr.check_name(ATTR_CLEAN) {
true
} else {
// skip: not rustc_clean/dirty
return None
};
if !check_config(self.tcx, attr) {
// skip: not the correct `cfg=`
return None;
}
let assertion = if let Some(labels) = self.labels(attr) {
if is_clean {
Assertion::from_clean_labels(labels)
} else {
Assertion::from_dirty_labels(labels)
}
} else {
self.assertion_auto(item_id, attr, is_clean)
};
Some(assertion)
}
/// Get the "auto" assertion on pre-validated attr, along with the `except` labels
fn assertion_auto(&mut self, item_id: ast::NodeId, attr: &Attribute, is_clean: bool)
-> Assertion
{
let (name, mut auto) = self.auto_labels(item_id, attr);
let except = self.except(attr);
for e in except.iter() {
if !auto.remove(e) {
let msg = format!(
"`except` specified DepNodes that can not be affected for \"{}\": \"{}\"",
name,
e
);
self.tcx.sess.span_fatal(attr.span, &msg);
}
}
if is_clean {
Assertion {
clean: auto,
dirty: except,
}
} else {
Assertion {
clean: except,
dirty: auto,
}
}
}
fn labels(&self, attr: &Attribute) -> Option<Labels> {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(LABEL) {
let value = expect_associated_value(self.tcx, &item);
return Some(self.resolve_labels(&item, value.as_str().as_ref()));
}
}
None
}
/// `except=` attribute value
fn except(&self, attr: &Attribute) -> Labels {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(EXCEPT) {
let value = expect_associated_value(self.tcx, &item);
return self.resolve_labels(&item, value.as_str().as_ref());
}
}
// if no `label` or `except` is given, only the node's group are asserted
Labels::new()
}
/// Return all DepNode labels that should be asserted for this item.
/// index=0 is the "name" used for error messages
fn auto_labels(&mut self, item_id: ast::NodeId, attr: &Attribute) -> (&'static str, Labels) {
let node = self.tcx.hir.get(item_id);
let (name, labels) = match node {
HirNode::NodeItem(item) => {
match item.node {
// note: these are in the same order as hir::Item_;
// FIXME(michaelwoerister): do commented out ones
// // An `extern crate` item, with optional original crate name,
// HirItem::ItemExternCrate(..), // intentionally no assertions
// // `use foo::bar::*;` or `use foo::bar::baz as quux;`
// HirItem::ItemUse(..), // intentionally no assertions
// A `static` item
HirItem::ItemStatic(..) => ("ItemStatic", LABELS_CONST),
// A `const` item
HirItem::ItemConst(..) => ("ItemConst", LABELS_CONST),
// A function declaration
HirItem::ItemFn(..) => ("ItemFn", LABELS_FN),
// // A module
HirItem::ItemMod(..) =>("ItemMod", LABELS_HIR_ONLY),
// // An external module
HirItem::ItemForeignMod(..) => ("ItemForeignMod", LABELS_HIR_ONLY),
// Module-level inline assembly (from global_asm!)
HirItem::ItemGlobalAsm(..) => ("ItemGlobalAsm", LABELS_HIR_ONLY),
// A type alias, e.g. `type Foo = Bar<u8>`
HirItem::ItemTy(..) => ("ItemTy", LABELS_HIR_ONLY),
// An enum definition, e.g. `enum Foo<A, B> {C<A>, D<B>}`
HirItem::ItemEnum(..) => ("ItemEnum", LABELS_ADT),
// A struct definition, e.g. `struct Foo<A> {x: A}`
HirItem::ItemStruct(..) => ("ItemStruct", LABELS_ADT),
// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
HirItem::ItemUnion(..) => ("ItemUnion", LABELS_ADT),
// Represents a Trait Declaration
// FIXME(michaelwoerister): trait declaration is buggy because sometimes some of
// the depnodes don't exist (because they legitametely didn't need to be
// calculated)
//
// michaelwoerister and vitiral came up with a possible solution,
// to just do this before every query
// ```
// ::rustc::ty::maps::plumbing::force_from_dep_node(tcx, dep_node)
// ```
//
// However, this did not seem to work effectively and more bugs were hit.
// Nebie @vitiral gave up :)
//
//HirItem::ItemTrait(..) => ("ItemTrait", LABELS_TRAIT),
// An implementation, eg `impl<A> Trait for Foo { .. }`
HirItem::ItemImpl(..) => ("ItemImpl", LABELS_IMPL),
_ => self.tcx.sess.span_fatal(
attr.span,
&format!(
"clean/dirty auto-assertions not yet defined for NodeItem.node={:?}",
item.node
)
),
}
},
HirNode::NodeTraitItem(item) => {
match item.node {
TraitItemKind::Method(..) => ("NodeTraitItem", LABELS_FN_IN_TRAIT),
TraitItemKind::Const(..) => ("NodeTraitConst", LABELS_CONST_IN_TRAIT),
TraitItemKind::Type(..) => ("NodeTraitType", LABELS_CONST_IN_TRAIT),
}
},
HirNode::NodeImplItem(item) => {
match item.node {
ImplItemKind::Method(..) => ("NodeImplItem", LABELS_FN_IN_IMPL),
ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL),
ImplItemKind::Type(..) => ("NodeImplType", LABELS_CONST_IN_IMPL),
}
},
_ => self.tcx.sess.span_fatal(
attr.span,
&format!(
"clean/dirty auto-assertions not yet defined for {:?}",
node
)
),
};
let labels = Labels::from_iter(
labels.iter().flat_map(|s| s.iter().map(|l| l.to_string()))
);
(name, labels)
}
fn resolve_labels(&self, item: &NestedMetaItem, value: &str) -> Labels {
let mut out: Labels = HashSet::new();
for label in value.split(',') {
let label = label.trim();
if DepNode::has_label_string(label) {
if out.contains(label) {
self.tcx.sess.span_fatal(
item.span,
&format!("dep-node label `{}` is repeated", label));
}
out.insert(label.to_string());
} else {
self.tcx.sess.span_fatal(
item.span,
&format!("dep-node label `{}` not recognized", label));
}
}
out
}
fn dep_nodes(&self, labels: &Labels, def_id: DefId) -> Vec<DepNode> {
let mut out = Vec::with_capacity(labels.len());
let def_path_hash = self.tcx.def_path_hash(def_id);
for label in labels.iter() {
match DepNode::from_label_string(label, def_path_hash) {
Ok(dep_node) => out.push(dep_node),
Err(()) => unreachable!(),
}
}
out
}
fn dep_node_str(&self, dep_node: &DepNode) -> String {
if let Some(def_id) = dep_node.extract_def_id(self.tcx) {
format!("{:?}({})",
dep_node.kind,
self.tcx.item_path_str(def_id))
} else {
format!("{:?}({:?})", dep_node.kind, dep_node.hash)
}
}
fn assert_dirty(&self, item_span: Span, dep_node: DepNode) {
debug!("assert_dirty({:?})", dep_node);
let dep_node_index = self.tcx.dep_graph.dep_node_index_of(&dep_node);
let current_fingerprint = self.tcx.dep_graph.fingerprint_of(dep_node_index);
let prev_fingerprint = self.tcx.dep_graph.prev_fingerprint_of(&dep_node);
if Some(current_fingerprint) == prev_fingerprint {
let dep_node_str = self.dep_node_str(&dep_node);
self.tcx.sess.span_err(
item_span,
&format!("`{}` should be dirty but is not", dep_node_str));
}
}
fn assert_clean(&self, item_span: Span, dep_node: DepNode) {
debug!("assert_clean({:?})", dep_node);
let dep_node_index = self.tcx.dep_graph.dep_node_index_of(&dep_node);
let current_fingerprint = self.tcx.dep_graph.fingerprint_of(dep_node_index);
let prev_fingerprint = self.tcx.dep_graph.prev_fingerprint_of(&dep_node);
if Some(current_fingerprint) != prev_fingerprint {
let dep_node_str = self.dep_node_str(&dep_node);
self.tcx.sess.span_err(
item_span,
&format!("`{}` should be clean but is not", dep_node_str));
}
}
fn check_item(&mut self, item_id: ast::NodeId, item_span: Span) {
let def_id = self.tcx.hir.local_def_id(item_id);
for attr in self.tcx.get_attrs(def_id).iter() {
let assertion = match self.assertion_maybe(item_id, attr) {
Some(a) => a,
None => continue,
};
self.checked_attrs.insert(attr.id);
for dep_node in self.dep_nodes(&assertion.clean, def_id) {
self.assert_clean(item_span, dep_node);
}
for dep_node in self.dep_nodes(&assertion.dirty, def_id) {
self.assert_dirty(item_span, dep_node);
}
}
}
}
impl<'a, 'tcx> ItemLikeVisitor<'tcx> for DirtyCleanVisitor<'a, 'tcx> {
fn visit_item(&mut self, item: &'tcx hir::Item) {
self.check_item(item.id, item.span);
}
fn visit_trait_item(&mut self, item: &hir::TraitItem) {
self.check_item(item.id, item.span);
}
fn visit_impl_item(&mut self, item: &hir::ImplItem) {
self.check_item(item.id, item.span);
}
}
/// Given a `#[rustc_dirty]` or `#[rustc_clean]` attribute, scan
/// for a `cfg="foo"` attribute and check whether we have a cfg
/// flag called `foo`.
///
/// Also make sure that the `label` and `except` fields do not
/// both exist.
fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool {
debug!("check_config(attr={:?})", attr);
let config = &tcx.sess.parse_sess.config;
debug!("check_config: config={:?}", config);
let (mut cfg, mut except, mut label) = (None, false, false);
for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(CFG) {
let value = expect_associated_value(tcx, &item);
debug!("check_config: searching for cfg {:?}", value);
cfg = Some(config.contains(&(value, None)));
}
if item.check_name(LABEL) {
label = true;
}
if item.check_name(EXCEPT) {
except = true;
}
}
if label && except {
tcx.sess.span_fatal(
attr.span,
"must specify only one of: `label`, `except`"
);
}
match cfg {
None => tcx.sess.span_fatal(
attr.span,
"no cfg attribute"
),
Some(c) => c,
}
}
fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name {
if let Some(value) = item.value_str() {
value
} else {
let msg = if let Some(name) = item.name() {
format!("associated value expected for `{}`", name)
} else {
"expected an associated value".to_string()
};
tcx.sess.span_fatal(item.span, &msg);
}
}
// A visitor that collects all #[rustc_dirty]/#[rustc_clean] attributes from
// the HIR. It is used to verfiy that we really ran checks for all annotated
// nodes.
pub struct FindAllAttrs<'a, 'tcx:'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
attr_names: Vec<&'static str>,
found_attrs: Vec<&'tcx Attribute>,
}
impl<'a, 'tcx> FindAllAttrs<'a, 'tcx> {
fn is_active_attr(&mut self, attr: &Attribute) -> bool {
for attr_name in &self.attr_names {
if attr.check_name(attr_name) && check_config(self.tcx, attr) {
return true;
}
}
false
}
fn report_unchecked_attrs(&self, checked_attrs: &FxHashSet<ast::AttrId>) {
for attr in &self.found_attrs {
if !checked_attrs.contains(&attr.id) {
self.tcx.sess.span_err(attr.span, &format!("found unchecked \
#[rustc_dirty]/#[rustc_clean] attribute"));
}
}
}
}
impl<'a, 'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'a, 'tcx> {
fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
intravisit::NestedVisitorMap::All(&self.tcx.hir)
}
fn visit_attribute(&mut self, attr: &'tcx Attribute) {
if self.is_active_attr(attr) {
self.found_attrs.push(attr);
}
}
}