Skip to content

Add support for arms in macros and quotes, fix a pretty printer bug, and other minor features #16037

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 30, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,10 @@ pub enum Pat_ {
/// records this pattern's NodeId in an auxiliary
/// set (of "PatIdents that refer to nullary enums")
PatIdent(BindingMode, SpannedIdent, Option<Gc<Pat>>),
PatEnum(Path, Option<Vec<Gc<Pat>>>), /* "none" means a * pattern where
* we don't bind the fields to names */

/// "None" means a * pattern where we don't bind the fields to names.
PatEnum(Path, Option<Vec<Gc<Pat>>>),

PatStruct(Path, Vec<FieldPat>, bool),
PatTup(Vec<Gc<Pat>>),
PatBox(Gc<Pat>),
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/ext/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,9 @@ fn initial_syntax_expander_table() -> SyntaxEnv {
syntax_expanders.insert(intern("quote_pat"),
builtin_normal_expander(
ext::quote::expand_quote_pat));
syntax_expanders.insert(intern("quote_arm"),
builtin_normal_expander(
ext::quote::expand_quote_arm));
syntax_expanders.insert(intern("quote_stmt"),
builtin_normal_expander(
ext::quote::expand_quote_stmt));
Expand Down
52 changes: 52 additions & 0 deletions src/libsyntax/ext/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,13 @@ pub trait AstBuilder {
subpats: Vec<Gc<ast::Pat>>) -> Gc<ast::Pat>;
fn pat_struct(&self, span: Span,
path: ast::Path, field_pats: Vec<ast::FieldPat> ) -> Gc<ast::Pat>;
fn pat_tuple(&self, span: Span, pats: Vec<Gc<ast::Pat>>) -> Gc<ast::Pat>;

fn pat_some(&self, span: Span, pat: Gc<ast::Pat>) -> Gc<ast::Pat>;
fn pat_none(&self, span: Span) -> Gc<ast::Pat>;

fn pat_ok(&self, span: Span, pat: Gc<ast::Pat>) -> Gc<ast::Pat>;
fn pat_err(&self, span: Span, pat: Gc<ast::Pat>) -> Gc<ast::Pat>;

fn arm(&self, span: Span, pats: Vec<Gc<ast::Pat>> , expr: Gc<ast::Expr>) -> ast::Arm;
fn arm_unreachable(&self, span: Span) -> ast::Arm;
Expand All @@ -178,6 +185,7 @@ pub trait AstBuilder {
fn expr_if(&self, span: Span,
cond: Gc<ast::Expr>, then: Gc<ast::Expr>,
els: Option<Gc<ast::Expr>>) -> Gc<ast::Expr>;
fn expr_loop(&self, span: Span, block: P<ast::Block>) -> Gc<ast::Expr>;

fn lambda_fn_decl(&self, span: Span,
fn_decl: P<ast::FnDecl>, blk: P<ast::Block>) -> Gc<ast::Expr>;
Expand Down Expand Up @@ -777,6 +785,46 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
let pat = ast::PatStruct(path, field_pats, false);
self.pat(span, pat)
}
fn pat_tuple(&self, span: Span, pats: Vec<Gc<ast::Pat>>) -> Gc<ast::Pat> {
let pat = ast::PatTup(pats);
self.pat(span, pat)
}

fn pat_some(&self, span: Span, pat: Gc<ast::Pat>) -> Gc<ast::Pat> {
let some = vec!(
self.ident_of("std"),
self.ident_of("option"),
self.ident_of("Some"));
let path = self.path_global(span, some);
self.pat_enum(span, path, vec!(pat))
}

fn pat_none(&self, span: Span) -> Gc<ast::Pat> {
let some = vec!(
self.ident_of("std"),
self.ident_of("option"),
self.ident_of("None"));
let path = self.path_global(span, some);
self.pat_enum(span, path, vec!())
}

fn pat_ok(&self, span: Span, pat: Gc<ast::Pat>) -> Gc<ast::Pat> {
let some = vec!(
self.ident_of("std"),
self.ident_of("result"),
self.ident_of("Ok"));
let path = self.path_global(span, some);
self.pat_enum(span, path, vec!(pat))
}

fn pat_err(&self, span: Span, pat: Gc<ast::Pat>) -> Gc<ast::Pat> {
let some = vec!(
self.ident_of("std"),
self.ident_of("result"),
self.ident_of("Err"));
let path = self.path_global(span, some);
self.pat_enum(span, path, vec!(pat))
}

fn arm(&self, _span: Span, pats: Vec<Gc<ast::Pat>> , expr: Gc<ast::Expr>) -> ast::Arm {
ast::Arm {
Expand All @@ -803,6 +851,10 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
self.expr(span, ast::ExprIf(cond, self.block_expr(then), els))
}

fn expr_loop(&self, span: Span, block: P<ast::Block>) -> Gc<ast::Expr> {
self.expr(span, ast::ExprLoop(block, None))
}

fn lambda_fn_decl(&self, span: Span,
fn_decl: P<ast::FnDecl>, blk: P<ast::Block>) -> Gc<ast::Expr> {
self.expr(span, ast::ExprFnBlock(fn_decl, blk))
Expand Down
12 changes: 12 additions & 0 deletions src/libsyntax/ext/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,10 @@ pub mod rt {
impl_to_source!(Generics, generics_to_string)
impl_to_source!(Gc<ast::Item>, item_to_string)
impl_to_source!(Gc<ast::Method>, method_to_string)
impl_to_source!(Gc<ast::Stmt>, stmt_to_string)
impl_to_source!(Gc<ast::Expr>, expr_to_string)
impl_to_source!(Gc<ast::Pat>, pat_to_string)
impl_to_source!(ast::Arm, arm_to_string)
impl_to_source_slice!(ast::Ty, ", ")
impl_to_source_slice!(Gc<ast::Item>, "\n\n")

Expand Down Expand Up @@ -239,11 +241,13 @@ pub mod rt {
impl_to_tokens!(ast::Ident)
impl_to_tokens!(Gc<ast::Item>)
impl_to_tokens!(Gc<ast::Pat>)
impl_to_tokens!(ast::Arm)
impl_to_tokens!(Gc<ast::Method>)
impl_to_tokens_lifetime!(&'a [Gc<ast::Item>])
impl_to_tokens!(ast::Ty)
impl_to_tokens_lifetime!(&'a [ast::Ty])
impl_to_tokens!(Generics)
impl_to_tokens!(Gc<ast::Stmt>)
impl_to_tokens!(Gc<ast::Expr>)
impl_to_tokens!(ast::Block)
impl_to_tokens!(ast::Arg)
Expand Down Expand Up @@ -345,6 +349,14 @@ pub fn expand_quote_pat(cx: &mut ExtCtxt,
base::MacExpr::new(expanded)
}

pub fn expand_quote_arm(cx: &mut ExtCtxt,
sp: Span,
tts: &[ast::TokenTree])
-> Box<base::MacResult> {
let expanded = expand_parse_call(cx, sp, "parse_arm", vec!(), tts);
base::MacExpr::new(expanded)
}

pub fn expand_quote_ty(cx: &mut ExtCtxt,
sp: Span,
tts: &[ast::TokenTree])
Expand Down
54 changes: 29 additions & 25 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2727,37 +2727,41 @@ impl<'a> Parser<'a> {
self.commit_expr_expecting(discriminant, token::LBRACE);
let mut arms: Vec<Arm> = Vec::new();
while self.token != token::RBRACE {
let attrs = self.parse_outer_attributes();
let pats = self.parse_pats();
let mut guard = None;
if self.eat_keyword(keywords::If) {
guard = Some(self.parse_expr());
}
self.expect(&token::FAT_ARROW);
let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);

let require_comma =
!classify::expr_is_simple_block(expr)
&& self.token != token::RBRACE;

if require_comma {
self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
} else {
self.eat(&token::COMMA);
}

arms.push(ast::Arm {
attrs: attrs,
pats: pats,
guard: guard,
body: expr
});
arms.push(self.parse_arm());
}
let hi = self.span.hi;
self.bump();
return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
}

pub fn parse_arm(&mut self) -> Arm {
let attrs = self.parse_outer_attributes();
let pats = self.parse_pats();
let mut guard = None;
if self.eat_keyword(keywords::If) {
guard = Some(self.parse_expr());
}
self.expect(&token::FAT_ARROW);
let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);

let require_comma =
!classify::expr_is_simple_block(expr)
&& self.token != token::RBRACE;

if require_comma {
self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
} else {
self.eat(&token::COMMA);
}

ast::Arm {
attrs: attrs,
pats: pats,
guard: guard,
body: expr,
}
}

/// Parse an expression
pub fn parse_expr(&mut self) -> Gc<Expr> {
return self.parse_expr_res(UNRESTRICTED);
Expand Down
99 changes: 51 additions & 48 deletions src/libsyntax/print/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use attr::{AttrMetaMethods, AttributeMethods};
use codemap::{CodeMap, BytePos};
use codemap;
use diagnostic;
use parse::classify::expr_is_simple_block;
use parse::token;
use parse::lexer::comments;
use parse;
Expand Down Expand Up @@ -151,6 +150,10 @@ pub fn pat_to_string(pat: &ast::Pat) -> String {
to_string(|s| s.print_pat(pat))
}

pub fn arm_to_string(arm: &ast::Arm) -> String {
to_string(|s| s.print_arm(arm))
}

pub fn expr_to_string(e: &ast::Expr) -> String {
to_string(|s| s.print_expr(e))
}
Expand Down Expand Up @@ -1402,53 +1405,8 @@ impl<'a> State<'a> {
try!(self.print_expr(&**expr));
try!(space(&mut self.s));
try!(self.bopen());
let len = arms.len();
for (i, arm) in arms.iter().enumerate() {
// I have no idea why this check is necessary, but here it
// is :(
if arm.attrs.is_empty() {
try!(space(&mut self.s));
}
try!(self.cbox(indent_unit));
try!(self.ibox(0u));
try!(self.print_outer_attributes(arm.attrs.as_slice()));
let mut first = true;
for p in arm.pats.iter() {
if first {
first = false;
} else {
try!(space(&mut self.s));
try!(self.word_space("|"));
}
try!(self.print_pat(&**p));
}
try!(space(&mut self.s));
match arm.guard {
Some(ref e) => {
try!(self.word_space("if"));
try!(self.print_expr(&**e));
try!(space(&mut self.s));
}
None => ()
}
try!(self.word_space("=>"));

match arm.body.node {
ast::ExprBlock(ref blk) => {
// the block will close the pattern's ibox
try!(self.print_block_unclosed_indent(&**blk,
indent_unit));
}
_ => {
try!(self.end()); // close the ibox for the pattern
try!(self.print_expr(&*arm.body));
}
}
if !expr_is_simple_block(expr.clone())
&& i < len - 1 {
try!(word(&mut self.s, ","));
}
try!(self.end()); // close enclosing cbox
for arm in arms.iter() {
try!(self.print_arm(arm));
}
try!(self.bclose_(expr.span, indent_unit));
}
Expand Down Expand Up @@ -1882,6 +1840,51 @@ impl<'a> State<'a> {
self.ann.post(self, NodePat(pat))
}

fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
// I have no idea why this check is necessary, but here it
// is :(
if arm.attrs.is_empty() {
try!(space(&mut self.s));
}
try!(self.cbox(indent_unit));
try!(self.ibox(0u));
try!(self.print_outer_attributes(arm.attrs.as_slice()));
let mut first = true;
for p in arm.pats.iter() {
if first {
first = false;
} else {
try!(space(&mut self.s));
try!(self.word_space("|"));
}
try!(self.print_pat(&**p));
}
try!(space(&mut self.s));
match arm.guard {
Some(ref e) => {
try!(self.word_space("if"));
try!(self.print_expr(&**e));
try!(space(&mut self.s));
}
None => ()
}
try!(self.word_space("=>"));

match arm.body.node {
ast::ExprBlock(ref blk) => {
// the block will close the pattern's ibox
try!(self.print_block_unclosed_indent(&**blk,
indent_unit));
}
_ => {
try!(self.end()); // close the ibox for the pattern
try!(self.print_expr(&*arm.body));
try!(word(&mut self.s, ","));
}
}
self.end() // close enclosing cbox
}

// Returns whether it printed anything
fn print_explicit_self(&mut self,
explicit_self: ast::ExplicitSelf_,
Expand Down
16 changes: 16 additions & 0 deletions src/test/pretty/match-block-expr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2012 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.

// pp-exact

fn main() {
let x = match { 5i } { 1 => 5i, 2 => 6, _ => 7, };
assert_eq!(x , 7);
}
2 changes: 1 addition & 1 deletion src/test/pretty/match-naked-expr-medium.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ fn main() {
"long".to_string(), "string".to_string()],
None =>
["none".to_string(), "a".to_string(), "a".to_string(),
"a".to_string(), "a".to_string()]
"a".to_string(), "a".to_string()],
};
}
2 changes: 1 addition & 1 deletion src/test/pretty/match-naked-expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ fn main() {
let _y =
match x {
Some(_) => "some(_)".to_string(),
None => "none".to_string()
None => "none".to_string(),
};
}
4 changes: 2 additions & 2 deletions src/test/run-make/graphviz-flowgraph/f07.dot-expected.dot
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ digraph block {
N4[label="expr 777i"];
N5[label="expr 7777i"];
N6[label="expr [7i, 77i, 777i, 7777i]"];
N7[label="expr match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y }"];
N7[label="expr match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y, }"];
N8[label="(dummy_node)"];
N9[label="local x"];
N10[label="local y"];
Expand All @@ -15,7 +15,7 @@ digraph block {
N13[label="expr x"];
N14[label="expr y"];
N15[label="expr x + y"];
N16[label="block { match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y }; }"];
N16[label="block { match [7i, 77i, 777i, 7777i] { [x, y, ..] => x + y, }; }"];
N0 -> N2;
N2 -> N3;
N3 -> N4;
Expand Down
Loading