1 // Copyright 2017 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.
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.
11 // ignore-cross-compile
14 // The general idea of this test is to enumerate all "interesting" expressions and check that
15 // `parse(print(e)) == e` for all `e`. Here's what's interesting, for the purposes of this test:
17 // 1. The test focuses on expression nesting, because interactions between different expression
18 // types are harder to test manually than single expression types in isolation.
20 // 2. The test only considers expressions of at most two nontrivial nodes. So it will check `x +
21 // x` and `x + (x - x)` but not `(x * x) + (x - x)`. The assumption here is that the correct
22 // handling of an expression might depend on the expression's parent, but doesn't depend on its
23 // siblings or any more distant ancestors.
25 // 3. The test only checks certain expression kinds. The assumption is that similar expression
26 // types, such as `if` and `while` or `+` and `-`, will be handled identically in the printer
27 // and parser. So if all combinations of exprs involving `if` work correctly, then combinations
28 // using `while`, `if let`, and so on will likely work as well.
31 #![feature(rustc_private)]
33 extern crate rustc_data_structures;
36 use rustc_data_structures::thin_vec::ThinVec;
38 use syntax::source_map::{Spanned, DUMMY_SP, FileName};
39 use syntax::source_map::FilePathMapping;
40 use syntax::fold::{self, Folder};
41 use syntax::parse::{self, ParseSess};
42 use syntax::print::pprust;
46 fn parse_expr(ps: &ParseSess, src: &str) -> P<Expr> {
47 let mut p = parse::new_parser_from_source_str(ps,
48 FileName::Custom("expr".to_owned()),
50 p.parse_expr().unwrap()
54 // Helper functions for building exprs
55 fn expr(kind: ExprKind) -> P<Expr> {
60 attrs: ThinVec::new(),
64 fn make_x() -> P<Expr> {
65 let seg = PathSegment::from_ident(Ident::from_str("x"));
66 let path = Path { segments: vec![seg], span: DUMMY_SP };
67 expr(ExprKind::Path(None, path))
70 /// Iterate over exprs of depth up to `depth`. The goal is to explore all "interesting"
71 /// combinations of expression nesting. For example, we explore combinations using `if`, but not
72 /// `while` or `match`, since those should print and parse in much the same way as `if`.
73 fn iter_exprs(depth: usize, f: &mut FnMut(P<Expr>)) {
79 let mut g = |e| f(expr(e));
83 0 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Box(e))),
84 1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, vec![]))),
86 let seg = PathSegment::from_ident(Ident::from_str("x"));
87 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
88 seg.clone(), vec![e, make_x()])));
89 iter_exprs(depth - 1, &mut |e| g(ExprKind::MethodCall(
90 seg.clone(), vec![make_x(), e])));
93 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Add };
94 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
95 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
98 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Mul };
99 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
100 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
103 let op = Spanned { span: DUMMY_SP, node: BinOpKind::Shl };
104 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, e, make_x())));
105 iter_exprs(depth - 1, &mut |e| g(ExprKind::Binary(op, make_x(), e)));
108 iter_exprs(depth - 1, &mut |e| g(ExprKind::Unary(UnOp::Deref, e)));
111 let block = P(Block {
114 rules: BlockCheckMode::Default,
118 iter_exprs(depth - 1, &mut |e| g(ExprKind::If(e, block.clone(), None)));
121 let decl = P(FnDecl {
123 output: FunctionRetTy::Default(DUMMY_SP),
126 iter_exprs(depth - 1, &mut |e| g(
127 ExprKind::Closure(CaptureBy::Value,
135 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(e, make_x())));
136 iter_exprs(depth - 1, &mut |e| g(ExprKind::Assign(make_x(), e)));
139 iter_exprs(depth - 1, &mut |e| g(ExprKind::Field(e, Ident::from_str("f"))));
142 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
143 Some(e), Some(make_x()), RangeLimits::HalfOpen)));
144 iter_exprs(depth - 1, &mut |e| g(ExprKind::Range(
145 Some(make_x()), Some(e), RangeLimits::HalfOpen)));
148 iter_exprs(depth - 1, &mut |e| g(ExprKind::AddrOf(Mutability::Immutable, e)));
151 g(ExprKind::Ret(None));
152 iter_exprs(depth - 1, &mut |e| g(ExprKind::Ret(Some(e))));
155 let path = Path::from_ident(Ident::from_str("S"));
156 g(ExprKind::Struct(path, vec![], Some(make_x())));
159 iter_exprs(depth - 1, &mut |e| g(ExprKind::Try(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 /// Folder that removes all `ExprKind::Paren` nodes.
172 impl Folder for RemoveParens {
173 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
174 let e = match e.node {
175 ExprKind::Paren(ref inner) => inner.clone(),
178 e.map(|e| fold::noop_fold_expr(e, self))
183 /// Folder that inserts `ExprKind::Paren` nodes around every `Expr`.
186 impl Folder for AddParens {
187 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
188 let e = e.map(|e| fold::noop_fold_expr(e, self));
191 node: ExprKind::Paren(e),
193 attrs: ThinVec::new(),
199 syntax::with_globals(|| run());
203 let ps = ParseSess::new(FilePathMapping::empty());
205 iter_exprs(2, &mut |e| {
206 // If the pretty printer is correct, then `parse(print(e))` should be identical to `e`,
207 // modulo placement of `Paren` nodes.
208 let printed = pprust::expr_to_string(&e);
209 println!("printed: {}", printed);
211 let parsed = parse_expr(&ps, &printed);
213 // We want to know if `parsed` is structurally identical to `e`, ignoring trivial
214 // differences like placement of `Paren`s or the exact ranges of node spans.
215 // Unfortunately, there is no easy way to make this comparison. Instead, we add `Paren`s
216 // everywhere we can, then pretty-print. This should give an unambiguous representation of
217 // each `Expr`, and it bypasses nearly all of the parenthesization logic, so we aren't
218 // relying on the correctness of the very thing we're testing.
219 let e1 = AddParens.fold_expr(RemoveParens.fold_expr(e));
220 let text1 = pprust::expr_to_string(&e1);
221 let e2 = AddParens.fold_expr(RemoveParens.fold_expr(parsed));
222 let text2 = pprust::expr_to_string(&e2);
223 assert!(text1 == text2,
224 "exprs are not equal:\n e = {:?}\n parsed = {:?}",