2 // ignore-cross-compile
4 // The general idea of this test is to enumerate all "interesting" expressions and check that
5 // `parse(print(e)) == e` for all `e`. Here's what's interesting, for the purposes of this test:
7 // 1. The test focuses on expression nesting, because interactions between different expression
8 // types are harder to test manually than single expression types in isolation.
10 // 2. The test only considers expressions of at most two nontrivial nodes. So it will check `x +
11 // x` and `x + (x - x)` but not `(x * x) + (x - x)`. The assumption here is that the correct
12 // handling of an expression might depend on the expression's parent, but doesn't depend on its
13 // siblings or any more distant ancestors.
15 // 3. The test only checks certain expression kinds. The assumption is that similar expression
16 // types, such as `if` and `while` or `+` and `-`, will be handled identically in the printer
17 // and parser. So if all combinations of exprs involving `if` work correctly, then combinations
18 // using `while`, `if let`, and so on will likely work as well.
20 #![feature(rustc_private)]
22 extern crate rustc_data_structures;
25 use rustc_data_structures::thin_vec::ThinVec;
27 use syntax::sess::ParseSess;
28 use syntax::source_map::{Spanned, DUMMY_SP, FileName};
29 use syntax::source_map::FilePathMapping;
30 use syntax::mut_visit::{self, MutVisitor, visit_clobber};
32 use syntax::print::pprust;
35 fn parse_expr(ps: &ParseSess, src: &str) -> Option<P<Expr>> {
36 let src_as_string = src.to_string();
38 let mut p = parse::new_parser_from_source_str(
40 FileName::Custom(src_as_string.clone()),
43 p.parse_expr().map_err(|mut e| e.cancel()).ok()
47 // Helper functions for building exprs
48 fn expr(kind: ExprKind) -> P<Expr> {
53 attrs: ThinVec::new(),
57 fn make_x() -> P<Expr> {
58 let seg = PathSegment::from_ident(Ident::from_str("x"));
59 let path = Path { segments: vec![seg], span: DUMMY_SP };
60 expr(ExprKind::Path(None, path))
63 /// Iterate over exprs of depth up to `depth`. The goal is to explore all "interesting"
64 /// combinations of expression nesting. For example, we explore combinations using `if`, but not
65 /// `while` or `match`, since those should print and parse in much the same way as `if`.
66 fn iter_exprs(depth: usize, f: &mut dyn FnMut(P<Expr>)) {
72 let mut g = |e| f(expr(e));
76 0 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Box(e))),
77 1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, vec![]))),
79 let seg = PathSegment::from_ident(Ident::from_str("x"));
80 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
81 seg.clone(), vec![e, make_x()])));
82 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
83 seg.clone(), vec![make_x(), e])));
98 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
99 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
102 iter_exprs(depth - 1, &mut |e| g(ExprKind::Unary(UnOp::Deref, e)));
105 let block = P(Block {
108 rules: BlockCheckMode::Default,
111 iter_exprs(depth - 1, &mut |e| g(ExprKind::If(e, block.clone(), None)));
114 let decl = P(FnDecl {
116 output: FunctionRetTy::Default(DUMMY_SP),
118 iter_exprs(depth - 1, &mut |e| g(
119 ExprKind::Closure(CaptureBy::Value,
127 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(e, make_x())));
128 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(make_x(), e)));
131 iter_exprs(depth - 1, &mut |e| g(ExprKind::Field(e, Ident::from_str("f"))));
134 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
135 Some(e), Some(make_x()), RangeLimits::HalfOpen)));
136 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
137 Some(make_x()), Some(e), RangeLimits::HalfOpen)));
140 iter_exprs(depth - 1, &mut |e| g(ExprKind::AddrOf(Mutability::Immutable, e)));
143 g(ExprKind::Ret(None));
144 iter_exprs(depth - 1, &mut |e| g(ExprKind::Ret(Some(e))));
147 let path = Path::from_ident(Ident::from_str("S"));
148 g(ExprKind::Struct(path, vec![], Some(make_x())));
151 iter_exprs(depth - 1, &mut |e| g(ExprKind::Try(e)));
159 iter_exprs(depth - 1, &mut |e| g(ExprKind::Let(pat.clone(), e)))
161 _ => panic!("bad counter value in iter_exprs"),
167 // Folders for manipulating the placement of `Paren` nodes. See below for why this is needed.
169 /// `MutVisitor` that removes all `ExprKind::Paren` nodes.
172 impl MutVisitor for RemoveParens {
173 fn visit_expr(&mut self, e: &mut P<Expr>) {
174 match e.kind.clone() {
175 ExprKind::Paren(inner) => *e = inner,
178 mut_visit::noop_visit_expr(e, self);
183 /// `MutVisitor` that inserts `ExprKind::Paren` nodes around every `Expr`.
186 impl MutVisitor for AddParens {
187 fn visit_expr(&mut self, e: &mut P<Expr>) {
188 mut_visit::noop_visit_expr(e, self);
189 visit_clobber(e, |e| {
192 kind: ExprKind::Paren(e),
194 attrs: ThinVec::new(),
201 syntax::with_default_globals(|| run());
205 let ps = ParseSess::new(FilePathMapping::empty());
207 iter_exprs(2, &mut |mut e| {
208 // If the pretty printer is correct, then `parse(print(e))` should be identical to `e`,
209 // modulo placement of `Paren` nodes.
210 let printed = pprust::expr_to_string(&e);
211 println!("printed: {}", printed);
213 // Ignore expressions with chained comparisons that fail to parse
214 if let Some(mut parsed) = parse_expr(&ps, &printed) {
215 // We want to know if `parsed` is structurally identical to `e`, ignoring trivial
216 // differences like placement of `Paren`s or the exact ranges of node spans.
217 // Unfortunately, there is no easy way to make this comparison. Instead, we add `Paren`s
218 // everywhere we can, then pretty-print. This should give an unambiguous representation
219 // of each `Expr`, and it bypasses nearly all of the parenthesization logic, so we
220 // aren't relying on the correctness of the very thing we're testing.
221 RemoveParens.visit_expr(&mut e);
222 AddParens.visit_expr(&mut e);
223 let text1 = pprust::expr_to_string(&e);
224 RemoveParens.visit_expr(&mut parsed);
225 AddParens.visit_expr(&mut parsed);
226 let text2 = pprust::expr_to_string(&parsed);
227 assert!(text1 == text2,
228 "exprs are not equal:\n e = {:?}\n parsed = {:?}",