1
Fork 0

Rollup merge of #41957 - llogiq:clippy-libsyntax, r=petrochenkov

Fix some clippy warnings in libsyntax

This is mostly removing stray ampersands, needless returns and lifetimes. Basically a lot of small changes.
This commit is contained in:
Mark Simulacrum 2017-05-16 17:31:50 -06:00 committed by GitHub
commit 4066c8ec71
32 changed files with 504 additions and 538 deletions

View file

@ -715,7 +715,7 @@ impl Stmt {
StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| { StmtKind::Mac(mac) => StmtKind::Mac(mac.map(|(mac, _style, attrs)| {
(mac, MacStmtStyle::Semicolon, attrs) (mac, MacStmtStyle::Semicolon, attrs)
})), })),
node @ _ => node, node => node,
}; };
self self
} }
@ -1076,16 +1076,16 @@ impl LitKind {
pub fn is_unsuffixed(&self) -> bool { pub fn is_unsuffixed(&self) -> bool {
match *self { match *self {
// unsuffixed variants // unsuffixed variants
LitKind::Str(..) => true, LitKind::Str(..) |
LitKind::ByteStr(..) => true, LitKind::ByteStr(..) |
LitKind::Byte(..) => true, LitKind::Byte(..) |
LitKind::Char(..) => true, LitKind::Char(..) |
LitKind::Int(_, LitIntType::Unsuffixed) => true, LitKind::Int(_, LitIntType::Unsuffixed) |
LitKind::FloatUnsuffixed(..) => true, LitKind::FloatUnsuffixed(..) |
LitKind::Bool(..) => true, LitKind::Bool(..) => true,
// suffixed variants // suffixed variants
LitKind::Int(_, LitIntType::Signed(..)) => false, LitKind::Int(_, LitIntType::Signed(..)) |
LitKind::Int(_, LitIntType::Unsigned(..)) => false, LitKind::Int(_, LitIntType::Unsigned(..)) |
LitKind::Float(..) => false, LitKind::Float(..) => false,
} }
} }

View file

@ -112,7 +112,7 @@ impl NestedMetaItem {
/// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem. /// Returns the MetaItem if self is a NestedMetaItemKind::MetaItem.
pub fn meta_item(&self) -> Option<&MetaItem> { pub fn meta_item(&self) -> Option<&MetaItem> {
match self.node { match self.node {
NestedMetaItemKind::MetaItem(ref item) => Some(&item), NestedMetaItemKind::MetaItem(ref item) => Some(item),
_ => None _ => None
} }
} }
@ -120,7 +120,7 @@ impl NestedMetaItem {
/// Returns the Lit if self is a NestedMetaItemKind::Literal. /// Returns the Lit if self is a NestedMetaItemKind::Literal.
pub fn literal(&self) -> Option<&Lit> { pub fn literal(&self) -> Option<&Lit> {
match self.node { match self.node {
NestedMetaItemKind::Literal(ref lit) => Some(&lit), NestedMetaItemKind::Literal(ref lit) => Some(lit),
_ => None _ => None
} }
} }
@ -259,7 +259,7 @@ impl MetaItem {
match self.node { match self.node {
MetaItemKind::NameValue(ref v) => { MetaItemKind::NameValue(ref v) => {
match v.node { match v.node {
LitKind::Str(ref s, _) => Some((*s).clone()), LitKind::Str(ref s, _) => Some(*s),
_ => None, _ => None,
} }
}, },
@ -1217,9 +1217,10 @@ impl LitKind {
Token::Literal(token::Lit::Float(symbol), Some(Symbol::intern(ty.ty_to_string()))) Token::Literal(token::Lit::Float(symbol), Some(Symbol::intern(ty.ty_to_string())))
} }
LitKind::FloatUnsuffixed(symbol) => Token::Literal(token::Lit::Float(symbol), None), LitKind::FloatUnsuffixed(symbol) => Token::Literal(token::Lit::Float(symbol), None),
LitKind::Bool(value) => Token::Ident(Ident::with_empty_ctxt(Symbol::intern(match value { LitKind::Bool(value) => Token::Ident(Ident::with_empty_ctxt(Symbol::intern(if value {
true => "true", "true"
false => "false", } else {
"false"
}))), }))),
} }
} }
@ -1261,7 +1262,7 @@ impl<T: HasAttrs> HasAttrs for Spanned<T> {
impl HasAttrs for Vec<Attribute> { impl HasAttrs for Vec<Attribute> {
fn attrs(&self) -> &[Attribute] { fn attrs(&self) -> &[Attribute] {
&self self
} }
fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
f(self) f(self)
@ -1270,7 +1271,7 @@ impl HasAttrs for Vec<Attribute> {
impl HasAttrs for ThinVec<Attribute> { impl HasAttrs for ThinVec<Attribute> {
fn attrs(&self) -> &[Attribute] { fn attrs(&self) -> &[Attribute] {
&self self
} }
fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self { fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
f(self.into()).into() f(self.into()).into()

View file

@ -485,7 +485,7 @@ impl CodeMap {
match self.span_to_snippet(sp) { match self.span_to_snippet(sp) {
Ok(snippet) => { Ok(snippet) => {
let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right(); let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
if snippet.len() > 0 && !snippet.contains('\n') { if !snippet.is_empty() && !snippet.contains('\n') {
Span { hi: BytePos(sp.lo.0 + snippet.len() as u32), ..sp } Span { hi: BytePos(sp.lo.0 + snippet.len() as u32), ..sp }
} else { } else {
sp sp
@ -502,7 +502,7 @@ impl CodeMap {
pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> { pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> {
for fm in self.files.borrow().iter() { for fm in self.files.borrow().iter() {
if filename == fm.name { if filename == fm.name {
(self.dep_tracking_callback.borrow())(&fm); (self.dep_tracking_callback.borrow())(fm);
return Some(fm.clone()); return Some(fm.clone());
} }
} }

View file

@ -123,7 +123,7 @@ impl<'a> StripUnconfigured<'a> {
return false; return false;
} }
let mis = if !is_cfg(&attr) { let mis = if !is_cfg(attr) {
return true; return true;
} else if let Some(mis) = attr.meta_item_list() { } else if let Some(mis) = attr.meta_item_list() {
mis mis
@ -150,7 +150,7 @@ impl<'a> StripUnconfigured<'a> {
// flag the offending attributes // flag the offending attributes
for attr in attrs.iter() { for attr in attrs.iter() {
if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) { if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
let mut err = feature_err(&self.sess, let mut err = feature_err(self.sess,
"stmt_expr_attributes", "stmt_expr_attributes",
attr.span, attr.span,
GateIssue::Language, GateIssue::Language,
@ -258,7 +258,7 @@ impl<'a> StripUnconfigured<'a> {
pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> { pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) { if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) {
if !field.attrs.is_empty() { if !field.attrs.is_empty() {
let mut err = feature_err(&self.sess, let mut err = feature_err(self.sess,
"struct_field_attributes", "struct_field_attributes",
field.span, field.span,
GateIssue::Language, GateIssue::Language,
@ -290,7 +290,7 @@ impl<'a> StripUnconfigured<'a> {
for attr in attrs.iter() { for attr in attrs.iter() {
if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) { if !self.features.map(|features| features.struct_field_attributes).unwrap_or(true) {
let mut err = feature_err( let mut err = feature_err(
&self.sess, self.sess,
"struct_field_attributes", "struct_field_attributes",
attr.span, attr.span,
GateIssue::Language, GateIssue::Language,

View file

@ -120,7 +120,7 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt,
// URLs can be unavoidably longer than the line limit, so we allow them. // URLs can be unavoidably longer than the line limit, so we allow them.
// Allowed format is: `[name]: https://www.rust-lang.org/` // Allowed format is: `[name]: https://www.rust-lang.org/`
let is_url = |l: &str| l.starts_with('[') && l.contains("]:") && l.contains("http"); let is_url = |l: &str| l.starts_with("[") && l.contains("]:") && l.contains("http");
if msg.lines().any(|line| line.len() > MAX_DESCRIPTION_WIDTH && !is_url(line)) { if msg.lines().any(|line| line.len() > MAX_DESCRIPTION_WIDTH && !is_url(line)) {
ecx.span_err(span, &format!( ecx.span_err(span, &format!(
@ -177,7 +177,7 @@ pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt,
if let Err(e) = output_metadata(ecx, if let Err(e) = output_metadata(ecx,
&target_triple, &target_triple,
&crate_name.name.as_str(), &crate_name.name.as_str(),
&diagnostics) { diagnostics) {
ecx.span_bug(span, &format!( ecx.span_bug(span, &format!(
"error writing metadata for triple `{}` and crate `{}`, error: {}, \ "error writing metadata for triple `{}` and crate `{}`, error: {}, \
cause: {:?}", cause: {:?}",
@ -227,7 +227,7 @@ pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt,
MacEager::items(SmallVector::many(vec![ MacEager::items(SmallVector::many(vec![
P(ast::Item { P(ast::Item {
ident: name.clone(), ident: *name,
attrs: Vec::new(), attrs: Vec::new(),
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Const( node: ast::ItemKind::Const(

View file

@ -635,8 +635,8 @@ pub struct ExpansionData {
} }
/// One of these is made during expansion and incrementally updated as we go; /// One of these is made during expansion and incrementally updated as we go;
/// when a macro expansion occurs, the resulting nodes have the backtrace() /// when a macro expansion occurs, the resulting nodes have the `backtrace()
/// -> expn_info of their expansion context stored into their span. /// -> expn_info` of their expansion context stored into their span.
pub struct ExtCtxt<'a> { pub struct ExtCtxt<'a> {
pub parse_sess: &'a parse::ParseSess, pub parse_sess: &'a parse::ParseSess,
pub ecfg: expand::ExpansionConfig<'a>, pub ecfg: expand::ExpansionConfig<'a>,
@ -709,7 +709,7 @@ impl<'a> ExtCtxt<'a> {
} }
ctxt = info.call_site.ctxt; ctxt = info.call_site.ctxt;
last_macro = Some(info.call_site); last_macro = Some(info.call_site);
return Some(()); Some(())
}).is_none() { }).is_none() {
break break
} }
@ -770,9 +770,9 @@ impl<'a> ExtCtxt<'a> {
} }
pub fn trace_macros_diag(&self) { pub fn trace_macros_diag(&self) {
for (sp, notes) in self.expansions.iter() { for (sp, notes) in self.expansions.iter() {
let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, &"trace_macro"); let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
for note in notes { for note in notes {
db.note(&note); db.note(note);
} }
db.emit(); db.emit();
} }
@ -795,7 +795,7 @@ impl<'a> ExtCtxt<'a> {
v.push(self.ident_of(s)); v.push(self.ident_of(s));
} }
v.extend(components.iter().map(|s| self.ident_of(s))); v.extend(components.iter().map(|s| self.ident_of(s)));
return v v
} }
pub fn name_of(&self, st: &str) -> ast::Name { pub fn name_of(&self, st: &str) -> ast::Name {
Symbol::intern(st) Symbol::intern(st)

View file

@ -415,19 +415,19 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
match *ext { match *ext {
MultiModifier(ref mac) => { MultiModifier(ref mac) => {
let meta = panictry!(attr.parse_meta(&self.cx.parse_sess)); let meta = panictry!(attr.parse_meta(self.cx.parse_sess));
let item = mac.expand(self.cx, attr.span, &meta, item); let item = mac.expand(self.cx, attr.span, &meta, item);
kind.expect_from_annotatables(item) kind.expect_from_annotatables(item)
} }
MultiDecorator(ref mac) => { MultiDecorator(ref mac) => {
let mut items = Vec::new(); let mut items = Vec::new();
let meta = panictry!(attr.parse_meta(&self.cx.parse_sess)); let meta = panictry!(attr.parse_meta(self.cx.parse_sess));
mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item)); mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
items.push(item); items.push(item);
kind.expect_from_annotatables(items) kind.expect_from_annotatables(items)
} }
SyntaxExtension::AttrProcMacro(ref mac) => { SyntaxExtension::AttrProcMacro(ref mac) => {
let item_toks = stream_for_item(&item, &self.cx.parse_sess); let item_toks = stream_for_item(&item, self.cx.parse_sess);
let span = Span { ctxt: self.cx.backtrace(), ..attr.span }; let span = Span { ctxt: self.cx.backtrace(), ..attr.span };
let tok_result = mac.expand(self.cx, attr.span, attr.tokens, item_toks); let tok_result = mac.expand(self.cx, attr.span, attr.tokens, item_toks);
@ -439,7 +439,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
} }
_ => { _ => {
let msg = &format!("macro `{}` may not be used in attributes", attr.path); let msg = &format!("macro `{}` may not be used in attributes", attr.path);
self.cx.span_err(attr.span, &msg); self.cx.span_err(attr.span, msg);
kind.dummy(attr.span) kind.dummy(attr.span)
} }
} }
@ -454,7 +454,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
}; };
let path = &mac.node.path; let path = &mac.node.path;
let ident = ident.unwrap_or(keywords::Invalid.ident()); let ident = ident.unwrap_or_else(|| keywords::Invalid.ident());
let marked_tts = noop_fold_tts(mac.node.stream(), &mut Marker(mark)); let marked_tts = noop_fold_tts(mac.node.stream(), &mut Marker(mark));
let opt_expanded = match *ext { let opt_expanded = match *ext {
NormalTT(ref expandfun, exp_span, allow_internal_unstable) => { NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
@ -591,7 +591,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
} }
_ => { _ => {
let msg = &format!("macro `{}` may not be used for derive attributes", attr.path); let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
self.cx.span_err(span, &msg); self.cx.span_err(span, msg);
kind.dummy(span) kind.dummy(span)
} }
} }
@ -749,19 +749,15 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
fn check_attributes(&mut self, attrs: &[ast::Attribute]) { fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
let features = self.cx.ecfg.features.unwrap(); let features = self.cx.ecfg.features.unwrap();
for attr in attrs.iter() { for attr in attrs.iter() {
feature_gate::check_attribute(&attr, &self.cx.parse_sess, features); feature_gate::check_attribute(attr, self.cx.parse_sess, features);
} }
} }
} }
pub fn find_attr_invoc(attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> { pub fn find_attr_invoc(attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> {
for i in 0 .. attrs.len() { attrs.iter()
if !attr::is_known(&attrs[i]) && !is_builtin_attr(&attrs[i]) { .position(|a| !attr::is_known(a) && !is_builtin_attr(a))
return Some(attrs.remove(i)); .map(|i| attrs.remove(i))
}
}
None
} }
// These are pretty nasty. Ideally, we would keep the tokens around, linked from // These are pretty nasty. Ideally, we would keep the tokens around, linked from
@ -923,7 +919,7 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
let result = noop_fold_item(item, self); let result = noop_fold_item(item, self);
self.cx.current_expansion.module = orig_module; self.cx.current_expansion.module = orig_module;
self.cx.current_expansion.directory_ownership = orig_directory_ownership; self.cx.current_expansion.directory_ownership = orig_directory_ownership;
return result; result
} }
// Ensure that test functions are accessible from the test harness. // Ensure that test functions are accessible from the test harness.
ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => { ast::ItemKind::Fn(..) if self.cx.ecfg.should_test => {

View file

@ -23,7 +23,7 @@ use tokenstream::{TokenStream, TokenTree};
/// ///
/// This is registered as a set of expression syntax extension called quote! /// This is registered as a set of expression syntax extension called quote!
/// that lifts its argument token-tree to an AST representing the /// that lifts its argument token-tree to an AST representing the
/// construction of the same token tree, with token::SubstNt interpreted /// construction of the same token tree, with `token::SubstNt` interpreted
/// as antiquotes (splices). /// as antiquotes (splices).
pub mod rt { pub mod rt {
@ -389,7 +389,7 @@ pub fn unflatten(tts: Vec<TokenTree>) -> Vec<TokenTree> {
result = results.pop().unwrap(); result = results.pop().unwrap();
result.push(tree); result.push(tree);
} }
tree @ _ => result.push(tree), tree => result.push(tree),
} }
} }
result result

View file

@ -150,7 +150,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenT
cx.span_err(sp, cx.span_err(sp,
&format!("{} wasn't a utf-8 file", &format!("{} wasn't a utf-8 file",
file.display())); file.display()));
return DummyResult::expr(sp); DummyResult::expr(sp)
} }
} }
} }
@ -167,7 +167,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::Toke
Err(e) => { Err(e) => {
cx.span_err(sp, cx.span_err(sp,
&format!("couldn't read {}: {}", file.display(), e)); &format!("couldn't read {}: {}", file.display(), e));
return DummyResult::expr(sp); DummyResult::expr(sp)
} }
Ok(..) => { Ok(..) => {
// Add this input file to the code map to make it available as // Add this input file to the code map to make it available as

View file

@ -36,43 +36,47 @@
//! repetitions indicated by Kleene stars. It only advances or calls out to the //! repetitions indicated by Kleene stars. It only advances or calls out to the
//! real Rust parser when no `cur_eis` items remain //! real Rust parser when no `cur_eis` items remain
//! //!
//! Example: Start parsing `a a a a b` against [· a $( a )* a b]. //! Example:
//! //!
//! Remaining input: `a a a a b` //! ```text, ignore
//! Start parsing a a a a b against [· a $( a )* a b].
//!
//! Remaining input: a a a a b
//! next_eis: [· a $( a )* a b] //! next_eis: [· a $( a )* a b]
//! //!
//! - - - Advance over an `a`. - - - //! - - - Advance over an a. - - -
//! //!
//! Remaining input: `a a a b` //! Remaining input: a a a b
//! cur: [a · $( a )* a b] //! cur: [a · $( a )* a b]
//! Descend/Skip (first item). //! Descend/Skip (first item).
//! next: [a $( · a )* a b] [a $( a )* · a b]. //! next: [a $( · a )* a b] [a $( a )* · a b].
//! //!
//! - - - Advance over an `a`. - - - //! - - - Advance over an a. - - -
//! //!
//! Remaining input: `a a b` //! Remaining input: a a b
//! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item) //! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//! //!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! - - - Advance over an a. - - - (this looks exactly like the last step)
//! //!
//! Remaining input: `a b` //! Remaining input: a b
//! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item) //! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
//! //!
//! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! - - - Advance over an a. - - - (this looks exactly like the last step)
//! //!
//! Remaining input: `b` //! Remaining input: b
//! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! cur: [a $( a · )* a b] next: [a $( a )* a · b]
//! Finish/Repeat (first item) //! Finish/Repeat (first item)
//! next: [a $( a )* · a b] [a $( · a )* a b] //! next: [a $( a )* · a b] [a $( · a )* a b]
//! //!
//! - - - Advance over a `b`. - - - //! - - - Advance over a b. - - -
//! //!
//! Remaining input: `` //! Remaining input: ''
//! eof: [a $( a )* a b ·] //! eof: [a $( a )* a b ·]
//! ```
pub use self::NamedMatch::*; pub use self::NamedMatch::*;
pub use self::ParseResult::*; pub use self::ParseResult::*;
@ -178,20 +182,20 @@ fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> {
}) })
} }
/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL: /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
/// so it is associated with a single ident in a parse, and all /// so it is associated with a single ident in a parse, and all
/// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type /// `MatchedNonterminal`s in the `NamedMatch` have the same nonterminal type
/// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
/// single token::MATCH_NONTERMINAL in the TokenTree that produced it. /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
/// ///
/// The in-memory structure of a particular NamedMatch represents the match /// The in-memory structure of a particular `NamedMatch` represents the match
/// that occurred when a particular subset of a matcher was applied to a /// that occurred when a particular subset of a matcher was applied to a
/// particular token tree. /// particular token tree.
/// ///
/// The width of each MatchedSeq in the NamedMatch, and the identity of the /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
/// `MatchedNonterminal`s, will depend on the token tree it was applied to: /// the `MatchedNonterminal`s, will depend on the token tree it was applied
/// each MatchedSeq corresponds to a single TTSeq in the originating /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
/// token tree. The depth of the NamedMatch structure will therefore depend /// token tree. The depth of the `NamedMatch` structure will therefore depend
/// only on the nesting depth of `ast::TTSeq`s in the originating /// only on the nesting depth of `ast::TTSeq`s in the originating
/// token tree it was derived from. /// token tree it was derived from.
@ -335,7 +339,7 @@ fn inner_parse_loop(sess: &ParseSess,
// Check if we need a separator // Check if we need a separator
if idx == len && ei.sep.is_some() { if idx == len && ei.sep.is_some() {
// We have a separator, and it is the current token. // We have a separator, and it is the current token.
if ei.sep.as_ref().map(|ref sep| token_name_eq(&token, sep)).unwrap_or(false) { if ei.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) {
ei.idx += 1; ei.idx += 1;
next_eis.push(ei); next_eis.push(ei);
} }
@ -402,7 +406,7 @@ fn inner_parse_loop(sess: &ParseSess,
cur_eis.push(ei); cur_eis.push(ei);
} }
TokenTree::Token(_, ref t) => { TokenTree::Token(_, ref t) => {
if token_name_eq(t, &token) { if token_name_eq(t, token) {
ei.idx += 1; ei.idx += 1;
next_eis.push(ei); next_eis.push(ei);
} }
@ -486,11 +490,8 @@ pub fn parse(sess: &ParseSess, tts: TokenStream, ms: &[TokenTree], directory: Op
} }
fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal { fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
match name { if name == "tt" {
"tt" => { return token::NtTT(p.parse_token_tree());
return token::NtTT(p.parse_token_tree());
}
_ => {}
} }
// check at the beginning and the parser checks after each bump // check at the beginning and the parser checks after each bump
p.process_potential_macro_variable(); p.process_potential_macro_variable();

View file

@ -94,7 +94,7 @@ fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
-> Box<MacResult+'cx> { -> Box<MacResult+'cx> {
if cx.trace_macros() { if cx.trace_macros() {
let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp); let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
let mut values: &mut Vec<String> = cx.expansions.entry(sp).or_insert(vec![]); let mut values: &mut Vec<String> = cx.expansions.entry(sp).or_insert_with(Vec::new);
values.push(format!("expands to `{}! {{ {} }}`", name, arg)); values.push(format!("expands to `{}! {{ {} }}`", name, arg));
} }
@ -206,7 +206,7 @@ pub fn compile(sess: &ParseSess, features: &RefCell<Features>, def: &ast::Item)
let mut valid = true; let mut valid = true;
// Extract the arguments: // Extract the arguments:
let lhses = match **argument_map.get(&lhs_nm).unwrap() { let lhses = match *argument_map[&lhs_nm] {
MatchedSeq(ref s, _) => { MatchedSeq(ref s, _) => {
s.iter().map(|m| { s.iter().map(|m| {
if let MatchedNonterminal(ref nt) = **m { if let MatchedNonterminal(ref nt) = **m {
@ -222,7 +222,7 @@ pub fn compile(sess: &ParseSess, features: &RefCell<Features>, def: &ast::Item)
_ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs") _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
}; };
let rhses = match **argument_map.get(&rhs_nm).unwrap() { let rhses = match *argument_map[&rhs_nm] {
MatchedSeq(ref s, _) => { MatchedSeq(ref s, _) => {
s.iter().map(|m| { s.iter().map(|m| {
if let MatchedNonterminal(ref nt) = **m { if let MatchedNonterminal(ref nt) = **m {
@ -260,13 +260,12 @@ fn check_lhs_nt_follows(sess: &ParseSess,
lhs: &quoted::TokenTree) -> bool { lhs: &quoted::TokenTree) -> bool {
// lhs is going to be like TokenTree::Delimited(...), where the // lhs is going to be like TokenTree::Delimited(...), where the
// entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens. // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
match lhs { if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
&quoted::TokenTree::Delimited(_, ref tts) => check_matcher(sess, features, &tts.tts), check_matcher(sess, features, &tts.tts)
_ => { } else {
let msg = "invalid macro matcher; matchers must be contained in balanced delimiters"; let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
sess.span_diagnostic.span_err(lhs.span(), msg); sess.span_diagnostic.span_err(lhs.span(), msg);
false false
}
} }
// we don't abort on errors on rejection, the driver will do that for us // we don't abort on errors on rejection, the driver will do that for us
// after parsing/expansion. we can report every error in every macro this way. // after parsing/expansion. we can report every error in every macro this way.
@ -283,17 +282,15 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
return false; return false;
}, },
TokenTree::Sequence(span, ref seq) => { TokenTree::Sequence(span, ref seq) => {
if seq.separator.is_none() { if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
if seq.tts.iter().all(|seq_tt| { match *seq_tt {
match *seq_tt { TokenTree::Sequence(_, ref sub_seq) =>
TokenTree::Sequence(_, ref sub_seq) => sub_seq.op == quoted::KleeneOp::ZeroOrMore,
sub_seq.op == quoted::KleeneOp::ZeroOrMore, _ => false,
_ => false,
}
}) {
sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
return false;
} }
}) {
sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
return false;
} }
if !check_lhs_no_empty_seq(sess, &seq.tts) { if !check_lhs_no_empty_seq(sess, &seq.tts) {
return false; return false;
@ -407,7 +404,7 @@ impl FirstSets {
} }
} }
return first; first
} }
} }
@ -469,7 +466,7 @@ impl FirstSets {
// we only exit the loop if `tts` was empty or if every // we only exit the loop if `tts` was empty or if every
// element of `tts` matches the empty sequence. // element of `tts` matches the empty sequence.
assert!(first.maybe_empty); assert!(first.maybe_empty);
return first; first
} }
} }
@ -579,7 +576,7 @@ fn check_matcher_core(sess: &ParseSess,
let build_suffix_first = || { let build_suffix_first = || {
let mut s = first_sets.first(suffix); let mut s = first_sets.first(suffix);
if s.maybe_empty { s.add_all(follow); } if s.maybe_empty { s.add_all(follow); }
return s; s
}; };
// (we build `suffix_first` on demand below; you can tell // (we build `suffix_first` on demand below; you can tell
@ -861,6 +858,7 @@ fn quoted_tt_to_string(tt: &quoted::TokenTree) -> String {
match *tt { match *tt {
quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok), quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind), quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
_ => panic!("unexpected quoted::TokenTree::{Sequence or Delimited} in follow set checker"), _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
in follow set checker"),
} }
} }

View file

@ -96,6 +96,17 @@ impl TokenTree {
} }
} }
pub fn is_empty(&self) -> bool {
match *self {
TokenTree::Delimited(_, ref delimed) => match delimed.delim {
token::NoDelim => delimed.tts.is_empty(),
_ => false,
},
TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
_ => true,
}
}
pub fn get_tt(&self, index: usize) -> TokenTree { pub fn get_tt(&self, index: usize) -> TokenTree {
match (self, index) { match (self, index) {
(&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => { (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
@ -144,9 +155,9 @@ pub fn parse(input: tokenstream::TokenStream, expect_matchers: bool, sess: &Pars
} }
_ => end_sp, _ => end_sp,
}, },
tree @ _ => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span), tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span),
}, },
tree @ _ => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(start_sp), tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(start_sp),
}; };
sess.missing_fragment_specifiers.borrow_mut().insert(span); sess.missing_fragment_specifiers.borrow_mut().insert(span);
result.push(TokenTree::MetaVarDecl(span, ident, keywords::Invalid.ident())); result.push(TokenTree::MetaVarDecl(span, ident, keywords::Invalid.ident()));
@ -228,10 +239,10 @@ fn parse_sep_and_kleene_op<I>(input: &mut I, span: Span, sess: &ParseSess)
Some(op) => return (Some(tok), op), Some(op) => return (Some(tok), op),
None => span, None => span,
}, },
tree @ _ => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span), tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span),
} }
}, },
tree @ _ => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span), tree => tree.as_ref().map(tokenstream::TokenTree::span).unwrap_or(span),
}; };
sess.span_diagnostic.span_err(span, "expected `*` or `+`"); sess.span_diagnostic.span_err(span, "expected `*` or `+`");

View file

@ -121,20 +121,20 @@ pub fn transcribe(sp_diag: &Handler,
&repeats) { &repeats) {
LockstepIterSize::Unconstrained => { LockstepIterSize::Unconstrained => {
panic!(sp_diag.span_fatal( panic!(sp_diag.span_fatal(
sp.clone(), /* blame macro writer */ sp, /* blame macro writer */
"attempted to repeat an expression \ "attempted to repeat an expression \
containing no syntax \ containing no syntax \
variables matched as repeating at this depth")); variables matched as repeating at this depth"));
} }
LockstepIterSize::Contradiction(ref msg) => { LockstepIterSize::Contradiction(ref msg) => {
// FIXME #2887 blame macro invoker instead // FIXME #2887 blame macro invoker instead
panic!(sp_diag.span_fatal(sp.clone(), &msg[..])); panic!(sp_diag.span_fatal(sp, &msg[..]));
} }
LockstepIterSize::Constraint(len, _) => { LockstepIterSize::Constraint(len, _) => {
if len == 0 { if len == 0 {
if seq.op == quoted::KleeneOp::OneOrMore { if seq.op == quoted::KleeneOp::OneOrMore {
// FIXME #2887 blame invoker // FIXME #2887 blame invoker
panic!(sp_diag.span_fatal(sp.clone(), panic!(sp_diag.span_fatal(sp,
"this must repeat at least once")); "this must repeat at least once"));
} }
} else { } else {

View file

@ -472,7 +472,7 @@ pub enum Stability {
impl ::std::fmt::Debug for AttributeGate { impl ::std::fmt::Debug for AttributeGate {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match *self { match *self {
Gated(ref stab, ref name, ref expl, _) => Gated(ref stab, name, expl, _) =>
write!(fmt, "Gated({:?}, {}, {})", stab, name, expl), write!(fmt, "Gated({:?}, {}, {})", stab, name, expl),
Ungated => write!(fmt, "Ungated") Ungated => write!(fmt, "Ungated")
} }
@ -816,7 +816,7 @@ pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeG
]; ];
// cfg(...)'s that are feature gated // cfg(...)'s that are feature gated
const GATED_CFGS: &'static [(&'static str, &'static str, fn(&Features) -> bool)] = &[ const GATED_CFGS: &[(&str, &str, fn(&Features) -> bool)] = &[
// (name in cfg, feature, function to check if the feature is enabled) // (name in cfg, feature, function to check if the feature is enabled)
("target_feature", "cfg_target_feature", cfg_fn!(cfg_target_feature)), ("target_feature", "cfg_target_feature", cfg_fn!(cfg_target_feature)),
("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)), ("target_vendor", "cfg_target_vendor", cfg_fn!(cfg_target_vendor)),
@ -881,7 +881,7 @@ impl<'a> Context<'a> {
let name = unwrap_or!(attr.name(), return).as_str(); let name = unwrap_or!(attr.name(), return).as_str();
for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES { for &(n, ty, ref gateage) in BUILTIN_ATTRIBUTES {
if name == n { if name == n {
if let &Gated(_, ref name, ref desc, ref has_feature) = gateage { if let Gated(_, name, desc, ref has_feature) = *gateage {
gate_feature_fn!(self, has_feature, attr.span, name, desc); gate_feature_fn!(self, has_feature, attr.span, name, desc);
} }
debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage); debug!("check_attribute: {:?} is builtin, {:?}, {:?}", attr.path, ty, gateage);
@ -1098,7 +1098,7 @@ fn contains_novel_literal(item: &ast::MetaItem) -> bool {
NameValue(ref lit) => !lit.node.is_str(), NameValue(ref lit) => !lit.node.is_str(),
List(ref list) => list.iter().any(|li| { List(ref list) => list.iter().any(|li| {
match li.node { match li.node {
MetaItem(ref mi) => contains_novel_literal(&mi), MetaItem(ref mi) => contains_novel_literal(mi),
Literal(_) => true, Literal(_) => true,
} }
}), }),
@ -1120,7 +1120,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
return return
} }
let meta = panictry!(attr.parse_meta(&self.context.parse_sess)); let meta = panictry!(attr.parse_meta(self.context.parse_sess));
if contains_novel_literal(&meta) { if contains_novel_literal(&meta) {
gate_feature_post!(&self, attr_literals, attr.span, gate_feature_post!(&self, attr_literals, attr.span,
"non-string literals in attributes, or string \ "non-string literals in attributes, or string \
@ -1216,14 +1216,11 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
} }
ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => { ast::ItemKind::Impl(_, polarity, defaultness, _, _, _, _) => {
match polarity { if polarity == ast::ImplPolarity::Negative {
ast::ImplPolarity::Negative => { gate_feature_post!(&self, optin_builtin_traits,
gate_feature_post!(&self, optin_builtin_traits, i.span,
i.span, "negative trait bounds are not yet fully implemented; \
"negative trait bounds are not yet fully implemented; \ use marker types for now");
use marker types for now");
},
_ => {}
} }
if let ast::Defaultness::Default = defaultness { if let ast::Defaultness::Default = defaultness {
@ -1272,11 +1269,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) { fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FunctionRetTy) {
if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty { if let ast::FunctionRetTy::Ty(ref output_ty) = *ret_ty {
match output_ty.node { if output_ty.node != ast::TyKind::Never {
ast::TyKind::Never => return, self.visit_ty(output_ty)
_ => (), }
};
self.visit_ty(output_ty)
} }
} }
@ -1373,17 +1368,14 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
span: Span, span: Span,
_node_id: NodeId) { _node_id: NodeId) {
// check for const fn declarations // check for const fn declarations
match fn_kind { if let FnKind::ItemFn(_, _, _, Spanned { node: ast::Constness::Const, .. }, _, _, _) =
FnKind::ItemFn(_, _, _, Spanned { node: ast::Constness::Const, .. }, _, _, _) => { fn_kind {
gate_feature_post!(&self, const_fn, span, "const fn is unstable"); gate_feature_post!(&self, const_fn, span, "const fn is unstable");
}
_ => {
// stability of const fn methods are covered in
// visit_trait_item and visit_impl_item below; this is
// because default methods don't pass through this
// point.
}
} }
// stability of const fn methods are covered in
// visit_trait_item and visit_impl_item below; this is
// because default methods don't pass through this
// point.
match fn_kind { match fn_kind {
FnKind::ItemFn(_, _, _, _, abi, _, _) | FnKind::ItemFn(_, _, _, _, abi, _, _) |

View file

@ -337,7 +337,7 @@ impl DiagnosticSpanLine {
}) })
.collect() .collect()
}) })
.unwrap_or(vec![]) .unwrap_or_else(|_| vec![])
} }
} }

View file

@ -62,7 +62,7 @@ impl<'a> Parser<'a> {
_ => break, _ => break,
} }
} }
return Ok(attrs); Ok(attrs)
} }
/// Matches `attribute = # ! [ meta_item ]` /// Matches `attribute = # ! [ meta_item ]`
@ -182,7 +182,7 @@ impl<'a> Parser<'a> {
} }
let attr = self.parse_attribute(true)?; let attr = self.parse_attribute(true)?;
assert!(attr.style == ast::AttrStyle::Inner); assert_eq!(attr.style, ast::AttrStyle::Inner);
attrs.push(attr); attrs.push(attr);
} }
token::DocComment(s) => { token::DocComment(s) => {

View file

@ -43,14 +43,14 @@ pub fn expr_is_simple_block(e: &ast::Expr) -> bool {
} }
/// this statement requires a semicolon after it. /// this statement requires a semicolon after it.
/// note that in one case (stmt_semi), we've already /// note that in one case (`stmt_semi`), we've already
/// seen the semicolon, and thus don't need another. /// seen the semicolon, and thus don't need another.
pub fn stmt_ends_with_semi(stmt: &ast::StmtKind) -> bool { pub fn stmt_ends_with_semi(stmt: &ast::StmtKind) -> bool {
match *stmt { match *stmt {
ast::StmtKind::Local(_) => true, ast::StmtKind::Local(_) => true,
ast::StmtKind::Item(_) => false,
ast::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(e), ast::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(e),
ast::StmtKind::Semi(..) => false, ast::StmtKind::Item(_) |
ast::StmtKind::Semi(..) |
ast::StmtKind::Mac(..) => false, ast::StmtKind::Mac(..) => false,
} }
} }

View file

@ -12,7 +12,7 @@
use parse::token; use parse::token;
/// SeqSep : a sequence separator (token) /// `SeqSep` : a sequence separator (token)
/// and whether a trailing separator is allowed. /// and whether a trailing separator is allowed.
pub struct SeqSep { pub struct SeqSep {
pub sep: Option<token::Token>, pub sep: Option<token::Token>,

View file

@ -77,7 +77,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String {
while j > i && lines[j - 1].trim().is_empty() { while j > i && lines[j - 1].trim().is_empty() {
j -= 1; j -= 1;
} }
lines[i..j].iter().cloned().collect() lines[i..j].to_vec()
} }
/// remove a "[ \t]*\*" block from each line, if possible /// remove a "[ \t]*\*" block from each line, if possible

View file

@ -144,7 +144,7 @@ impl<'a> StringReader<'a> {
impl<'a> StringReader<'a> { impl<'a> StringReader<'a> {
/// For comments.rs, which hackily pokes into next_pos and ch /// For comments.rs, which hackily pokes into next_pos and ch
pub fn new_raw<'b>(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self { pub fn new_raw(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
let mut sr = StringReader::new_raw_internal(sess, filemap); let mut sr = StringReader::new_raw_internal(sess, filemap);
sr.bump(); sr.bump();
sr sr
@ -180,7 +180,7 @@ impl<'a> StringReader<'a> {
pub fn new(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self { pub fn new(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self {
let mut sr = StringReader::new_raw(sess, filemap); let mut sr = StringReader::new_raw(sess, filemap);
if let Err(_) = sr.advance_token() { if sr.advance_token().is_err() {
sr.emit_fatal_errors(); sr.emit_fatal_errors();
panic!(FatalError); panic!(FatalError);
} }
@ -205,7 +205,7 @@ impl<'a> StringReader<'a> {
sr.bump(); sr.bump();
if let Err(_) = sr.advance_token() { if sr.advance_token().is_err() {
sr.emit_fatal_errors(); sr.emit_fatal_errors();
panic!(FatalError); panic!(FatalError);
} }
@ -525,7 +525,7 @@ impl<'a> StringReader<'a> {
self.bump(); self.bump();
} }
return if doc_comment { if doc_comment {
self.with_str_from(start_bpos, |string| { self.with_str_from(start_bpos, |string| {
// comments with only more "/"s are not doc comments // comments with only more "/"s are not doc comments
let tok = if is_doc_comment(string) { let tok = if is_doc_comment(string) {
@ -544,7 +544,7 @@ impl<'a> StringReader<'a> {
tok: token::Comment, tok: token::Comment,
sp: mk_sp(start_bpos, self.pos), sp: mk_sp(start_bpos, self.pos),
}) })
}; }
} }
Some('*') => { Some('*') => {
self.bump(); self.bump();
@ -764,7 +764,7 @@ impl<'a> StringReader<'a> {
} }
let pos = self.pos; let pos = self.pos;
self.check_float_base(start_bpos, pos, base); self.check_float_base(start_bpos, pos, base);
return token::Float(self.name_from(start_bpos)); token::Float(self.name_from(start_bpos))
} else { } else {
// it might be a float if it has an exponent // it might be a float if it has an exponent
if self.ch_is('e') || self.ch_is('E') { if self.ch_is('e') || self.ch_is('E') {
@ -774,7 +774,7 @@ impl<'a> StringReader<'a> {
return token::Float(self.name_from(start_bpos)); return token::Float(self.name_from(start_bpos));
} }
// but we certainly have an integer! // but we certainly have an integer!
return token::Integer(self.name_from(start_bpos)); token::Integer(self.name_from(start_bpos))
} }
} }
@ -1051,9 +1051,9 @@ impl<'a> StringReader<'a> {
self.bump(); self.bump();
if self.ch_is('=') { if self.ch_is('=') {
self.bump(); self.bump();
return token::BinOpEq(op); token::BinOpEq(op)
} else { } else {
return token::BinOp(op); token::BinOp(op)
} }
} }
@ -1100,15 +1100,15 @@ impl<'a> StringReader<'a> {
// One-byte tokens. // One-byte tokens.
';' => { ';' => {
self.bump(); self.bump();
return Ok(token::Semi); Ok(token::Semi)
} }
',' => { ',' => {
self.bump(); self.bump();
return Ok(token::Comma); Ok(token::Comma)
} }
'.' => { '.' => {
self.bump(); self.bump();
return if self.ch_is('.') { if self.ch_is('.') {
self.bump(); self.bump();
if self.ch_is('.') { if self.ch_is('.') {
self.bump(); self.bump();
@ -1118,61 +1118,61 @@ impl<'a> StringReader<'a> {
} }
} else { } else {
Ok(token::Dot) Ok(token::Dot)
}; }
} }
'(' => { '(' => {
self.bump(); self.bump();
return Ok(token::OpenDelim(token::Paren)); Ok(token::OpenDelim(token::Paren))
} }
')' => { ')' => {
self.bump(); self.bump();
return Ok(token::CloseDelim(token::Paren)); Ok(token::CloseDelim(token::Paren))
} }
'{' => { '{' => {
self.bump(); self.bump();
return Ok(token::OpenDelim(token::Brace)); Ok(token::OpenDelim(token::Brace))
} }
'}' => { '}' => {
self.bump(); self.bump();
return Ok(token::CloseDelim(token::Brace)); Ok(token::CloseDelim(token::Brace))
} }
'[' => { '[' => {
self.bump(); self.bump();
return Ok(token::OpenDelim(token::Bracket)); Ok(token::OpenDelim(token::Bracket))
} }
']' => { ']' => {
self.bump(); self.bump();
return Ok(token::CloseDelim(token::Bracket)); Ok(token::CloseDelim(token::Bracket))
} }
'@' => { '@' => {
self.bump(); self.bump();
return Ok(token::At); Ok(token::At)
} }
'#' => { '#' => {
self.bump(); self.bump();
return Ok(token::Pound); Ok(token::Pound)
} }
'~' => { '~' => {
self.bump(); self.bump();
return Ok(token::Tilde); Ok(token::Tilde)
} }
'?' => { '?' => {
self.bump(); self.bump();
return Ok(token::Question); Ok(token::Question)
} }
':' => { ':' => {
self.bump(); self.bump();
if self.ch_is(':') { if self.ch_is(':') {
self.bump(); self.bump();
return Ok(token::ModSep); Ok(token::ModSep)
} else { } else {
return Ok(token::Colon); Ok(token::Colon)
} }
} }
'$' => { '$' => {
self.bump(); self.bump();
return Ok(token::Dollar); Ok(token::Dollar)
} }
// Multi-byte tokens. // Multi-byte tokens.
@ -1180,21 +1180,21 @@ impl<'a> StringReader<'a> {
self.bump(); self.bump();
if self.ch_is('=') { if self.ch_is('=') {
self.bump(); self.bump();
return Ok(token::EqEq); Ok(token::EqEq)
} else if self.ch_is('>') { } else if self.ch_is('>') {
self.bump(); self.bump();
return Ok(token::FatArrow); Ok(token::FatArrow)
} else { } else {
return Ok(token::Eq); Ok(token::Eq)
} }
} }
'!' => { '!' => {
self.bump(); self.bump();
if self.ch_is('=') { if self.ch_is('=') {
self.bump(); self.bump();
return Ok(token::Ne); Ok(token::Ne)
} else { } else {
return Ok(token::Not); Ok(token::Not)
} }
} }
'<' => { '<' => {
@ -1202,21 +1202,21 @@ impl<'a> StringReader<'a> {
match self.ch.unwrap_or('\x00') { match self.ch.unwrap_or('\x00') {
'=' => { '=' => {
self.bump(); self.bump();
return Ok(token::Le); Ok(token::Le)
} }
'<' => { '<' => {
return Ok(self.binop(token::Shl)); Ok(self.binop(token::Shl))
} }
'-' => { '-' => {
self.bump(); self.bump();
match self.ch.unwrap_or('\x00') { match self.ch.unwrap_or('\x00') {
_ => { _ => {
return Ok(token::LArrow); Ok(token::LArrow)
} }
} }
} }
_ => { _ => {
return Ok(token::Lt); Ok(token::Lt)
} }
} }
} }
@ -1225,13 +1225,13 @@ impl<'a> StringReader<'a> {
match self.ch.unwrap_or('\x00') { match self.ch.unwrap_or('\x00') {
'=' => { '=' => {
self.bump(); self.bump();
return Ok(token::Ge); Ok(token::Ge)
} }
'>' => { '>' => {
return Ok(self.binop(token::Shr)); Ok(self.binop(token::Shr))
} }
_ => { _ => {
return Ok(token::Gt); Ok(token::Gt)
} }
} }
} }
@ -1301,7 +1301,7 @@ impl<'a> StringReader<'a> {
}; };
self.bump(); // advance ch past token self.bump(); // advance ch past token
let suffix = self.scan_optional_raw_name(); let suffix = self.scan_optional_raw_name();
return Ok(token::Literal(token::Char(id), suffix)); Ok(token::Literal(token::Char(id), suffix))
} }
'b' => { 'b' => {
self.bump(); self.bump();
@ -1312,7 +1312,7 @@ impl<'a> StringReader<'a> {
_ => unreachable!(), // Should have been a token::Ident above. _ => unreachable!(), // Should have been a token::Ident above.
}; };
let suffix = self.scan_optional_raw_name(); let suffix = self.scan_optional_raw_name();
return Ok(token::Literal(lit, suffix)); Ok(token::Literal(lit, suffix))
} }
'"' => { '"' => {
let start_bpos = self.pos; let start_bpos = self.pos;
@ -1343,7 +1343,7 @@ impl<'a> StringReader<'a> {
}; };
self.bump(); self.bump();
let suffix = self.scan_optional_raw_name(); let suffix = self.scan_optional_raw_name();
return Ok(token::Literal(token::Str_(id), suffix)); Ok(token::Literal(token::Str_(id), suffix))
} }
'r' => { 'r' => {
let start_bpos = self.pos; let start_bpos = self.pos;
@ -1414,24 +1414,24 @@ impl<'a> StringReader<'a> {
Symbol::intern("??") Symbol::intern("??")
}; };
let suffix = self.scan_optional_raw_name(); let suffix = self.scan_optional_raw_name();
return Ok(token::Literal(token::StrRaw(id, hash_count), suffix)); Ok(token::Literal(token::StrRaw(id, hash_count), suffix))
} }
'-' => { '-' => {
if self.nextch_is('>') { if self.nextch_is('>') {
self.bump(); self.bump();
self.bump(); self.bump();
return Ok(token::RArrow); Ok(token::RArrow)
} else { } else {
return Ok(self.binop(token::Minus)); Ok(self.binop(token::Minus))
} }
} }
'&' => { '&' => {
if self.nextch_is('&') { if self.nextch_is('&') {
self.bump(); self.bump();
self.bump(); self.bump();
return Ok(token::AndAnd); Ok(token::AndAnd)
} else { } else {
return Ok(self.binop(token::And)); Ok(self.binop(token::And))
} }
} }
'|' => { '|' => {
@ -1439,27 +1439,27 @@ impl<'a> StringReader<'a> {
Some('|') => { Some('|') => {
self.bump(); self.bump();
self.bump(); self.bump();
return Ok(token::OrOr); Ok(token::OrOr)
} }
_ => { _ => {
return Ok(self.binop(token::Or)); Ok(self.binop(token::Or))
} }
} }
} }
'+' => { '+' => {
return Ok(self.binop(token::Plus)); Ok(self.binop(token::Plus))
} }
'*' => { '*' => {
return Ok(self.binop(token::Star)); Ok(self.binop(token::Star))
} }
'/' => { '/' => {
return Ok(self.binop(token::Slash)); Ok(self.binop(token::Slash))
} }
'^' => { '^' => {
return Ok(self.binop(token::Caret)); Ok(self.binop(token::Caret))
} }
'%' => { '%' => {
return Ok(self.binop(token::Percent)); Ok(self.binop(token::Percent))
} }
c => { c => {
let last_bpos = self.pos; let last_bpos = self.pos;
@ -1468,7 +1468,7 @@ impl<'a> StringReader<'a> {
bpos, bpos,
"unknown start of token", "unknown start of token",
c); c);
unicode_chars::check_for_substitution(&self, c, &mut err); unicode_chars::check_for_substitution(self, c, &mut err);
self.fatal_errs.push(err); self.fatal_errs.push(err);
Err(()) Err(())
} }
@ -1490,14 +1490,14 @@ impl<'a> StringReader<'a> {
if self.ch_is('\n') { if self.ch_is('\n') {
self.bump(); self.bump();
} }
return val; val
} }
fn read_one_line_comment(&mut self) -> String { fn read_one_line_comment(&mut self) -> String {
let val = self.read_to_eol(); let val = self.read_to_eol();
assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') || assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') ||
(val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!')); (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
return val; val
} }
fn consume_non_eol_whitespace(&mut self) { fn consume_non_eol_whitespace(&mut self) {
@ -1541,7 +1541,7 @@ impl<'a> StringReader<'a> {
Symbol::intern("?") Symbol::intern("?")
}; };
self.bump(); // advance ch past token self.bump(); // advance ch past token
return token::Byte(id); token::Byte(id)
} }
fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool { fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
@ -1574,7 +1574,7 @@ impl<'a> StringReader<'a> {
Symbol::intern("??") Symbol::intern("??")
}; };
self.bump(); self.bump();
return token::ByteStr(id); token::ByteStr(id)
} }
fn scan_raw_byte_string(&mut self) -> token::Lit { fn scan_raw_byte_string(&mut self) -> token::Lit {
@ -1627,8 +1627,8 @@ impl<'a> StringReader<'a> {
self.bump(); self.bump();
} }
self.bump(); self.bump();
return token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos),
hash_count); hash_count)
} }
} }
@ -1646,7 +1646,7 @@ fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
} }
fn is_dec_digit(c: Option<char>) -> bool { fn is_dec_digit(c: Option<char>) -> bool {
return in_range(c, '0', '9'); in_range(c, '0', '9')
} }
pub fn is_doc_comment(s: &str) -> bool { pub fn is_doc_comment(s: &str) -> bool {

View file

@ -107,18 +107,18 @@ pub fn parse_crate_attrs_from_file<'a>(input: &Path, sess: &'a ParseSess)
parser.parse_inner_attributes() parser.parse_inner_attributes()
} }
pub fn parse_crate_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_crate_from_source_str(name: String, source: String, sess: &ParseSess)
-> PResult<'a, ast::Crate> { -> PResult<ast::Crate> {
new_parser_from_source_str(sess, name, source).parse_crate_mod() new_parser_from_source_str(sess, name, source).parse_crate_mod()
} }
pub fn parse_crate_attrs_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_crate_attrs_from_source_str(name: String, source: String, sess: &ParseSess)
-> PResult<'a, Vec<ast::Attribute>> { -> PResult<Vec<ast::Attribute>> {
new_parser_from_source_str(sess, name, source).parse_inner_attributes() new_parser_from_source_str(sess, name, source).parse_inner_attributes()
} }
pub fn parse_expr_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_expr_from_source_str(name: String, source: String, sess: &ParseSess)
-> PResult<'a, P<ast::Expr>> { -> PResult<P<ast::Expr>> {
new_parser_from_source_str(sess, name, source).parse_expr() new_parser_from_source_str(sess, name, source).parse_expr()
} }
@ -126,29 +126,29 @@ pub fn parse_expr_from_source_str<'a>(name: String, source: String, sess: &'a Pa
/// ///
/// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err` /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and`Err`
/// when a syntax error occurred. /// when a syntax error occurred.
pub fn parse_item_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_item_from_source_str(name: String, source: String, sess: &ParseSess)
-> PResult<'a, Option<P<ast::Item>>> { -> PResult<Option<P<ast::Item>>> {
new_parser_from_source_str(sess, name, source).parse_item() new_parser_from_source_str(sess, name, source).parse_item()
} }
pub fn parse_meta_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_meta_from_source_str(name: String, source: String, sess: &ParseSess)
-> PResult<'a, ast::MetaItem> { -> PResult<ast::MetaItem> {
new_parser_from_source_str(sess, name, source).parse_meta_item() new_parser_from_source_str(sess, name, source).parse_meta_item()
} }
pub fn parse_stmt_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_stmt_from_source_str(name: String, source: String, sess: &ParseSess)
-> PResult<'a, Option<ast::Stmt>> { -> PResult<Option<ast::Stmt>> {
new_parser_from_source_str(sess, name, source).parse_stmt() new_parser_from_source_str(sess, name, source).parse_stmt()
} }
pub fn parse_stream_from_source_str<'a>(name: String, source: String, sess: &'a ParseSess) pub fn parse_stream_from_source_str(name: String, source: String, sess: &ParseSess)
-> TokenStream { -> TokenStream {
filemap_to_stream(sess, sess.codemap().new_filemap(name, source)) filemap_to_stream(sess, sess.codemap().new_filemap(name, source))
} }
// Create a new parser from a source string // Create a new parser from a source string
pub fn new_parser_from_source_str<'a>(sess: &'a ParseSess, name: String, source: String) pub fn new_parser_from_source_str(sess: &ParseSess, name: String, source: String)
-> Parser<'a> { -> Parser {
filemap_to_parser(sess, sess.codemap().new_filemap(name, source)) filemap_to_parser(sess, sess.codemap().new_filemap(name, source))
} }
@ -173,7 +173,7 @@ pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess,
} }
/// Given a filemap and config, return a parser /// Given a filemap and config, return a parser
pub fn filemap_to_parser<'a>(sess: &'a ParseSess, filemap: Rc<FileMap>, ) -> Parser<'a> { pub fn filemap_to_parser(sess: & ParseSess, filemap: Rc<FileMap>, ) -> Parser {
let end_pos = filemap.end_pos; let end_pos = filemap.end_pos;
let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap)); let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap));
@ -186,7 +186,7 @@ pub fn filemap_to_parser<'a>(sess: &'a ParseSess, filemap: Rc<FileMap>, ) -> Par
// must preserve old name for now, because quote! from the *existing* // must preserve old name for now, because quote! from the *existing*
// compiler expands into it // compiler expands into it
pub fn new_parser_from_tts<'a>(sess: &'a ParseSess, tts: Vec<TokenTree>) -> Parser<'a> { pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec<TokenTree>) -> Parser {
stream_to_parser(sess, tts.into_iter().collect()) stream_to_parser(sess, tts.into_iter().collect())
} }
@ -216,8 +216,8 @@ pub fn filemap_to_stream(sess: &ParseSess, filemap: Rc<FileMap>) -> TokenStream
panictry!(srdr.parse_all_token_trees()) panictry!(srdr.parse_all_token_trees())
} }
/// Given stream and the ParseSess, produce a parser /// Given stream and the `ParseSess`, produce a parser
pub fn stream_to_parser<'a>(sess: &'a ParseSess, stream: TokenStream) -> Parser<'a> { pub fn stream_to_parser(sess: &ParseSess, stream: TokenStream) -> Parser {
Parser::new(sess, stream, None, false) Parser::new(sess, stream, None, false)
} }
@ -251,7 +251,7 @@ pub fn char_lit(lit: &str) -> (char, isize) {
(c, 4) (c, 4)
} }
'u' => { 'u' => {
assert!(lit.as_bytes()[2] == b'{'); assert_eq!(lit.as_bytes()[2], b'{');
let idx = lit.find('}').unwrap(); let idx = lit.find('}').unwrap();
let v = u32::from_str_radix(&lit[3..idx], 16).unwrap(); let v = u32::from_str_radix(&lit[3..idx], 16).unwrap();
let c = char::from_u32(v).unwrap(); let c = char::from_u32(v).unwrap();
@ -287,51 +287,46 @@ pub fn str_lit(lit: &str) -> String {
} }
let mut chars = lit.char_indices().peekable(); let mut chars = lit.char_indices().peekable();
loop { while let Some((i, c)) = chars.next() {
match chars.next() { match c {
Some((i, c)) => { '\\' => {
match c { let ch = chars.peek().unwrap_or_else(|| {
'\\' => { panic!("{}", error(i))
let ch = chars.peek().unwrap_or_else(|| { }).1;
panic!("{}", error(i))
}).1;
if ch == '\n' { if ch == '\n' {
eat(&mut chars); eat(&mut chars);
} else if ch == '\r' { } else if ch == '\r' {
chars.next(); chars.next();
let ch = chars.peek().unwrap_or_else(|| { let ch = chars.peek().unwrap_or_else(|| {
panic!("{}", error(i)) panic!("{}", error(i))
}).1; }).1;
if ch != '\n' { if ch != '\n' {
panic!("lexer accepted bare CR"); panic!("lexer accepted bare CR");
}
eat(&mut chars);
} else {
// otherwise, a normal escape
let (c, n) = char_lit(&lit[i..]);
for _ in 0..n - 1 { // we don't need to move past the first \
chars.next();
}
res.push(c);
}
},
'\r' => {
let ch = chars.peek().unwrap_or_else(|| {
panic!("{}", error(i))
}).1;
if ch != '\n' {
panic!("lexer accepted bare CR");
}
chars.next();
res.push('\n');
} }
c => res.push(c), eat(&mut chars);
} else {
// otherwise, a normal escape
let (c, n) = char_lit(&lit[i..]);
for _ in 0..n - 1 { // we don't need to move past the first \
chars.next();
}
res.push(c);
} }
}, },
None => break '\r' => {
let ch = chars.peek().unwrap_or_else(|| {
panic!("{}", error(i))
}).1;
if ch != '\n' {
panic!("lexer accepted bare CR");
}
chars.next();
res.push('\n');
}
c => res.push(c),
} }
} }
@ -346,22 +341,16 @@ pub fn raw_str_lit(lit: &str) -> String {
debug!("raw_str_lit: given {}", escape_default(lit)); debug!("raw_str_lit: given {}", escape_default(lit));
let mut res = String::with_capacity(lit.len()); let mut res = String::with_capacity(lit.len());
// FIXME #8372: This could be a for-loop if it didn't borrow the iterator
let mut chars = lit.chars().peekable(); let mut chars = lit.chars().peekable();
loop { while let Some(c) = chars.next() {
match chars.next() { if c == '\r' {
Some(c) => { if *chars.peek().unwrap() != '\n' {
if c == '\r' { panic!("lexer accepted bare CR");
if *chars.peek().unwrap() != '\n' { }
panic!("lexer accepted bare CR"); chars.next();
} res.push('\n');
chars.next(); } else {
res.push('\n'); res.push(c);
} else {
res.push(c);
}
},
None => break
} }
} }
@ -459,7 +448,7 @@ pub fn byte_lit(lit: &str) -> (u8, usize) {
if lit.len() == 1 { if lit.len() == 1 {
(lit.as_bytes()[0], 1) (lit.as_bytes()[0], 1)
} else { } else {
assert!(lit.as_bytes()[0] == b'\\', err(0)); assert_eq!(lit.as_bytes()[0], b'\\', "{}", err(0));
let b = match lit.as_bytes()[1] { let b = match lit.as_bytes()[1] {
b'"' => b'"', b'"' => b'"',
b'n' => b'\n', b'n' => b'\n',
@ -480,7 +469,7 @@ pub fn byte_lit(lit: &str) -> (u8, usize) {
} }
} }
}; };
return (b, 2); (b, 2)
} }
} }
@ -491,7 +480,7 @@ pub fn byte_str_lit(lit: &str) -> Rc<Vec<u8>> {
let error = |i| format!("lexer should have rejected {} at {}", lit, i); let error = |i| format!("lexer should have rejected {} at {}", lit, i);
/// Eat everything up to a non-whitespace /// Eat everything up to a non-whitespace
fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) { fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
loop { loop {
match it.peek().map(|x| x.1) { match it.peek().map(|x| x.1) {
Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => { Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => {
@ -578,7 +567,7 @@ pub fn integer_lit(s: &str, suffix: Option<Symbol>, diag: Option<(Span, &Handler
if let Some(err) = err { if let Some(err) = err {
err!(diag, |span, diag| diag.span_err(span, err)); err!(diag, |span, diag| diag.span_err(span, err));
} }
return filtered_float_lit(Symbol::intern(&s), Some(suf), diag) return filtered_float_lit(Symbol::intern(s), Some(suf), diag)
} }
} }

View file

@ -59,7 +59,7 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> {
if !self.obsolete_set.contains(&kind) && if !self.obsolete_set.contains(&kind) &&
(error || self.sess.span_diagnostic.can_emit_warnings) { (error || self.sess.span_diagnostic.can_emit_warnings) {
err.note(&format!("{}", desc)); err.note(desc);
self.obsolete_set.insert(kind); self.obsolete_set.insert(kind);
} }
err.emit(); err.emit();

View file

@ -248,7 +248,7 @@ impl TokenCursor {
fn next_desugared(&mut self) -> TokenAndSpan { fn next_desugared(&mut self) -> TokenAndSpan {
let (sp, name) = match self.next() { let (sp, name) = match self.next() {
TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name), TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
tok @ _ => return tok, tok => return tok,
}; };
let stripped = strip_doc_comment_decoration(&name.as_str()); let stripped = strip_doc_comment_decoration(&name.as_str());
@ -354,7 +354,7 @@ pub enum Error {
} }
impl Error { impl Error {
pub fn span_err<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> { pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
match self { match self {
Error::FileNotFoundForModule { ref mod_name, Error::FileNotFoundForModule { ref mod_name,
ref default_path, ref default_path,
@ -478,9 +478,10 @@ impl<'a> Parser<'a> {
} }
fn next_tok(&mut self) -> TokenAndSpan { fn next_tok(&mut self) -> TokenAndSpan {
let mut next = match self.desugar_doc_comments { let mut next = if self.desugar_doc_comments {
true => self.token_cursor.next_desugared(), self.token_cursor.next_desugared()
false => self.token_cursor.next(), } else {
self.token_cursor.next()
}; };
if next.sp == syntax_pos::DUMMY_SP { if next.sp == syntax_pos::DUMMY_SP {
next.sp = self.prev_span; next.sp = self.prev_span;
@ -551,7 +552,7 @@ impl<'a> Parser<'a> {
// This might be a sign we need a connect method on Iterator. // This might be a sign we need a connect method on Iterator.
let b = i.next() let b = i.next()
.map_or("".to_string(), |t| t.to_string()); .map_or("".to_string(), |t| t.to_string());
i.enumerate().fold(b, |mut b, (i, ref a)| { i.enumerate().fold(b, |mut b, (i, a)| {
if tokens.len() > 2 && i == tokens.len() - 2 { if tokens.len() > 2 && i == tokens.len() - 2 {
b.push_str(", or "); b.push_str(", or ");
} else if tokens.len() == 2 && i == tokens.len() - 2 { } else if tokens.len() == 2 && i == tokens.len() - 2 {
@ -985,18 +986,15 @@ impl<'a> Parser<'a> {
token::CloseDelim(..) | token::Eof => break, token::CloseDelim(..) | token::Eof => break,
_ => {} _ => {}
}; };
match sep.sep { if let Some(ref t) = sep.sep {
Some(ref t) => { if first {
if first { first = false;
first = false; } else {
} else { if let Err(e) = self.expect(t) {
if let Err(e) = self.expect(t) { fe(e);
fe(e); break;
break;
}
} }
} }
_ => ()
} }
if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) { if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
break; break;
@ -1493,7 +1491,7 @@ impl<'a> Parser<'a> {
let sum_span = ty.span.to(self.prev_span); let sum_span = ty.span.to(self.prev_span);
let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178, let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
"expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(&ty)); "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
match ty.node { match ty.node {
TyKind::Rptr(ref lifetime, ref mut_ty) => { TyKind::Rptr(ref lifetime, ref mut_ty) => {
@ -1547,7 +1545,7 @@ impl<'a> Parser<'a> {
pub fn is_named_argument(&mut self) -> bool { pub fn is_named_argument(&mut self) -> bool {
let offset = match self.token { let offset = match self.token {
token::BinOp(token::And) => 1, token::BinOp(token::And) |
token::AndAnd => 1, token::AndAnd => 1,
_ if self.token.is_keyword(keywords::Mut) => 1, _ if self.token.is_keyword(keywords::Mut) => 1,
_ => 0 _ => 0
@ -3154,10 +3152,11 @@ impl<'a> Parser<'a> {
let attrs = self.parse_outer_attributes()?; let attrs = self.parse_outer_attributes()?;
let pats = self.parse_pats()?; let pats = self.parse_pats()?;
let mut guard = None; let guard = if self.eat_keyword(keywords::If) {
if self.eat_keyword(keywords::If) { Some(self.parse_expr()?)
guard = Some(self.parse_expr()?); } else {
} None
};
self.expect(&token::FatArrow)?; self.expect(&token::FatArrow)?;
let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?; let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
@ -3600,10 +3599,11 @@ impl<'a> Parser<'a> {
let lo = self.span; let lo = self.span;
let pat = self.parse_pat()?; let pat = self.parse_pat()?;
let mut ty = None; let ty = if self.eat(&token::Colon) {
if self.eat(&token::Colon) { Some(self.parse_ty()?)
ty = Some(self.parse_ty()?); } else {
} None
};
let init = self.parse_initializer()?; let init = self.parse_initializer()?;
Ok(P(ast::Local { Ok(P(ast::Local {
ty: ty, ty: ty,
@ -3929,7 +3929,7 @@ impl<'a> Parser<'a> {
}, },
None => { None => {
let unused_attrs = |attrs: &[_], s: &mut Self| { let unused_attrs = |attrs: &[_], s: &mut Self| {
if attrs.len() > 0 { if !attrs.is_empty() {
if s.prev_token_kind == PrevTokenKind::DocComment { if s.prev_token_kind == PrevTokenKind::DocComment {
s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit(); s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
} else { } else {
@ -4815,7 +4815,7 @@ impl<'a> Parser<'a> {
self.expect(&token::Not)?; self.expect(&token::Not)?;
} }
self.complain_if_pub_macro(&vis, prev_span); self.complain_if_pub_macro(vis, prev_span);
// eat a matched-delimiter token tree: // eat a matched-delimiter token tree:
*at_end = true; *at_end = true;
@ -4917,13 +4917,10 @@ impl<'a> Parser<'a> {
} }
} }
} else { } else {
match polarity { if polarity == ast::ImplPolarity::Negative {
ast::ImplPolarity::Negative => { // This is a negated type implementation
// This is a negated type implementation // `impl !MyType {}`, which is not allowed.
// `impl !MyType {}`, which is not allowed. self.span_err(neg_span, "inherent implementation can't be negated");
self.span_err(neg_span, "inherent implementation can't be negated");
},
_ => {}
} }
None None
}; };
@ -5185,7 +5182,7 @@ impl<'a> Parser<'a> {
let path_span = self.prev_span; let path_span = self.prev_span;
let help_msg = format!("make this visible only to module `{}` with `in`:", path); let help_msg = format!("make this visible only to module `{}` with `in`:", path);
self.expect(&token::CloseDelim(token::Paren))?; // `)` self.expect(&token::CloseDelim(token::Paren))?; // `)`
let mut err = self.span_fatal_help(path_span, &msg, &suggestion); let mut err = self.span_fatal_help(path_span, msg, suggestion);
err.span_suggestion(path_span, &help_msg, format!("in {}", path)); err.span_suggestion(path_span, &help_msg, format!("in {}", path));
err.emit(); // emit diagnostic, but continue with public visibility err.emit(); // emit diagnostic, but continue with public visibility
} }

View file

@ -53,6 +53,10 @@ impl DelimToken {
pub fn len(self) -> usize { pub fn len(self) -> usize {
if self == NoDelim { 0 } else { 1 } if self == NoDelim { 0 } else { 1 }
} }
pub fn is_empty(self) -> bool {
self == NoDelim
}
} }
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)] #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
@ -198,17 +202,17 @@ impl Token {
pub fn can_begin_expr(&self) -> bool { pub fn can_begin_expr(&self) -> bool {
match *self { match *self {
Ident(ident) => ident_can_begin_expr(ident), // value name or keyword Ident(ident) => ident_can_begin_expr(ident), // value name or keyword
OpenDelim(..) => true, // tuple, array or block OpenDelim(..) | // tuple, array or block
Literal(..) => true, // literal Literal(..) | // literal
Not => true, // operator not Not | // operator not
BinOp(Minus) => true, // unary minus BinOp(Minus) | // unary minus
BinOp(Star) => true, // dereference BinOp(Star) | // dereference
BinOp(Or) | OrOr => true, // closure BinOp(Or) | OrOr | // closure
BinOp(And) => true, // reference BinOp(And) | // reference
AndAnd => true, // double reference AndAnd | // double reference
DotDot | DotDotDot => true, // range notation DotDot | DotDotDot | // range notation
Lt | BinOp(Shl) => true, // associated path Lt | BinOp(Shl) | // associated path
ModSep => true, // global path ModSep | // global path
Pound => true, // expression attributes Pound => true, // expression attributes
Interpolated(ref nt) => match **nt { Interpolated(ref nt) => match **nt {
NtIdent(..) | NtExpr(..) | NtBlock(..) | NtPath(..) => true, NtIdent(..) | NtExpr(..) | NtBlock(..) | NtPath(..) => true,
@ -222,16 +226,16 @@ impl Token {
pub fn can_begin_type(&self) -> bool { pub fn can_begin_type(&self) -> bool {
match *self { match *self {
Ident(ident) => ident_can_begin_type(ident), // type name or keyword Ident(ident) => ident_can_begin_type(ident), // type name or keyword
OpenDelim(Paren) => true, // tuple OpenDelim(Paren) | // tuple
OpenDelim(Bracket) => true, // array OpenDelim(Bracket) | // array
Underscore => true, // placeholder Underscore | // placeholder
Not => true, // never Not | // never
BinOp(Star) => true, // raw pointer BinOp(Star) | // raw pointer
BinOp(And) => true, // reference BinOp(And) | // reference
AndAnd => true, // double reference AndAnd | // double reference
Question => true, // maybe bound in trait object Question | // maybe bound in trait object
Lifetime(..) => true, // lifetime bound in trait object Lifetime(..) | // lifetime bound in trait object
Lt | BinOp(Shl) => true, // associated path Lt | BinOp(Shl) | // associated path
ModSep => true, // global path ModSep => true, // global path
Interpolated(ref nt) => match **nt { Interpolated(ref nt) => match **nt {
NtIdent(..) | NtTy(..) | NtPath(..) => true, NtIdent(..) | NtTy(..) | NtPath(..) => true,

View file

@ -113,22 +113,22 @@
//! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer //! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer
//! and point-in-infinite-stream senses freely. //! and point-in-infinite-stream senses freely.
//! //!
//! There is a parallel ring buffer, 'size', that holds the calculated size of //! There is a parallel ring buffer, `size`, that holds the calculated size of
//! each token. Why calculated? Because for Begin/End pairs, the "size" //! each token. Why calculated? Because for Begin/End pairs, the "size"
//! includes everything between the pair. That is, the "size" of Begin is //! includes everything between the pair. That is, the "size" of Begin is
//! actually the sum of the sizes of everything between Begin and the paired //! actually the sum of the sizes of everything between Begin and the paired
//! End that follows. Since that is arbitrarily far in the future, 'size' is //! End that follows. Since that is arbitrarily far in the future, `size` is
//! being rewritten regularly while the printer runs; in fact most of the //! being rewritten regularly while the printer runs; in fact most of the
//! machinery is here to work out 'size' entries on the fly (and give up when //! machinery is here to work out `size` entries on the fly (and give up when
//! they're so obviously over-long that "infinity" is a good enough //! they're so obviously over-long that "infinity" is a good enough
//! approximation for purposes of line breaking). //! approximation for purposes of line breaking).
//! //!
//! The "input side" of the printer is managed as an abstract process called //! The "input side" of the printer is managed as an abstract process called
//! SCAN, which uses 'scan_stack', to manage calculating 'size'. SCAN is, in //! SCAN, which uses `scan_stack`, to manage calculating `size`. SCAN is, in
//! other words, the process of calculating 'size' entries. //! other words, the process of calculating 'size' entries.
//! //!
//! The "output side" of the printer is managed by an abstract process called //! The "output side" of the printer is managed by an abstract process called
//! PRINT, which uses 'print_stack', 'margin' and 'space' to figure out what to //! PRINT, which uses `print_stack`, `margin` and `space` to figure out what to
//! do with each token/size pair it consumes as it goes. It's trying to consume //! do with each token/size pair it consumes as it goes. It's trying to consume
//! the entire buffered window, but can't output anything until the size is >= //! the entire buffered window, but can't output anything until the size is >=
//! 0 (sizes are set to negative while they're pending calculation). //! 0 (sizes are set to negative while they're pending calculation).
@ -409,7 +409,7 @@ impl<'a> Printer<'a> {
pub fn advance_right(&mut self) { pub fn advance_right(&mut self) {
self.right += 1; self.right += 1;
self.right %= self.buf_len; self.right %= self.buf_len;
assert!(self.right != self.left); assert_ne!(self.right, self.left);
} }
pub fn advance_left(&mut self) -> io::Result<()> { pub fn advance_left(&mut self) -> io::Result<()> {
debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right, debug!("advance_left Vec<{},{}>, sizeof({})={}", self.left, self.right,

View file

@ -233,7 +233,7 @@ pub fn token_to_string(tok: &Token) -> String {
token::CloseDelim(token::Bracket) => "]".to_string(), token::CloseDelim(token::Bracket) => "]".to_string(),
token::OpenDelim(token::Brace) => "{".to_string(), token::OpenDelim(token::Brace) => "{".to_string(),
token::CloseDelim(token::Brace) => "}".to_string(), token::CloseDelim(token::Brace) => "}".to_string(),
token::OpenDelim(token::NoDelim) => " ".to_string(), token::OpenDelim(token::NoDelim) |
token::CloseDelim(token::NoDelim) => " ".to_string(), token::CloseDelim(token::NoDelim) => " ".to_string(),
token::Pound => "#".to_string(), token::Pound => "#".to_string(),
token::Dollar => "$".to_string(), token::Dollar => "$".to_string(),
@ -244,7 +244,7 @@ pub fn token_to_string(tok: &Token) -> String {
let mut out = match lit { let mut out = match lit {
token::Byte(b) => format!("b'{}'", b), token::Byte(b) => format!("b'{}'", b),
token::Char(c) => format!("'{}'", c), token::Char(c) => format!("'{}'", c),
token::Float(c) => c.to_string(), token::Float(c) |
token::Integer(c) => c.to_string(), token::Integer(c) => c.to_string(),
token::Str_(s) => format!("\"{}\"", s), token::Str_(s) => format!("\"{}\"", s),
token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}", token::StrRaw(s, n) => format!("r{delim}\"{string}\"{delim}",
@ -277,23 +277,23 @@ pub fn token_to_string(tok: &Token) -> String {
token::Shebang(s) => format!("/* shebang: {}*/", s), token::Shebang(s) => format!("/* shebang: {}*/", s),
token::Interpolated(ref nt) => match **nt { token::Interpolated(ref nt) => match **nt {
token::NtExpr(ref e) => expr_to_string(&e), token::NtExpr(ref e) => expr_to_string(e),
token::NtMeta(ref e) => meta_item_to_string(&e), token::NtMeta(ref e) => meta_item_to_string(e),
token::NtTy(ref e) => ty_to_string(&e), token::NtTy(ref e) => ty_to_string(e),
token::NtPath(ref e) => path_to_string(&e), token::NtPath(ref e) => path_to_string(e),
token::NtItem(ref e) => item_to_string(&e), token::NtItem(ref e) => item_to_string(e),
token::NtBlock(ref e) => block_to_string(&e), token::NtBlock(ref e) => block_to_string(e),
token::NtStmt(ref e) => stmt_to_string(&e), token::NtStmt(ref e) => stmt_to_string(e),
token::NtPat(ref e) => pat_to_string(&e), token::NtPat(ref e) => pat_to_string(e),
token::NtIdent(ref e) => ident_to_string(e.node), token::NtIdent(ref e) => ident_to_string(e.node),
token::NtTT(ref tree) => tt_to_string(tree.clone()), token::NtTT(ref tree) => tt_to_string(tree.clone()),
token::NtArm(ref e) => arm_to_string(&e), token::NtArm(ref e) => arm_to_string(e),
token::NtImplItem(ref e) => impl_item_to_string(&e), token::NtImplItem(ref e) => impl_item_to_string(e),
token::NtTraitItem(ref e) => trait_item_to_string(&e), token::NtTraitItem(ref e) => trait_item_to_string(e),
token::NtGenerics(ref e) => generics_to_string(&e), token::NtGenerics(ref e) => generics_to_string(e),
token::NtWhereClause(ref e) => where_clause_to_string(&e), token::NtWhereClause(ref e) => where_clause_to_string(e),
token::NtArg(ref e) => arg_to_string(&e), token::NtArg(ref e) => arg_to_string(e),
token::NtVis(ref e) => vis_to_string(&e), token::NtVis(ref e) => vis_to_string(e),
} }
} }
} }
@ -520,8 +520,7 @@ pub trait PrintState<'a> {
let mut result = None; let mut result = None;
if let &Some(ref lits) = self.literals() if let Some(ref lits) = *self.literals() {
{
while cur_lit < lits.len() { while cur_lit < lits.len() {
let ltrl = (*lits)[cur_lit].clone(); let ltrl = (*lits)[cur_lit].clone();
if ltrl.pos > pos { break; } if ltrl.pos > pos { break; }
@ -618,11 +617,8 @@ pub trait PrintState<'a> {
fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> { fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
self.maybe_print_comment(lit.span.lo)?; self.maybe_print_comment(lit.span.lo)?;
match self.next_lit(lit.span.lo) { if let Some(ref ltrl) = self.next_lit(lit.span.lo) {
Some(ref ltrl) => { return word(self.writer(), &(*ltrl).lit);
return word(self.writer(), &(*ltrl).lit);
}
_ => ()
} }
match lit.node { match lit.node {
ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style), ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
@ -799,7 +795,7 @@ pub trait PrintState<'a> {
self.popen()?; self.popen()?;
self.commasep(Consistent, self.commasep(Consistent,
&items[..], &items[..],
|s, i| s.print_meta_list_item(&i))?; |s, i| s.print_meta_list_item(i))?;
self.pclose()?; self.pclose()?;
} }
} }
@ -982,14 +978,14 @@ impl<'a> State<'a> {
pub fn commasep_exprs(&mut self, b: Breaks, pub fn commasep_exprs(&mut self, b: Breaks,
exprs: &[P<ast::Expr>]) -> io::Result<()> { exprs: &[P<ast::Expr>]) -> io::Result<()> {
self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span) self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
} }
pub fn print_mod(&mut self, _mod: &ast::Mod, pub fn print_mod(&mut self, _mod: &ast::Mod,
attrs: &[ast::Attribute]) -> io::Result<()> { attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_inner_attributes(attrs)?; self.print_inner_attributes(attrs)?;
for item in &_mod.items { for item in &_mod.items {
self.print_item(&item)?; self.print_item(item)?;
} }
Ok(()) Ok(())
} }
@ -1018,7 +1014,7 @@ impl<'a> State<'a> {
match ty.node { match ty.node {
ast::TyKind::Slice(ref ty) => { ast::TyKind::Slice(ref ty) => {
word(&mut self.s, "[")?; word(&mut self.s, "[")?;
self.print_type(&ty)?; self.print_type(ty)?;
word(&mut self.s, "]")?; word(&mut self.s, "]")?;
} }
ast::TyKind::Ptr(ref mt) => { ast::TyKind::Ptr(ref mt) => {
@ -1040,7 +1036,7 @@ impl<'a> State<'a> {
ast::TyKind::Tup(ref elts) => { ast::TyKind::Tup(ref elts) => {
self.popen()?; self.popen()?;
self.commasep(Inconsistent, &elts[..], self.commasep(Inconsistent, &elts[..],
|s, ty| s.print_type(&ty))?; |s, ty| s.print_type(ty))?;
if elts.len() == 1 { if elts.len() == 1 {
word(&mut self.s, ",")?; word(&mut self.s, ",")?;
} }
@ -1048,7 +1044,7 @@ impl<'a> State<'a> {
} }
ast::TyKind::Paren(ref typ) => { ast::TyKind::Paren(ref typ) => {
self.popen()?; self.popen()?;
self.print_type(&typ)?; self.print_type(typ)?;
self.pclose()?; self.pclose()?;
} }
ast::TyKind::BareFn(ref f) => { ast::TyKind::BareFn(ref f) => {
@ -1081,14 +1077,14 @@ impl<'a> State<'a> {
} }
ast::TyKind::Array(ref ty, ref v) => { ast::TyKind::Array(ref ty, ref v) => {
word(&mut self.s, "[")?; word(&mut self.s, "[")?;
self.print_type(&ty)?; self.print_type(ty)?;
word(&mut self.s, "; ")?; word(&mut self.s, "; ")?;
self.print_expr(&v)?; self.print_expr(v)?;
word(&mut self.s, "]")?; word(&mut self.s, "]")?;
} }
ast::TyKind::Typeof(ref e) => { ast::TyKind::Typeof(ref e) => {
word(&mut self.s, "typeof(")?; word(&mut self.s, "typeof(")?;
self.print_expr(&e)?; self.print_expr(e)?;
word(&mut self.s, ")")?; word(&mut self.s, ")")?;
} }
ast::TyKind::Infer => { ast::TyKind::Infer => {
@ -1130,7 +1126,7 @@ impl<'a> State<'a> {
} }
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(&t)?; self.print_type(t)?;
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
self.end()?; // end the head-ibox self.end()?; // end the head-ibox
self.end() // end the outer cbox self.end() // end the outer cbox
@ -1187,7 +1183,7 @@ impl<'a> State<'a> {
self.head(&visibility_qualified(&item.vis, "extern crate"))?; self.head(&visibility_qualified(&item.vis, "extern crate"))?;
if let Some(p) = *optional_path { if let Some(p) = *optional_path {
let val = p.as_str(); let val = p.as_str();
if val.contains("-") { if val.contains('-') {
self.print_string(&val, ast::StrStyle::Cooked)?; self.print_string(&val, ast::StrStyle::Cooked)?;
} else { } else {
self.print_name(p)?; self.print_name(p)?;
@ -1203,7 +1199,7 @@ impl<'a> State<'a> {
} }
ast::ItemKind::Use(ref vp) => { ast::ItemKind::Use(ref vp) => {
self.head(&visibility_qualified(&item.vis, "use"))?; self.head(&visibility_qualified(&item.vis, "use"))?;
self.print_view_path(&vp)?; self.print_view_path(vp)?;
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
self.end()?; // end inner head-block self.end()?; // end inner head-block
self.end()?; // end outer head-block self.end()?; // end outer head-block
@ -1215,12 +1211,12 @@ impl<'a> State<'a> {
} }
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(&ty)?; self.print_type(ty)?;
space(&mut self.s)?; space(&mut self.s)?;
self.end()?; // end the head-ibox self.end()?; // end the head-ibox
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&expr)?; self.print_expr(expr)?;
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
self.end()?; // end the outer cbox self.end()?; // end the outer cbox
} }
@ -1228,12 +1224,12 @@ impl<'a> State<'a> {
self.head(&visibility_qualified(&item.vis, "const"))?; self.head(&visibility_qualified(&item.vis, "const"))?;
self.print_ident(item.ident)?; self.print_ident(item.ident)?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(&ty)?; self.print_type(ty)?;
space(&mut self.s)?; space(&mut self.s)?;
self.end()?; // end the head-ibox self.end()?; // end the head-ibox
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&expr)?; self.print_expr(expr)?;
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
self.end()?; // end the outer cbox self.end()?; // end the outer cbox
} }
@ -1249,7 +1245,7 @@ impl<'a> State<'a> {
&item.vis &item.vis
)?; )?;
word(&mut self.s, " ")?; word(&mut self.s, " ")?;
self.print_block_with_attrs(&body, &item.attrs)?; self.print_block_with_attrs(body, &item.attrs)?;
} }
ast::ItemKind::Mod(ref _mod) => { ast::ItemKind::Mod(ref _mod) => {
self.head(&visibility_qualified(&item.vis, "mod"))?; self.head(&visibility_qualified(&item.vis, "mod"))?;
@ -1282,7 +1278,7 @@ impl<'a> State<'a> {
self.print_where_clause(&params.where_clause)?; self.print_where_clause(&params.where_clause)?;
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("=")?; self.word_space("=")?;
self.print_type(&ty)?; self.print_type(ty)?;
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
self.end()?; // end the outer ibox self.end()?; // end the outer ibox
} }
@ -1297,11 +1293,11 @@ impl<'a> State<'a> {
} }
ast::ItemKind::Struct(ref struct_def, ref generics) => { ast::ItemKind::Struct(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "struct"))?; self.head(&visibility_qualified(&item.vis, "struct"))?;
self.print_struct(&struct_def, generics, item.ident, item.span, true)?; self.print_struct(struct_def, generics, item.ident, item.span, true)?;
} }
ast::ItemKind::Union(ref struct_def, ref generics) => { ast::ItemKind::Union(ref struct_def, ref generics) => {
self.head(&visibility_qualified(&item.vis, "union"))?; self.head(&visibility_qualified(&item.vis, "union"))?;
self.print_struct(&struct_def, generics, item.ident, item.span, true)?; self.print_struct(struct_def, generics, item.ident, item.span, true)?;
} }
ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => { ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
self.head("")?; self.head("")?;
@ -1333,11 +1329,8 @@ impl<'a> State<'a> {
space(&mut self.s)?; space(&mut self.s)?;
} }
match polarity { if polarity == ast::ImplPolarity::Negative {
ast::ImplPolarity::Negative => { word(&mut self.s, "!")?;
word(&mut self.s, "!")?;
},
_ => {}
} }
if let Some(ref t) = *opt_trait { if let Some(ref t) = *opt_trait {
@ -1346,7 +1339,7 @@ impl<'a> State<'a> {
self.word_space("for")?; self.word_space("for")?;
} }
self.print_type(&ty)?; self.print_type(ty)?;
self.print_where_clause(&generics.where_clause)?; self.print_where_clause(&generics.where_clause)?;
space(&mut self.s)?; space(&mut self.s)?;
@ -1543,7 +1536,7 @@ impl<'a> State<'a> {
Some(ref d) => { Some(ref d) => {
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&d) self.print_expr(d)
} }
_ => Ok(()) _ => Ok(())
} }
@ -1571,7 +1564,7 @@ impl<'a> State<'a> {
self.print_outer_attributes(&ti.attrs)?; self.print_outer_attributes(&ti.attrs)?;
match ti.node { match ti.node {
ast::TraitItemKind::Const(ref ty, ref default) => { ast::TraitItemKind::Const(ref ty, ref default) => {
self.print_associated_const(ti.ident, &ty, self.print_associated_const(ti.ident, ty,
default.as_ref().map(|expr| &**expr), default.as_ref().map(|expr| &**expr),
&ast::Visibility::Inherited)?; &ast::Visibility::Inherited)?;
} }
@ -1614,7 +1607,7 @@ impl<'a> State<'a> {
self.print_defaultness(ii.defaultness)?; self.print_defaultness(ii.defaultness)?;
match ii.node { match ii.node {
ast::ImplItemKind::Const(ref ty, ref expr) => { ast::ImplItemKind::Const(ref ty, ref expr) => {
self.print_associated_const(ii.ident, &ty, Some(&expr), &ii.vis)?; self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
} }
ast::ImplItemKind::Method(ref sig, ref body) => { ast::ImplItemKind::Method(ref sig, ref body) => {
self.head("")?; self.head("")?;
@ -1650,38 +1643,38 @@ impl<'a> State<'a> {
self.word_nbsp("let")?; self.word_nbsp("let")?;
self.ibox(INDENT_UNIT)?; self.ibox(INDENT_UNIT)?;
self.print_local_decl(&loc)?; self.print_local_decl(loc)?;
self.end()?; self.end()?;
if let Some(ref init) = loc.init { if let Some(ref init) = loc.init {
self.nbsp()?; self.nbsp()?;
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&init)?; self.print_expr(init)?;
} }
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
self.end()?; self.end()?;
} }
ast::StmtKind::Item(ref item) => self.print_item(&item)?, ast::StmtKind::Item(ref item) => self.print_item(item)?,
ast::StmtKind::Expr(ref expr) => { ast::StmtKind::Expr(ref expr) => {
self.space_if_not_bol()?; self.space_if_not_bol()?;
self.print_expr_outer_attr_style(&expr, false)?; self.print_expr_outer_attr_style(expr, false)?;
if parse::classify::expr_requires_semi_to_be_stmt(expr) { if parse::classify::expr_requires_semi_to_be_stmt(expr) {
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
} }
} }
ast::StmtKind::Semi(ref expr) => { ast::StmtKind::Semi(ref expr) => {
self.space_if_not_bol()?; self.space_if_not_bol()?;
self.print_expr_outer_attr_style(&expr, false)?; self.print_expr_outer_attr_style(expr, false)?;
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
} }
ast::StmtKind::Mac(ref mac) => { ast::StmtKind::Mac(ref mac) => {
let (ref mac, style, ref attrs) = **mac; let (ref mac, style, ref attrs) = **mac;
self.space_if_not_bol()?; self.space_if_not_bol()?;
self.print_outer_attributes(&attrs)?; self.print_outer_attributes(attrs)?;
let delim = match style { let delim = match style {
ast::MacStmtStyle::Braces => token::Brace, ast::MacStmtStyle::Braces => token::Brace,
_ => token::Paren _ => token::Paren
}; };
self.print_mac(&mac, delim)?; self.print_mac(mac, delim)?;
if style == ast::MacStmtStyle::Semicolon { if style == ast::MacStmtStyle::Semicolon {
word(&mut self.s, ";")?; word(&mut self.s, ";")?;
} }
@ -1735,7 +1728,7 @@ impl<'a> State<'a> {
ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => { ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
self.maybe_print_comment(st.span.lo)?; self.maybe_print_comment(st.span.lo)?;
self.space_if_not_bol()?; self.space_if_not_bol()?;
self.print_expr_outer_attr_style(&expr, false)?; self.print_expr_outer_attr_style(expr, false)?;
self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?; self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
} }
_ => self.print_stmt(st)?, _ => self.print_stmt(st)?,
@ -1755,9 +1748,9 @@ impl<'a> State<'a> {
self.cbox(INDENT_UNIT - 1)?; self.cbox(INDENT_UNIT - 1)?;
self.ibox(0)?; self.ibox(0)?;
word(&mut self.s, " else if ")?; word(&mut self.s, " else if ")?;
self.print_expr(&i)?; self.print_expr(i)?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block(&then)?; self.print_block(then)?;
self.print_else(e.as_ref().map(|e| &**e)) self.print_else(e.as_ref().map(|e| &**e))
} }
// "another else-if-let" // "another else-if-let"
@ -1765,12 +1758,12 @@ impl<'a> State<'a> {
self.cbox(INDENT_UNIT - 1)?; self.cbox(INDENT_UNIT - 1)?;
self.ibox(0)?; self.ibox(0)?;
word(&mut self.s, " else if let ")?; word(&mut self.s, " else if let ")?;
self.print_pat(&pat)?; self.print_pat(pat)?;
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&expr)?; self.print_expr(expr)?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block(&then)?; self.print_block(then)?;
self.print_else(e.as_ref().map(|e| &**e)) self.print_else(e.as_ref().map(|e| &**e))
} }
// "final else" // "final else"
@ -1778,7 +1771,7 @@ impl<'a> State<'a> {
self.cbox(INDENT_UNIT - 1)?; self.cbox(INDENT_UNIT - 1)?;
self.ibox(0)?; self.ibox(0)?;
word(&mut self.s, " else ")?; word(&mut self.s, " else ")?;
self.print_block(&b) self.print_block(b)
} }
// BLEAH, constraints would be great here // BLEAH, constraints would be great here
_ => { _ => {
@ -1844,12 +1837,8 @@ impl<'a> State<'a> {
binop: ast::BinOp) -> bool { binop: ast::BinOp) -> bool {
match sub_expr.node { match sub_expr.node {
ast::ExprKind::Binary(ref sub_op, _, _) => { ast::ExprKind::Binary(ref sub_op, _, _) => {
if AssocOp::from_ast_binop(sub_op.node).precedence() < AssocOp::from_ast_binop(sub_op.node).precedence() <
AssocOp::from_ast_binop(binop.node).precedence() { AssocOp::from_ast_binop(binop.node).precedence()
true
} else {
false
}
} }
_ => true _ => true
} }
@ -1929,7 +1918,7 @@ impl<'a> State<'a> {
space(&mut self.s)?; space(&mut self.s)?;
} }
word(&mut self.s, "..")?; word(&mut self.s, "..")?;
self.print_expr(&expr)?; self.print_expr(expr)?;
self.end()?; self.end()?;
} }
_ => if !fields.is_empty() { _ => if !fields.is_empty() {
@ -1969,7 +1958,7 @@ impl<'a> State<'a> {
if !tys.is_empty() { if !tys.is_empty() {
word(&mut self.s, "::<")?; word(&mut self.s, "::<")?;
self.commasep(Inconsistent, tys, self.commasep(Inconsistent, tys,
|s, ty| s.print_type(&ty))?; |s, ty| s.print_type(ty))?;
word(&mut self.s, ">")?; word(&mut self.s, ">")?;
} }
self.print_call_post(base_args) self.print_call_post(base_args)
@ -2038,7 +2027,7 @@ impl<'a> State<'a> {
self.print_expr_vec(&exprs[..], attrs)?; self.print_expr_vec(&exprs[..], attrs)?;
} }
ast::ExprKind::Repeat(ref element, ref count) => { ast::ExprKind::Repeat(ref element, ref count) => {
self.print_expr_repeat(&element, &count, attrs)?; self.print_expr_repeat(element, count, attrs)?;
} }
ast::ExprKind::Struct(ref path, ref fields, ref wth) => { ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
self.print_expr_struct(path, &fields[..], wth, attrs)?; self.print_expr_struct(path, &fields[..], wth, attrs)?;
@ -2047,43 +2036,43 @@ impl<'a> State<'a> {
self.print_expr_tup(&exprs[..], attrs)?; self.print_expr_tup(&exprs[..], attrs)?;
} }
ast::ExprKind::Call(ref func, ref args) => { ast::ExprKind::Call(ref func, ref args) => {
self.print_expr_call(&func, &args[..])?; self.print_expr_call(func, &args[..])?;
} }
ast::ExprKind::MethodCall(ident, ref tys, ref args) => { ast::ExprKind::MethodCall(ident, ref tys, ref args) => {
self.print_expr_method_call(ident, &tys[..], &args[..])?; self.print_expr_method_call(ident, &tys[..], &args[..])?;
} }
ast::ExprKind::Binary(op, ref lhs, ref rhs) => { ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
self.print_expr_binary(op, &lhs, &rhs)?; self.print_expr_binary(op, lhs, rhs)?;
} }
ast::ExprKind::Unary(op, ref expr) => { ast::ExprKind::Unary(op, ref expr) => {
self.print_expr_unary(op, &expr)?; self.print_expr_unary(op, expr)?;
} }
ast::ExprKind::AddrOf(m, ref expr) => { ast::ExprKind::AddrOf(m, ref expr) => {
self.print_expr_addr_of(m, &expr)?; self.print_expr_addr_of(m, expr)?;
} }
ast::ExprKind::Lit(ref lit) => { ast::ExprKind::Lit(ref lit) => {
self.print_literal(&lit)?; self.print_literal(lit)?;
} }
ast::ExprKind::Cast(ref expr, ref ty) => { ast::ExprKind::Cast(ref expr, ref ty) => {
if let ast::ExprKind::Cast(..) = expr.node { if let ast::ExprKind::Cast(..) = expr.node {
self.print_expr(&expr)?; self.print_expr(expr)?;
} else { } else {
self.print_expr_maybe_paren(&expr)?; self.print_expr_maybe_paren(expr)?;
} }
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("as")?; self.word_space("as")?;
self.print_type(&ty)?; self.print_type(ty)?;
} }
ast::ExprKind::Type(ref expr, ref ty) => { ast::ExprKind::Type(ref expr, ref ty) => {
self.print_expr(&expr)?; self.print_expr(expr)?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(&ty)?; self.print_type(ty)?;
} }
ast::ExprKind::If(ref test, ref blk, ref elseopt) => { ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e))?; self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
} }
ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => { ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
self.print_if_let(&pat, &expr, &blk, elseopt.as_ref().map(|e| &**e))?; self.print_if_let(pat, expr, blk, elseopt.as_ref().map(|e| &**e))?;
} }
ast::ExprKind::While(ref test, ref blk, opt_ident) => { ast::ExprKind::While(ref test, ref blk, opt_ident) => {
if let Some(ident) = opt_ident { if let Some(ident) = opt_ident {
@ -2091,9 +2080,9 @@ impl<'a> State<'a> {
self.word_space(":")?; self.word_space(":")?;
} }
self.head("while")?; self.head("while")?;
self.print_expr(&test)?; self.print_expr(test)?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block_with_attrs(&blk, attrs)?; self.print_block_with_attrs(blk, attrs)?;
} }
ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => { ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
if let Some(ident) = opt_ident { if let Some(ident) = opt_ident {
@ -2101,12 +2090,12 @@ impl<'a> State<'a> {
self.word_space(":")?; self.word_space(":")?;
} }
self.head("while let")?; self.head("while let")?;
self.print_pat(&pat)?; self.print_pat(pat)?;
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&expr)?; self.print_expr(expr)?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block_with_attrs(&blk, attrs)?; self.print_block_with_attrs(blk, attrs)?;
} }
ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => { ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
if let Some(ident) = opt_ident { if let Some(ident) = opt_ident {
@ -2114,12 +2103,12 @@ impl<'a> State<'a> {
self.word_space(":")?; self.word_space(":")?;
} }
self.head("for")?; self.head("for")?;
self.print_pat(&pat)?; self.print_pat(pat)?;
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("in")?; self.word_space("in")?;
self.print_expr(&iter)?; self.print_expr(iter)?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block_with_attrs(&blk, attrs)?; self.print_block_with_attrs(blk, attrs)?;
} }
ast::ExprKind::Loop(ref blk, opt_ident) => { ast::ExprKind::Loop(ref blk, opt_ident) => {
if let Some(ident) = opt_ident { if let Some(ident) = opt_ident {
@ -2128,13 +2117,13 @@ impl<'a> State<'a> {
} }
self.head("loop")?; self.head("loop")?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block_with_attrs(&blk, attrs)?; self.print_block_with_attrs(blk, attrs)?;
} }
ast::ExprKind::Match(ref expr, ref arms) => { ast::ExprKind::Match(ref expr, ref arms) => {
self.cbox(INDENT_UNIT)?; self.cbox(INDENT_UNIT)?;
self.ibox(4)?; self.ibox(4)?;
self.word_nbsp("match")?; self.word_nbsp("match")?;
self.print_expr(&expr)?; self.print_expr(expr)?;
space(&mut self.s)?; space(&mut self.s)?;
self.bopen()?; self.bopen()?;
self.print_inner_attributes_no_trailing_hardbreak(attrs)?; self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
@ -2146,7 +2135,7 @@ impl<'a> State<'a> {
ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => { ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
self.print_capture_clause(capture_clause)?; self.print_capture_clause(capture_clause)?;
self.print_fn_block_args(&decl)?; self.print_fn_block_args(decl)?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_expr(body)?; self.print_expr(body)?;
self.end()?; // need to close a box self.end()?; // need to close a box
@ -2161,48 +2150,48 @@ impl<'a> State<'a> {
self.cbox(INDENT_UNIT)?; self.cbox(INDENT_UNIT)?;
// head-box, will be closed by print-block after { // head-box, will be closed by print-block after {
self.ibox(0)?; self.ibox(0)?;
self.print_block_with_attrs(&blk, attrs)?; self.print_block_with_attrs(blk, attrs)?;
} }
ast::ExprKind::Assign(ref lhs, ref rhs) => { ast::ExprKind::Assign(ref lhs, ref rhs) => {
self.print_expr(&lhs)?; self.print_expr(lhs)?;
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&rhs)?; self.print_expr(rhs)?;
} }
ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => { ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
self.print_expr(&lhs)?; self.print_expr(lhs)?;
space(&mut self.s)?; space(&mut self.s)?;
word(&mut self.s, op.node.to_string())?; word(&mut self.s, op.node.to_string())?;
self.word_space("=")?; self.word_space("=")?;
self.print_expr(&rhs)?; self.print_expr(rhs)?;
} }
ast::ExprKind::Field(ref expr, id) => { ast::ExprKind::Field(ref expr, id) => {
self.print_expr(&expr)?; self.print_expr(expr)?;
word(&mut self.s, ".")?; word(&mut self.s, ".")?;
self.print_ident(id.node)?; self.print_ident(id.node)?;
} }
ast::ExprKind::TupField(ref expr, id) => { ast::ExprKind::TupField(ref expr, id) => {
self.print_expr(&expr)?; self.print_expr(expr)?;
word(&mut self.s, ".")?; word(&mut self.s, ".")?;
self.print_usize(id.node)?; self.print_usize(id.node)?;
} }
ast::ExprKind::Index(ref expr, ref index) => { ast::ExprKind::Index(ref expr, ref index) => {
self.print_expr(&expr)?; self.print_expr(expr)?;
word(&mut self.s, "[")?; word(&mut self.s, "[")?;
self.print_expr(&index)?; self.print_expr(index)?;
word(&mut self.s, "]")?; word(&mut self.s, "]")?;
} }
ast::ExprKind::Range(ref start, ref end, limits) => { ast::ExprKind::Range(ref start, ref end, limits) => {
if let &Some(ref e) = start { if let Some(ref e) = *start {
self.print_expr(&e)?; self.print_expr(e)?;
} }
if limits == ast::RangeLimits::HalfOpen { if limits == ast::RangeLimits::HalfOpen {
word(&mut self.s, "..")?; word(&mut self.s, "..")?;
} else { } else {
word(&mut self.s, "...")?; word(&mut self.s, "...")?;
} }
if let &Some(ref e) = end { if let Some(ref e) = *end {
self.print_expr(&e)?; self.print_expr(e)?;
} }
} }
ast::ExprKind::Path(None, ref path) => { ast::ExprKind::Path(None, ref path) => {
@ -2233,12 +2222,9 @@ impl<'a> State<'a> {
} }
ast::ExprKind::Ret(ref result) => { ast::ExprKind::Ret(ref result) => {
word(&mut self.s, "return")?; word(&mut self.s, "return")?;
match *result { if let Some(ref expr) = *result {
Some(ref expr) => { word(&mut self.s, " ")?;
word(&mut self.s, " ")?; self.print_expr(expr)?;
self.print_expr(&expr)?;
}
_ => ()
} }
} }
ast::ExprKind::InlineAsm(ref a) => { ast::ExprKind::InlineAsm(ref a) => {
@ -2268,7 +2254,7 @@ impl<'a> State<'a> {
self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| { self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
s.print_string(&co.as_str(), ast::StrStyle::Cooked)?; s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
s.popen()?; s.popen()?;
s.print_expr(&o)?; s.print_expr(o)?;
s.pclose()?; s.pclose()?;
Ok(()) Ok(())
})?; })?;
@ -2308,7 +2294,7 @@ impl<'a> State<'a> {
ast::ExprKind::Paren(ref e) => { ast::ExprKind::Paren(ref e) => {
self.popen()?; self.popen()?;
self.print_inner_attributes_inline(attrs)?; self.print_inner_attributes_inline(attrs)?;
self.print_expr(&e)?; self.print_expr(e)?;
self.pclose()?; self.pclose()?;
}, },
ast::ExprKind::Try(ref e) => { ast::ExprKind::Try(ref e) => {
@ -2318,7 +2304,7 @@ impl<'a> State<'a> {
ast::ExprKind::Catch(ref blk) => { ast::ExprKind::Catch(ref blk) => {
self.head("do catch")?; self.head("do catch")?;
space(&mut self.s)?; space(&mut self.s)?;
self.print_block_with_attrs(&blk, attrs)? self.print_block_with_attrs(blk, attrs)?
} }
} }
self.ann.post(self, NodeExpr(expr))?; self.ann.post(self, NodeExpr(expr))?;
@ -2329,7 +2315,7 @@ impl<'a> State<'a> {
self.print_pat(&loc.pat)?; self.print_pat(&loc.pat)?;
if let Some(ref ty) = loc.ty { if let Some(ref ty) = loc.ty {
self.word_space(":")?; self.word_space(":")?;
self.print_type(&ty)?; self.print_type(ty)?;
} }
Ok(()) Ok(())
} }
@ -2397,7 +2383,7 @@ impl<'a> State<'a> {
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("as")?; self.word_space("as")?;
let depth = path.segments.len() - qself.position; let depth = path.segments.len() - qself.position;
self.print_path(&path, false, depth, false)?; self.print_path(path, false, depth, false)?;
} }
word(&mut self.s, ">")?; word(&mut self.s, ">")?;
word(&mut self.s, "::")?; word(&mut self.s, "::")?;
@ -2438,7 +2424,7 @@ impl<'a> State<'a> {
self.commasep( self.commasep(
Inconsistent, Inconsistent,
&data.types, &data.types,
|s, ty| s.print_type(&ty))?; |s, ty| s.print_type(ty))?;
comma = true; comma = true;
} }
@ -2461,13 +2447,13 @@ impl<'a> State<'a> {
self.commasep( self.commasep(
Inconsistent, Inconsistent,
&data.inputs, &data.inputs,
|s, ty| s.print_type(&ty))?; |s, ty| s.print_type(ty))?;
word(&mut self.s, ")")?; word(&mut self.s, ")")?;
if let Some(ref ty) = data.output { if let Some(ref ty) = data.output {
self.space_if_not_bol()?; self.space_if_not_bol()?;
self.word_space("->")?; self.word_space("->")?;
self.print_type(&ty)?; self.print_type(ty)?;
} }
} }
} }
@ -2496,24 +2482,24 @@ impl<'a> State<'a> {
self.print_ident(path1.node)?; self.print_ident(path1.node)?;
if let Some(ref p) = *sub { if let Some(ref p) = *sub {
word(&mut self.s, "@")?; word(&mut self.s, "@")?;
self.print_pat(&p)?; self.print_pat(p)?;
} }
} }
PatKind::TupleStruct(ref path, ref elts, ddpos) => { PatKind::TupleStruct(ref path, ref elts, ddpos) => {
self.print_path(path, true, 0, false)?; self.print_path(path, true, 0, false)?;
self.popen()?; self.popen()?;
if let Some(ddpos) = ddpos { if let Some(ddpos) = ddpos {
self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?; self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
if ddpos != 0 { if ddpos != 0 {
self.word_space(",")?; self.word_space(",")?;
} }
word(&mut self.s, "..")?; word(&mut self.s, "..")?;
if ddpos != elts.len() { if ddpos != elts.len() {
word(&mut self.s, ",")?; word(&mut self.s, ",")?;
self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?; self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
} }
} else { } else {
self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?; self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
} }
self.pclose()?; self.pclose()?;
} }
@ -2549,17 +2535,17 @@ impl<'a> State<'a> {
PatKind::Tuple(ref elts, ddpos) => { PatKind::Tuple(ref elts, ddpos) => {
self.popen()?; self.popen()?;
if let Some(ddpos) = ddpos { if let Some(ddpos) = ddpos {
self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p))?; self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
if ddpos != 0 { if ddpos != 0 {
self.word_space(",")?; self.word_space(",")?;
} }
word(&mut self.s, "..")?; word(&mut self.s, "..")?;
if ddpos != elts.len() { if ddpos != elts.len() {
word(&mut self.s, ",")?; word(&mut self.s, ",")?;
self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p))?; self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
} }
} else { } else {
self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p))?; self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
if elts.len() == 1 { if elts.len() == 1 {
word(&mut self.s, ",")?; word(&mut self.s, ",")?;
} }
@ -2568,41 +2554,41 @@ impl<'a> State<'a> {
} }
PatKind::Box(ref inner) => { PatKind::Box(ref inner) => {
word(&mut self.s, "box ")?; word(&mut self.s, "box ")?;
self.print_pat(&inner)?; self.print_pat(inner)?;
} }
PatKind::Ref(ref inner, mutbl) => { PatKind::Ref(ref inner, mutbl) => {
word(&mut self.s, "&")?; word(&mut self.s, "&")?;
if mutbl == ast::Mutability::Mutable { if mutbl == ast::Mutability::Mutable {
word(&mut self.s, "mut ")?; word(&mut self.s, "mut ")?;
} }
self.print_pat(&inner)?; self.print_pat(inner)?;
} }
PatKind::Lit(ref e) => self.print_expr(&**e)?, PatKind::Lit(ref e) => self.print_expr(&**e)?,
PatKind::Range(ref begin, ref end, ref end_kind) => { PatKind::Range(ref begin, ref end, ref end_kind) => {
self.print_expr(&begin)?; self.print_expr(begin)?;
space(&mut self.s)?; space(&mut self.s)?;
match *end_kind { match *end_kind {
RangeEnd::Included => word(&mut self.s, "...")?, RangeEnd::Included => word(&mut self.s, "...")?,
RangeEnd::Excluded => word(&mut self.s, "..")?, RangeEnd::Excluded => word(&mut self.s, "..")?,
} }
self.print_expr(&end)?; self.print_expr(end)?;
} }
PatKind::Slice(ref before, ref slice, ref after) => { PatKind::Slice(ref before, ref slice, ref after) => {
word(&mut self.s, "[")?; word(&mut self.s, "[")?;
self.commasep(Inconsistent, self.commasep(Inconsistent,
&before[..], &before[..],
|s, p| s.print_pat(&p))?; |s, p| s.print_pat(p))?;
if let Some(ref p) = *slice { if let Some(ref p) = *slice {
if !before.is_empty() { self.word_space(",")?; } if !before.is_empty() { self.word_space(",")?; }
if p.node != PatKind::Wild { if p.node != PatKind::Wild {
self.print_pat(&p)?; self.print_pat(p)?;
} }
word(&mut self.s, "..")?; word(&mut self.s, "..")?;
if !after.is_empty() { self.word_space(",")?; } if !after.is_empty() { self.word_space(",")?; }
} }
self.commasep(Inconsistent, self.commasep(Inconsistent,
&after[..], &after[..],
|s, p| s.print_pat(&p))?; |s, p| s.print_pat(p))?;
word(&mut self.s, "]")?; word(&mut self.s, "]")?;
} }
PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?, PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
@ -2628,12 +2614,12 @@ impl<'a> State<'a> {
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("|")?; self.word_space("|")?;
} }
self.print_pat(&p)?; self.print_pat(p)?;
} }
space(&mut self.s)?; space(&mut self.s)?;
if let Some(ref e) = arm.guard { if let Some(ref e) = arm.guard {
self.word_space("if")?; self.word_space("if")?;
self.print_expr(&e)?; self.print_expr(e)?;
space(&mut self.s)?; space(&mut self.s)?;
} }
self.word_space("=>")?; self.word_space("=>")?;
@ -2641,7 +2627,7 @@ impl<'a> State<'a> {
match arm.body.node { match arm.body.node {
ast::ExprKind::Block(ref blk) => { ast::ExprKind::Block(ref blk) => {
// the block will close the pattern's ibox // the block will close the pattern's ibox
self.print_block_unclosed_indent(&blk, INDENT_UNIT)?; self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
// If it is a user-provided unsafe block, print a comma after it // If it is a user-provided unsafe block, print a comma after it
if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules { if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
@ -2673,7 +2659,7 @@ impl<'a> State<'a> {
self.print_mutability(m)?; self.print_mutability(m)?;
word(&mut self.s, "self")?; word(&mut self.s, "self")?;
self.word_space(":")?; self.word_space(":")?;
self.print_type(&typ) self.print_type(typ)
} }
} }
} }
@ -2725,7 +2711,7 @@ impl<'a> State<'a> {
self.word_space("->")?; self.word_space("->")?;
match decl.output { match decl.output {
ast::FunctionRetTy::Ty(ref ty) => { ast::FunctionRetTy::Ty(ref ty) => {
self.print_type(&ty)?; self.print_type(ty)?;
self.maybe_print_comment(ty.span.lo) self.maybe_print_comment(ty.span.lo)
} }
ast::FunctionRetTy::Default(..) => unreachable!(), ast::FunctionRetTy::Default(..) => unreachable!(),
@ -2839,7 +2825,7 @@ impl<'a> State<'a> {
Some(ref default) => { Some(ref default) => {
space(&mut self.s)?; space(&mut self.s)?;
self.word_space("=")?; self.word_space("=")?;
self.print_type(&default) self.print_type(default)
} }
_ => Ok(()) _ => Ok(())
} }
@ -2865,7 +2851,7 @@ impl<'a> State<'a> {
ref bounds, ref bounds,
..}) => { ..}) => {
self.print_formal_lifetime_list(bound_lifetimes)?; self.print_formal_lifetime_list(bound_lifetimes)?;
self.print_type(&bounded_ty)?; self.print_type(bounded_ty)?;
self.print_bounds(":", bounds)?; self.print_bounds(":", bounds)?;
} }
ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime, ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
@ -2977,7 +2963,7 @@ impl<'a> State<'a> {
match decl.output { match decl.output {
ast::FunctionRetTy::Default(..) => unreachable!(), ast::FunctionRetTy::Default(..) => unreachable!(),
ast::FunctionRetTy::Ty(ref ty) => ast::FunctionRetTy::Ty(ref ty) =>
self.print_type(&ty)? self.print_type(ty)?
} }
self.end()?; self.end()?;
@ -3044,14 +3030,9 @@ impl<'a> State<'a> {
if self.next_comment().is_none() { if self.next_comment().is_none() {
hardbreak(&mut self.s)?; hardbreak(&mut self.s)?;
} }
loop { while let Some(ref cmnt) = self.next_comment() {
match self.next_comment() { self.print_comment(cmnt)?;
Some(ref cmnt) => { self.cur_cmnt_and_lit.cur_cmnt += 1;
self.print_comment(cmnt)?;
self.cur_cmnt_and_lit.cur_cmnt += 1;
}
_ => break
}
} }
Ok(()) Ok(())
} }

View file

@ -18,7 +18,7 @@ use ptr::P;
use tokenstream::TokenStream; use tokenstream::TokenStream;
/// Craft a span that will be ignored by the stability lint's /// Craft a span that will be ignored by the stability lint's
/// call to codemap's is_internal check. /// call to codemap's `is_internal` check.
/// The expanded code uses the unstable `#[prelude_import]` attribute. /// The expanded code uses the unstable `#[prelude_import]` attribute.
fn ignored_span(sp: Span) -> Span { fn ignored_span(sp: Span) -> Span {
let mark = Mark::fresh(); let mark = Mark::fresh();
@ -49,7 +49,7 @@ pub fn maybe_inject_crates_ref(mut krate: ast::Crate, alt_std_name: Option<Strin
None => return krate, None => return krate,
}; };
let crate_name = Symbol::intern(&alt_std_name.unwrap_or(name.to_string())); let crate_name = Symbol::intern(&alt_std_name.unwrap_or_else(|| name.to_string()));
krate.module.items.insert(0, P(ast::Item { krate.module.items.insert(0, P(ast::Item {
attrs: vec![attr::mk_attr_outer(DUMMY_SP, attrs: vec![attr::mk_attr_outer(DUMMY_SP,

View file

@ -106,9 +106,8 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> {
// Add a special __test module to the crate that will contain code // Add a special __test module to the crate that will contain code
// generated for the test harness // generated for the test harness
let (mod_, reexport) = mk_test_module(&mut self.cx); let (mod_, reexport) = mk_test_module(&mut self.cx);
match reexport { if let Some(re) = reexport {
Some(re) => folded.module.items.push(re), folded.module.items.push(re)
None => {}
} }
folded.module.items.push(mod_); folded.module.items.push(mod_);
folded folded
@ -257,7 +256,7 @@ fn mk_reexport_mod(cx: &mut TestCtxt,
let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent }; let parent = if parent == ast::DUMMY_NODE_ID { ast::CRATE_NODE_ID } else { parent };
cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent); cx.ext_cx.current_expansion.mark = cx.ext_cx.resolver.get_module_scope(parent);
let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item { let it = cx.ext_cx.monotonic_expander().fold_item(P(ast::Item {
ident: sym.clone(), ident: sym,
attrs: Vec::new(), attrs: Vec::new(),
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::Mod(reexport_mod), node: ast::ItemKind::Mod(reexport_mod),
@ -308,7 +307,7 @@ fn generate_test_harness(sess: &ParseSess,
} }
/// Craft a span that will be ignored by the stability lint's /// Craft a span that will be ignored by the stability lint's
/// call to codemap's is_internal check. /// call to codemap's `is_internal` check.
/// The expanded code calls some unstable functions in the test crate. /// The expanded code calls some unstable functions in the test crate.
fn ignored_span(cx: &TestCtxt, sp: Span) -> Span { fn ignored_span(cx: &TestCtxt, sp: Span) -> Span {
Span { ctxt: cx.ctxt, ..sp } Span { ctxt: cx.ctxt, ..sp }
@ -354,7 +353,7 @@ fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
} }
} }
return has_test_attr && has_test_signature(i) == Yes; has_test_attr && has_test_signature(i) == Yes
} }
fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
@ -385,7 +384,7 @@ fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool {
`fn(&mut Bencher) -> ()`"); `fn(&mut Bencher) -> ()`");
} }
return has_bench_attr && has_test_signature(i); has_bench_attr && has_test_signature(i)
} }
fn is_ignored(i: &ast::Item) -> bool { fn is_ignored(i: &ast::Item) -> bool {
@ -504,16 +503,14 @@ fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
ast::Unsafety::Normal, ast::Unsafety::Normal,
dummy_spanned(ast::Constness::NotConst), dummy_spanned(ast::Constness::NotConst),
::abi::Abi::Rust, ast::Generics::default(), main_body); ::abi::Abi::Rust, ast::Generics::default(), main_body);
let main = P(ast::Item { P(ast::Item {
ident: Ident::from_str("main"), ident: Ident::from_str("main"),
attrs: vec![main_attr], attrs: vec![main_attr],
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
node: main, node: main,
vis: ast::Visibility::Public, vis: ast::Visibility::Public,
span: sp span: sp
}); })
return main;
} }
fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) { fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {

View file

@ -10,16 +10,16 @@
//! # Token Streams //! # Token Streams
//! //!
//! TokenStreams represent syntactic objects before they are converted into ASTs. //! `TokenStream`s represent syntactic objects before they are converted into ASTs.
//! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s, //! A `TokenStream` is, roughly speaking, a sequence (eg stream) of `TokenTree`s,
//! which are themselves a single `Token` or a `Delimited` subsequence of tokens. //! which are themselves a single `Token` or a `Delimited` subsequence of tokens.
//! //!
//! ## Ownership //! ## Ownership
//! TokenStreams are persistent data structures constructed as ropes with reference //! `TokenStreams` are persistent data structures constructed as ropes with reference
//! counted-children. In general, this means that calling an operation on a TokenStream //! counted-children. In general, this means that calling an operation on a `TokenStream`
//! (such as `slice`) produces an entirely new TokenStream from the borrowed reference to //! (such as `slice`) produces an entirely new `TokenStream` from the borrowed reference to
//! the original. This essentially coerces TokenStreams into 'views' of their subparts, //! the original. This essentially coerces `TokenStream`s into 'views' of their subparts,
//! and a borrowed TokenStream is sufficient to build an owned TokenStream without taking //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking
//! ownership of the original. //! ownership of the original.
use syntax_pos::{BytePos, Span, DUMMY_SP}; use syntax_pos::{BytePos, Span, DUMMY_SP};
@ -88,7 +88,7 @@ impl Delimited {
/// If the syntax extension is an MBE macro, it will attempt to match its /// If the syntax extension is an MBE macro, it will attempt to match its
/// LHS token tree against the provided token tree, and if it finds a /// LHS token tree against the provided token tree, and if it finds a
/// match, will transcribe the RHS token tree, splicing in any captured /// match, will transcribe the RHS token tree, splicing in any captured
/// macro_parser::matched_nonterminals into the `SubstNt`s it finds. /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds.
/// ///
/// The RHS of an MBE macro is the only place `SubstNt`s are substituted. /// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
/// Nothing special happens to misnamed or misplaced `SubstNt`s. /// Nothing special happens to misnamed or misplaced `SubstNt`s.

View file

@ -53,9 +53,10 @@ pub fn find_best_match_for_name<'a, T>(iter_names: T,
iter_names iter_names
.filter_map(|&name| { .filter_map(|&name| {
let dist = lev_distance(lookup, &name.as_str()); let dist = lev_distance(lookup, &name.as_str());
match dist <= max_dist { // filter the unwanted cases if dist <= max_dist { // filter the unwanted cases
true => Some((name, dist)), Some((name, dist))
false => None, } else {
None
} }
}) })
.min_by_key(|&(_, val)| val) // extract the tuple containing the minimum edit distance .min_by_key(|&(_, val)| val) // extract the tuple containing the minimum edit distance

View file

@ -37,10 +37,10 @@ impl<T> MoveMap<T> for Vec<T> {
// move the read_i'th item out of the vector and map it // move the read_i'th item out of the vector and map it
// to an iterator // to an iterator
let e = ptr::read(self.get_unchecked(read_i)); let e = ptr::read(self.get_unchecked(read_i));
let mut iter = f(e).into_iter(); let iter = f(e).into_iter();
read_i += 1; read_i += 1;
while let Some(e) = iter.next() { for e in iter {
if write_i < read_i { if write_i < read_i {
ptr::write(self.get_unchecked_mut(write_i), e); ptr::write(self.get_unchecked_mut(write_i), e);
write_i += 1; write_i += 1;
@ -93,10 +93,10 @@ impl<T> MoveMap<T> for SmallVector<T> {
// move the read_i'th item out of the vector and map it // move the read_i'th item out of the vector and map it
// to an iterator // to an iterator
let e = ptr::read(self.get_unchecked(read_i)); let e = ptr::read(self.get_unchecked(read_i));
let mut iter = f(e).into_iter(); let iter = f(e).into_iter();
read_i += 1; read_i += 1;
while let Some(e) = iter.next() { for e in iter {
if write_i < read_i { if write_i < read_i {
ptr::write(self.get_unchecked_mut(write_i), e); ptr::write(self.get_unchecked_mut(write_i), e);
write_i += 1; write_i += 1;

View file

@ -345,9 +345,7 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) {
visitor.visit_ty(ty); visitor.visit_ty(ty);
visitor.visit_expr(expression) visitor.visit_expr(expression)
} }
TyKind::TraitObject(ref bounds) => { TyKind::TraitObject(ref bounds) |
walk_list!(visitor, visit_ty_param_bound, bounds);
}
TyKind::ImplTrait(ref bounds) => { TyKind::ImplTrait(ref bounds) => {
walk_list!(visitor, visit_ty_param_bound, bounds); walk_list!(visitor, visit_ty_param_bound, bounds);
} }
@ -542,7 +540,7 @@ pub fn walk_fn<'a, V>(visitor: &mut V, kind: FnKind<'a>, declaration: &'a FnDecl
walk_fn_decl(visitor, declaration); walk_fn_decl(visitor, declaration);
visitor.visit_block(body); visitor.visit_block(body);
} }
FnKind::Method(_, ref sig, _, body) => { FnKind::Method(_, sig, _, body) => {
visitor.visit_generics(&sig.generics); visitor.visit_generics(&sig.generics);
walk_fn_decl(visitor, declaration); walk_fn_decl(visitor, declaration);
visitor.visit_block(body); visitor.visit_block(body);
@ -778,7 +776,7 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) {
} }
ExprKind::InlineAsm(ref ia) => { ExprKind::InlineAsm(ref ia) => {
for &(_, ref input) in &ia.inputs { for &(_, ref input) in &ia.inputs {
visitor.visit_expr(&input) visitor.visit_expr(input)
} }
for output in &ia.outputs { for output in &ia.outputs {
visitor.visit_expr(&output.expr) visitor.visit_expr(&output.expr)