From 8a64cf7fb72ca93608be19e13dd83c23168b17d7 Mon Sep 17 00:00:00 2001 From: sinkuu Date: Sat, 25 Feb 2017 22:05:30 +0900 Subject: [PATCH 01/19] Fix suggestion span error with a line containing non-ASCIIs --- src/librustc_errors/lib.rs | 3 ++- src/test/ui/span/suggestion-non-ascii.rs | 16 ++++++++++++++++ src/test/ui/span/suggestion-non-ascii.stderr | 11 +++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/span/suggestion-non-ascii.rs create mode 100644 src/test/ui/span/suggestion-non-ascii.stderr diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs index d7bd5ed23c2b0..4c889dad8ca50 100644 --- a/src/librustc_errors/lib.rs +++ b/src/librustc_errors/lib.rs @@ -90,7 +90,8 @@ impl CodeSuggestion { hi_opt: Option<&Loc>) { let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize())); if let Some(line) = line_opt { - if line.len() > lo { + if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) { + let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi)); buf.push_str(match hi_opt { Some(hi) => &line[lo..hi], None => &line[lo..], diff --git a/src/test/ui/span/suggestion-non-ascii.rs b/src/test/ui/span/suggestion-non-ascii.rs new file mode 100644 index 0000000000000..67dbe1dc7b566 --- /dev/null +++ b/src/test/ui/span/suggestion-non-ascii.rs @@ -0,0 +1,16 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +fn main() { + let tup = (1,); + println!("☃{}", tup[0]); +} + diff --git a/src/test/ui/span/suggestion-non-ascii.stderr b/src/test/ui/span/suggestion-non-ascii.stderr new file mode 100644 index 0000000000000..385c211f393c6 --- /dev/null +++ b/src/test/ui/span/suggestion-non-ascii.stderr @@ -0,0 +1,11 @@ +error: cannot index a value of type `({integer},)` + --> $DIR/suggestion-non-ascii.rs:14:21 + | +14 | println!("☃{}", tup[0]); + | ^^^^^^ + | +help: to access tuple elements, use tuple indexing syntax as shown + | println!("☃{}", tup.0); + +error: aborting due to previous error + From 53d3c8939e3cf45f9e08fd360d9289e9440b6ece Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Tue, 28 Feb 2017 10:57:10 +0100 Subject: [PATCH 02/19] Dont bug! on user error --- src/librustc/infer/region_inference/graphviz.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc/infer/region_inference/graphviz.rs b/src/librustc/infer/region_inference/graphviz.rs index 95ce8d39ff488..a67049f72852b 100644 --- a/src/librustc/infer/region_inference/graphviz.rs +++ b/src/librustc/infer/region_inference/graphviz.rs @@ -91,7 +91,7 @@ pub fn maybe_print_constraints_for<'a, 'gcx, 'tcx>( }; if output_template.is_empty() { - bug!("empty string provided as RUST_REGION_GRAPH"); + panic!("empty string provided as RUST_REGION_GRAPH"); } if output_template.contains('%') { From 54a1c8b1a66ce6dd4f46fc6063612607897b2638 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Tue, 28 Feb 2017 10:59:36 +0100 Subject: [PATCH 03/19] Fix indentation in region infer docs --- src/librustc/infer/region_inference/README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/librustc/infer/region_inference/README.md b/src/librustc/infer/region_inference/README.md index 80da861139b42..4f24b37682eb5 100644 --- a/src/librustc/infer/region_inference/README.md +++ b/src/librustc/infer/region_inference/README.md @@ -122,14 +122,14 @@ every expression, block, and pattern (patterns are considered to relevant bindings). So, for example: fn foo(x: isize, y: isize) { // -+ - // +------------+ // | - // | +-----+ // | - // | +-+ +-+ +-+ // | - // | | | | | | | // | - // v v v v v v v // | - let z = x + y; // | - ... // | - } // -+ + // +------------+ // | + // | +-----+ // | + // | +-+ +-+ +-+ // | + // | | | | | | | // | + // v v v v v v v // | + let z = x + y; // | + ... // | + } // -+ fn bar() { ... } From 2a40918928818bdaa8bdc3780ce5d6449bb69f85 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Tue, 28 Feb 2017 11:17:14 +0100 Subject: [PATCH 04/19] Syntax highlighting in region infer docs --- src/librustc/infer/region_inference/README.md | 108 ++++++++++-------- 1 file changed, 59 insertions(+), 49 deletions(-) diff --git a/src/librustc/infer/region_inference/README.md b/src/librustc/infer/region_inference/README.md index 4f24b37682eb5..f5c254a459407 100644 --- a/src/librustc/infer/region_inference/README.md +++ b/src/librustc/infer/region_inference/README.md @@ -121,17 +121,19 @@ every expression, block, and pattern (patterns are considered to "execute" by testing the value they are applied to and creating any relevant bindings). So, for example: - fn foo(x: isize, y: isize) { // -+ - // +------------+ // | - // | +-----+ // | - // | +-+ +-+ +-+ // | - // | | | | | | | // | - // v v v v v v v // | - let z = x + y; // | - ... // | - } // -+ - - fn bar() { ... } +```rust +fn foo(x: isize, y: isize) { // -+ +// +------------+ // | +// | +-----+ // | +// | +-+ +-+ +-+ // | +// | | | | | | | // | +// v v v v v v v // | + let z = x + y; // | + ... // | +} // -+ + +fn bar() { ... } +``` In this example, there is a region for the fn body block as a whole, and then a subregion for the declaration of the local variable. @@ -160,7 +162,9 @@ this, we get a lot of spurious errors around nested calls, in particular when combined with `&mut` functions. For example, a call like this one - self.foo(self.bar()) +```rust +self.foo(self.bar()) +``` where both `foo` and `bar` are `&mut self` functions will always yield an error. @@ -168,20 +172,22 @@ an error. Here is a more involved example (which is safe) so we can see what's going on: - struct Foo { f: usize, g: usize } - ... - fn add(p: &mut usize, v: usize) { - *p += v; - } - ... - fn inc(p: &mut usize) -> usize { - *p += 1; *p - } - fn weird() { - let mut x: Box = box Foo { ... }; - 'a: add(&mut (*x).f, - 'b: inc(&mut (*x).f)) // (..) - } +```rust +struct Foo { f: usize, g: usize } +// ... +fn add(p: &mut usize, v: usize) { + *p += v; +} +// ... +fn inc(p: &mut usize) -> usize { + *p += 1; *p +} +fn weird() { + let mut x: Box = box Foo { ... }; + 'a: add(&mut (*x).f, + 'b: inc(&mut (*x).f)) // (..) +} +``` The important part is the line marked `(..)` which contains a call to `add()`. The first argument is a mutable borrow of the field `f`. The @@ -197,16 +203,18 @@ can see that this error is unnecessary. Let's examine the lifetimes involved with `'a` in detail. We'll break apart all the steps involved in a call expression: - 'a: { - 'a_arg1: let a_temp1: ... = add; - 'a_arg2: let a_temp2: &'a mut usize = &'a mut (*x).f; - 'a_arg3: let a_temp3: usize = { - let b_temp1: ... = inc; - let b_temp2: &'b = &'b mut (*x).f; - 'b_call: b_temp1(b_temp2) - }; - 'a_call: a_temp1(a_temp2, a_temp3) // (**) - } +```rust +'a: { + 'a_arg1: let a_temp1: ... = add; + 'a_arg2: let a_temp2: &'a mut usize = &'a mut (*x).f; + 'a_arg3: let a_temp3: usize = { + let b_temp1: ... = inc; + let b_temp2: &'b = &'b mut (*x).f; + 'b_call: b_temp1(b_temp2) + }; + 'a_call: a_temp1(a_temp2, a_temp3) // (**) +} +``` Here we see that the lifetime `'a` includes a number of substatements. In particular, there is this lifetime I've called `'a_call` that @@ -225,19 +233,21 @@ it will not be *dereferenced* during the evaluation of the second argument, it can still be *invalidated* by that evaluation. Consider this similar but unsound example: - struct Foo { f: usize, g: usize } - ... - fn add(p: &mut usize, v: usize) { - *p += v; - } - ... - fn consume(x: Box) -> usize { - x.f + x.g - } - fn weird() { - let mut x: Box = box Foo { ... }; - 'a: add(&mut (*x).f, consume(x)) // (..) - } +```rust +struct Foo { f: usize, g: usize } +// ... +fn add(p: &mut usize, v: usize) { + *p += v; +} +// ... +fn consume(x: Box) -> usize { + x.f + x.g +} +fn weird() { + let mut x: Box = box Foo { ... }; + 'a: add(&mut (*x).f, consume(x)) // (..) +} +``` In this case, the second argument to `add` actually consumes `x`, thus invalidating the first argument. From be49671df9772ee8b82a53c147f8a3cd115fd8f0 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Tue, 28 Feb 2017 11:19:48 +0100 Subject: [PATCH 05/19] Improve a bit more --- src/librustc/infer/region_inference/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc/infer/region_inference/README.md b/src/librustc/infer/region_inference/README.md index f5c254a459407..b564faf3d0c24 100644 --- a/src/librustc/infer/region_inference/README.md +++ b/src/librustc/infer/region_inference/README.md @@ -183,7 +183,7 @@ fn inc(p: &mut usize) -> usize { *p += 1; *p } fn weird() { - let mut x: Box = box Foo { ... }; + let mut x: Box = box Foo { /* ... */ }; 'a: add(&mut (*x).f, 'b: inc(&mut (*x).f)) // (..) } From 90e94d97f2635af1f976a1c6ad2f1296df05c784 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Tue, 28 Feb 2017 11:39:00 +0100 Subject: [PATCH 06/19] Syntax highlight and note about current rust in infer docs --- src/librustc/infer/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/librustc/infer/README.md b/src/librustc/infer/README.md index c835189820e51..68e64b8b7bfc8 100644 --- a/src/librustc/infer/README.md +++ b/src/librustc/infer/README.md @@ -152,7 +152,7 @@ course, it depends on the program. The main case which fails today that I would like to support is: -```text +```rust fn foo(x: T, y: T) { ... } fn bar() { @@ -168,6 +168,8 @@ because the type variable `T` is merged with the type variable for `X`, and thus inherits its UB/LB of `@mut int`. This leaves no flexibility for `T` to later adjust to accommodate `@int`. +Note: `@` and `@mut` are replaced with `Rc` and `Rc>` in current Rust. + ### What to do when not all bounds are present In the prior discussion we assumed that A.ub was not top and B.lb was From 9b317842a829b0beadca2929a14a67041213f50f Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 8 Mar 2017 16:30:31 +1300 Subject: [PATCH 07/19] save-analysis: only index path references once --- src/librustc_save_analysis/dump_visitor.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 3c275e0996dac..e8f532b0c82ea 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -1363,15 +1363,6 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, debug!("visit_expr {:?}", ex.node); self.process_macro_use(ex.span, ex.id); match ex.node { - ast::ExprKind::Call(ref _f, ref _args) => { - // Don't need to do anything for function calls, - // because just walking the callee path does what we want. - visit::walk_expr(self, ex); - } - ast::ExprKind::Path(_, ref path) => { - self.process_path(ex.id, path, None); - visit::walk_expr(self, ex); - } ast::ExprKind::Struct(ref path, ref fields, ref base) => { let hir_expr = self.save_ctxt.tcx.hir.expect_expr(ex.id); let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) { @@ -1469,6 +1460,8 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, self.visit_expr(element); self.nest_tables(count.id, |v| v.visit_expr(count)); } + // In particular, we take this branch for call and path expressions, + // where we'll index the idents involved just by continuing to walk. _ => { visit::walk_expr(self, ex) } From 0aceb99a769385ad47c15d32116e2e50c324b408 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 8 Mar 2017 18:04:30 +1300 Subject: [PATCH 08/19] save-analysis: index extern blocks --- src/librustc_save_analysis/dump_visitor.rs | 35 +++++++++++++ src/librustc_save_analysis/lib.rs | 55 +++++++++++++++++++++ src/test/run-make/save-analysis-fail/foo.rs | 5 ++ 3 files changed, 95 insertions(+) diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index e8f532b0c82ea..e764f99179a90 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -1560,4 +1560,39 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, walk_list!(self, visit_ty, &l.ty); walk_list!(self, visit_expr, &l.init); } + + fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) { + match item.node { + ast::ForeignItemKind::Fn(ref decl, ref generics) => { + if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) { + down_cast_data!(fn_data, FunctionData, item.span); + if !self.span.filter_generated(Some(fn_data.span), item.span) { + self.dumper.function(fn_data.clone().lower(self.tcx)); + } + + self.nest_tables(item.id, |v| v.process_formals(&decl.inputs, + &fn_data.qualname)); + self.process_generic_params(generics, item.span, &fn_data.qualname, item.id); + } + + for arg in &decl.inputs { + self.visit_ty(&arg.ty); + } + + if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output { + self.visit_ty(&ret_ty); + } + } + ast::ForeignItemKind::Static(ref ty, _) => { + if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) { + down_cast_data!(var_data, VariableData, item.span); + if !self.span.filter_generated(Some(var_data.span), item.span) { + self.dumper.variable(var_data.lower(self.tcx)); + } + } + + self.visit_ty(ty); + } + } + } } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index b1e435dcc751c..6be860967bf01 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -116,6 +116,46 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { result } + pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option { + let qualname = format!("::{}", self.tcx.node_path_str(item.id)); + match item.node { + ast::ForeignItemKind::Fn(ref decl, ref generics) => { + let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn); + Some(Data::FunctionData(FunctionData { + id: item.id, + name: item.ident.to_string(), + qualname: qualname, + declaration: None, + span: sub_span.unwrap(), + scope: self.enclosing_scope(item.id), + value: make_signature(decl, generics), + visibility: From::from(&item.vis), + parent: None, + docs: docs_for_attrs(&item.attrs), + sig: self.sig_base_extern(item), + })) + } + ast::ForeignItemKind::Static(ref ty, m) => { + let keyword = if m { keywords::Mut } else { keywords::Static }; + let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword); + Some(Data::VariableData(VariableData { + id: item.id, + kind: VariableKind::Static, + name: item.ident.to_string(), + qualname: qualname, + span: sub_span.unwrap(), + scope: self.enclosing_scope(item.id), + parent: None, + value: String::new(), + type_value: ty_to_string(ty), + visibility: From::from(&item.vis), + docs: docs_for_attrs(&item.attrs), + sig: Some(self.sig_base_extern(item)), + })) + } + } + } + pub fn get_item_data(&self, item: &ast::Item) -> Option { match item.node { ast::ItemKind::Fn(ref decl, .., ref generics, _) => { @@ -736,6 +776,21 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { } } + fn sig_base_extern(&self, item: &ast::ForeignItem) -> Signature { + let text = self.span_utils.signature_string_for_span(item.span); + let name = item.ident.to_string(); + let ident_start = text.find(&name).expect("Name not in signature?"); + let ident_end = ident_start + name.len(); + Signature { + span: mk_sp(item.span.lo, item.span.lo + BytePos(text.len() as u32)), + text: text, + ident_start: ident_start, + ident_end: ident_end, + defs: vec![], + refs: vec![], + } + } + #[inline] pub fn enclosing_scope(&self, id: NodeId) -> NodeId { self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID) diff --git a/src/test/run-make/save-analysis-fail/foo.rs b/src/test/run-make/save-analysis-fail/foo.rs index e331f65abb7b3..a996aa4fad5a7 100644 --- a/src/test/run-make/save-analysis-fail/foo.rs +++ b/src/test/run-make/save-analysis-fail/foo.rs @@ -448,3 +448,8 @@ fn test_format_args() { print!("{0} + {} = {}", x, y); print!("x is {}, y is {1}, name is {n}", x, y, n = name); } + +extern { + static EXTERN_FOO: u8; + fn extern_foo(a: u8, b: i32) -> String; +} From c4275c2ac376c866c93982e5513f5c6cb6d4dd98 Mon Sep 17 00:00:00 2001 From: Eduard-Mihai Burtescu Date: Wed, 8 Mar 2017 20:03:04 +0200 Subject: [PATCH 09/19] rustc_trans: don't emit ZST allocas that are only assigned to. --- src/librustc_trans/mir/analyze.rs | 3 +- src/librustc_trans/mir/mod.rs | 21 +++---------- src/librustc_trans/mir/operand.rs | 18 +++++++++++- src/librustc_trans/mir/rvalue.rs | 49 +++++++++++++++++-------------- 4 files changed, 49 insertions(+), 42 deletions(-) diff --git a/src/librustc_trans/mir/analyze.rs b/src/librustc_trans/mir/analyze.rs index 2c3b479c7dd0f..6f0f9cabef345 100644 --- a/src/librustc_trans/mir/analyze.rs +++ b/src/librustc_trans/mir/analyze.rs @@ -18,7 +18,6 @@ use rustc::mir::visit::{Visitor, LvalueContext}; use rustc::mir::traversal; use common; use super::MirContext; -use super::rvalue; pub fn lvalue_locals<'a, 'tcx>(mircx: &MirContext<'a, 'tcx>) -> BitVector { let mir = mircx.mir; @@ -92,7 +91,7 @@ impl<'mir, 'a, 'tcx> Visitor<'tcx> for LocalAnalyzer<'mir, 'a, 'tcx> { if let mir::Lvalue::Local(index) = *lvalue { self.mark_assigned(index); - if !rvalue::rvalue_creates_operand(rvalue) { + if !self.cx.rvalue_creates_operand(rvalue) { self.mark_as_lvalue(index); } } else { diff --git a/src/librustc_trans/mir/mod.rs b/src/librustc_trans/mir/mod.rs index 6419f41f86b6d..eaedabc1f54c9 100644 --- a/src/librustc_trans/mir/mod.rs +++ b/src/librustc_trans/mir/mod.rs @@ -11,20 +11,18 @@ use libc::c_uint; use llvm::{self, ValueRef, BasicBlockRef}; use llvm::debuginfo::DIScope; -use rustc::ty::{self, layout}; +use rustc::ty::{self, layout, Ty, TypeFoldable}; use rustc::mir::{self, Mir}; use rustc::mir::tcx::LvalueTy; use rustc::ty::subst::Substs; use rustc::infer::TransNormalize; -use rustc::ty::TypeFoldable; use session::config::FullDebugInfo; use base; use builder::Builder; -use common::{self, CrateContext, C_null, Funclet}; +use common::{self, CrateContext, Funclet}; use debuginfo::{self, declare_local, VariableAccess, VariableKind, FunctionDebugContext}; use monomorphize::{self, Instance}; use abi::FnType; -use type_of; use syntax_pos::{DUMMY_SP, NO_EXPANSION, COMMAND_LINE_EXPN, BytePos, Span}; use syntax::symbol::keywords; @@ -176,23 +174,12 @@ enum LocalRef<'tcx> { impl<'tcx> LocalRef<'tcx> { fn new_operand<'a>(ccx: &CrateContext<'a, 'tcx>, - ty: ty::Ty<'tcx>) -> LocalRef<'tcx> { + ty: Ty<'tcx>) -> LocalRef<'tcx> { if common::type_is_zero_size(ccx, ty) { // Zero-size temporaries aren't always initialized, which // doesn't matter because they don't contain data, but // we need something in the operand. - let llty = type_of::type_of(ccx, ty); - let val = if common::type_is_imm_pair(ccx, ty) { - let fields = llty.field_types(); - OperandValue::Pair(C_null(fields[0]), C_null(fields[1])) - } else { - OperandValue::Immediate(C_null(llty)) - }; - let op = OperandRef { - val: val, - ty: ty - }; - LocalRef::Operand(Some(op)) + LocalRef::Operand(Some(OperandRef::new_zst(ccx, ty))) } else { LocalRef::Operand(None) } diff --git a/src/librustc_trans/mir/operand.rs b/src/librustc_trans/mir/operand.rs index cb77fcbbff85d..df6667afd442e 100644 --- a/src/librustc_trans/mir/operand.rs +++ b/src/librustc_trans/mir/operand.rs @@ -15,7 +15,7 @@ use rustc::mir; use rustc_data_structures::indexed_vec::Idx; use base; -use common; +use common::{self, CrateContext, C_null}; use builder::Builder; use value::Value; use type_of; @@ -77,6 +77,22 @@ impl<'tcx> fmt::Debug for OperandRef<'tcx> { } impl<'a, 'tcx> OperandRef<'tcx> { + pub fn new_zst(ccx: &CrateContext<'a, 'tcx>, + ty: Ty<'tcx>) -> OperandRef<'tcx> { + assert!(common::type_is_zero_size(ccx, ty)); + let llty = type_of::type_of(ccx, ty); + let val = if common::type_is_imm_pair(ccx, ty) { + let fields = llty.field_types(); + OperandValue::Pair(C_null(fields[0]), C_null(fields[1])) + } else { + OperandValue::Immediate(C_null(llty)) + }; + OperandRef { + val: val, + ty: ty + } + } + /// Asserts that this operand refers to a scalar and returns /// a reference to its value. pub fn immediate(self) -> ValueRef { diff --git a/src/librustc_trans/mir/rvalue.rs b/src/librustc_trans/mir/rvalue.rs index b6af4e52e820b..4328f2516970e 100644 --- a/src/librustc_trans/mir/rvalue.rs +++ b/src/librustc_trans/mir/rvalue.rs @@ -157,7 +157,7 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } _ => { - assert!(rvalue_creates_operand(rvalue)); + assert!(self.rvalue_creates_operand(rvalue)); let (bcx, temp) = self.trans_rvalue_operand(bcx, rvalue); self.store_operand(&bcx, dest.llval, dest.alignment.to_align(), temp); bcx @@ -170,7 +170,7 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { rvalue: &mir::Rvalue<'tcx>) -> (Builder<'a, 'tcx>, OperandRef<'tcx>) { - assert!(rvalue_creates_operand(rvalue), "cannot trans {:?} to operand", rvalue); + assert!(self.rvalue_creates_operand(rvalue), "cannot trans {:?} to operand", rvalue); match *rvalue { mir::Rvalue::Cast(ref kind, ref source, cast_ty) => { @@ -478,8 +478,10 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { } mir::Rvalue::Repeat(..) | mir::Rvalue::Aggregate(..) => { - bug!("cannot generate operand from rvalue {:?}", rvalue); - + // According to `rvalue_creates_operand`, only ZST + // aggregate rvalues are allowed to be operands. + let ty = rvalue.ty(self.mir, self.ccx.tcx()); + (bcx, OperandRef::new_zst(self.ccx, self.monomorphize(&ty))) } } } @@ -662,26 +664,29 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { OperandValue::Pair(val, of) } -} -pub fn rvalue_creates_operand(rvalue: &mir::Rvalue) -> bool { - match *rvalue { - mir::Rvalue::Ref(..) | - mir::Rvalue::Len(..) | - mir::Rvalue::Cast(..) | // (*) - mir::Rvalue::BinaryOp(..) | - mir::Rvalue::CheckedBinaryOp(..) | - mir::Rvalue::UnaryOp(..) | - mir::Rvalue::Discriminant(..) | - mir::Rvalue::Box(..) | - mir::Rvalue::Use(..) => - true, - mir::Rvalue::Repeat(..) | - mir::Rvalue::Aggregate(..) => - false, - } + pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool { + match *rvalue { + mir::Rvalue::Ref(..) | + mir::Rvalue::Len(..) | + mir::Rvalue::Cast(..) | // (*) + mir::Rvalue::BinaryOp(..) | + mir::Rvalue::CheckedBinaryOp(..) | + mir::Rvalue::UnaryOp(..) | + mir::Rvalue::Discriminant(..) | + mir::Rvalue::Box(..) | + mir::Rvalue::Use(..) => + true, + mir::Rvalue::Repeat(..) | + mir::Rvalue::Aggregate(..) => { + let ty = rvalue.ty(self.mir, self.ccx.tcx()); + let ty = self.monomorphize(&ty); + common::type_is_zero_size(self.ccx, ty) + } + } - // (*) this is only true if the type is suitable + // (*) this is only true if the type is suitable + } } #[derive(Copy, Clone)] From df60044df5b531a8fc144024535d0dea43ca8b52 Mon Sep 17 00:00:00 2001 From: Eduard-Mihai Burtescu Date: Wed, 8 Mar 2017 20:08:09 +0200 Subject: [PATCH 10/19] rustc_trans: avoid a separate entry BB if START_BLOCK has no backedges. --- src/librustc_trans/mir/mod.rs | 17 ++++++----- src/test/codegen/naked-functions.rs | 47 +++++++++++++++++++++++------ 2 files changed, 47 insertions(+), 17 deletions(-) diff --git a/src/librustc_trans/mir/mod.rs b/src/librustc_trans/mir/mod.rs index eaedabc1f54c9..3bcb6e78dce9f 100644 --- a/src/librustc_trans/mir/mod.rs +++ b/src/librustc_trans/mir/mod.rs @@ -199,15 +199,17 @@ pub fn trans_mir<'a, 'tcx: 'a>( debug!("fn_ty: {:?}", fn_ty); let debug_context = debuginfo::create_function_debug_context(ccx, instance, sig, llfn, mir); - let bcx = Builder::new_block(ccx, llfn, "entry-block"); + let bcx = Builder::new_block(ccx, llfn, "start"); let cleanup_kinds = analyze::cleanup_kinds(&mir); - // Allocate a `Block` for every basic block + // Allocate a `Block` for every basic block, except + // the start block, if nothing loops back to it. + let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty(); let block_bcxs: IndexVec = mir.basic_blocks().indices().map(|bb| { - if bb == mir::START_BLOCK { - bcx.build_sibling_block("start").llbb() + if bb == mir::START_BLOCK && !reentrant_start_block { + bcx.llbb() } else { bcx.build_sibling_block(&format!("{:?}", bb)).llbb() } @@ -294,9 +296,10 @@ pub fn trans_mir<'a, 'tcx: 'a>( .collect() }; - // Branch to the START block - let start_bcx = mircx.blocks[mir::START_BLOCK]; - bcx.br(start_bcx); + // Branch to the START block, if it's not the entry block. + if reentrant_start_block { + bcx.br(mircx.blocks[mir::START_BLOCK]); + } // Up until here, IR instructions for this function have explicitly not been annotated with // source code location, so we don't step into call setup code. From here on, source location diff --git a/src/test/codegen/naked-functions.rs b/src/test/codegen/naked-functions.rs index 9de74f72005e3..9883ca6b35d04 100644 --- a/src/test/codegen/naked-functions.rs +++ b/src/test/codegen/naked-functions.rs @@ -20,7 +20,8 @@ #[no_mangle] #[naked] fn naked_empty() { - // CHECK: ret void + // CHECK-NEXT: {{.+}}: + // CHECK-NEXT: ret void } // CHECK: Function Attrs: naked uwtable @@ -28,9 +29,10 @@ fn naked_empty() { #[naked] // CHECK-NEXT: define internal void @naked_with_args(i{{[0-9]+}}) fn naked_with_args(a: isize) { - // CHECK: %a = alloca i{{[0-9]+}} - // CHECK: ret void + // CHECK-NEXT: {{.+}}: + // CHECK-NEXT: %a = alloca i{{[0-9]+}} &a; // keep variable in an alloca + // CHECK: ret void } // CHECK: Function Attrs: naked uwtable @@ -38,7 +40,8 @@ fn naked_with_args(a: isize) { #[no_mangle] #[naked] fn naked_with_return() -> isize { - // CHECK: ret i{{[0-9]+}} 0 + // CHECK-NEXT: {{.+}}: + // CHECK-NEXT: ret i{{[0-9]+}} 0 0 } @@ -47,9 +50,10 @@ fn naked_with_return() -> isize { #[no_mangle] #[naked] fn naked_with_args_and_return(a: isize) -> isize { - // CHECK: %a = alloca i{{[0-9]+}} - // CHECK: ret i{{[0-9]+}} %{{[0-9]+}} + // CHECK-NEXT: {{.+}}: + // CHECK-NEXT: %a = alloca i{{[0-9]+}} &a; // keep variable in an alloca + // CHECK: ret i{{[0-9]+}} %{{[0-9]+}} a } @@ -58,14 +62,37 @@ fn naked_with_args_and_return(a: isize) -> isize { #[no_mangle] #[naked] fn naked_recursive() { - // CHECK: call void @naked_empty() + // CHECK-NEXT: {{.+}}: + // CHECK-NEXT: call void @naked_empty() + + // FIXME(#39685) Avoid one block per call. + // CHECK-NEXT: br label %bb1 + // CHECK: bb1: + naked_empty(); - // CHECK: %{{[0-9]+}} = call i{{[0-9]+}} @naked_with_return() + + // CHECK-NEXT: %{{[0-9]+}} = call i{{[0-9]+}} @naked_with_return() + + // FIXME(#39685) Avoid one block per call. + // CHECK-NEXT: br label %bb2 + // CHECK: bb2: + + // CHECK-NEXT: %{{[0-9]+}} = call i{{[0-9]+}} @naked_with_args_and_return(i{{[0-9]+}} %{{[0-9]+}}) + + // FIXME(#39685) Avoid one block per call. + // CHECK-NEXT: br label %bb3 + // CHECK: bb3: + + // CHECK-NEXT: call void @naked_with_args(i{{[0-9]+}} %{{[0-9]+}}) + + // FIXME(#39685) Avoid one block per call. + // CHECK-NEXT: br label %bb4 + // CHECK: bb4: + naked_with_args( - // CHECK: %{{[0-9]+}} = call i{{[0-9]+}} @naked_with_args_and_return(i{{[0-9]+}} %{{[0-9]+}}) naked_with_args_and_return( - // CHECK: call void @naked_with_args(i{{[0-9]+}} %{{[0-9]+}}) naked_with_return() ) ); + // CHECK-NEXT: ret void } From 2719b8493f4e9c47067ef09000ca0d182c12ef87 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 8 Mar 2017 20:30:06 +0300 Subject: [PATCH 11/19] Give spans to individual path segments in AST --- src/librustc_resolve/lib.rs | 7 +++---- src/librustc_resolve/macros.rs | 5 ++++- src/libsyntax/ast.rs | 14 +++++++------- src/libsyntax/ext/build.rs | 19 ++++++++++++------- src/libsyntax/fold.rs | 3 ++- src/libsyntax/parse/mod.rs | 18 +++++++++++------- src/libsyntax/parse/parser.rs | 29 ++++++++++++++++++----------- src/libsyntax/std_inject.rs | 2 +- src/libsyntax/test.rs | 2 +- src/libsyntax_ext/concat_idents.rs | 2 +- 10 files changed, 60 insertions(+), 41 deletions(-) diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index d51ec268ec217..105af23d05c05 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -3124,11 +3124,10 @@ impl<'a> Resolver<'a> { if ident.name == lookup_name && ns == namespace { if filter_fn(name_binding.def()) { // create the path - let span = name_binding.span; let mut segms = path_segments.clone(); - segms.push(ident.into()); + segms.push(ast::PathSegment::from_ident(ident, name_binding.span)); let path = Path { - span: span, + span: name_binding.span, segments: segms, }; // the entity is accessible in the following cases: @@ -3148,7 +3147,7 @@ impl<'a> Resolver<'a> { if let Some(module) = name_binding.module() { // form the path let mut path_segments = path_segments.clone(); - path_segments.push(ident.into()); + path_segments.push(ast::PathSegment::from_ident(ident, name_binding.span)); if !in_module_is_extern || name_binding.vis == ty::Visibility::Public { // add the module to the lookup diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 720d616e007d2..d81bdf17034e6 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -110,8 +110,11 @@ impl<'a> base::Resolver for Resolver<'a> { path.segments[0].identifier.name = keywords::CrateRoot.name(); let module = self.0.resolve_crate_var(ident.ctxt); if !module.is_local() { + let span = path.segments[0].span; path.segments.insert(1, match module.kind { - ModuleKind::Def(_, name) => ast::Ident::with_empty_ctxt(name).into(), + ModuleKind::Def(_, name) => ast::PathSegment::from_ident( + ast::Ident::with_empty_ctxt(name), span + ), _ => unreachable!(), }) } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 9cc754cbf4d19..adb7e8d101fd1 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -134,7 +134,7 @@ impl Path { pub fn from_ident(s: Span, identifier: Ident) -> Path { Path { span: s, - segments: vec![identifier.into()], + segments: vec![PathSegment::from_ident(identifier, s)], } } @@ -159,6 +159,8 @@ impl Path { pub struct PathSegment { /// The identifier portion of this path segment. pub identifier: Ident, + /// Span of the segment identifier. + pub span: Span, /// Type/lifetime parameters attached to this path. They come in /// two flavors: `Path` and `Path(A,B) -> C`. Note that @@ -170,16 +172,14 @@ pub struct PathSegment { pub parameters: Option>, } -impl From for PathSegment { - fn from(id: Ident) -> Self { - PathSegment { identifier: id, parameters: None } - } -} - impl PathSegment { + pub fn from_ident(ident: Ident, span: Span) -> Self { + PathSegment { identifier: ident, span: span, parameters: None } + } pub fn crate_root() -> Self { PathSegment { identifier: keywords::CrateRoot.ident(), + span: DUMMY_SP, parameters: None, } } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index f8d4eff80b2d1..e0fb46ff5eb09 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -38,11 +38,11 @@ pub trait AstBuilder { fn qpath(&self, self_type: P, trait_path: ast::Path, - ident: ast::Ident) + ident: ast::SpannedIdent) -> (ast::QSelf, ast::Path); fn qpath_all(&self, self_type: P, trait_path: ast::Path, - ident: ast::Ident, + ident: ast::SpannedIdent, lifetimes: Vec, types: Vec>, bindings: Vec) @@ -323,7 +323,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { segments.push(ast::PathSegment::crate_root()); } - segments.extend(idents.into_iter().map(Into::into)); + segments.extend(idents.into_iter().map(|i| ast::PathSegment::from_ident(i, sp))); let parameters = if lifetimes.is_empty() && types.is_empty() && bindings.is_empty() { None } else { @@ -333,7 +333,11 @@ impl<'a> AstBuilder for ExtCtxt<'a> { bindings: bindings, }))) }; - segments.push(ast::PathSegment { identifier: last_identifier, parameters: parameters }); + segments.push(ast::PathSegment { + identifier: last_identifier, + span: sp, + parameters: parameters + }); ast::Path { span: sp, segments: segments, @@ -346,7 +350,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn qpath(&self, self_type: P, trait_path: ast::Path, - ident: ast::Ident) + ident: ast::SpannedIdent) -> (ast::QSelf, ast::Path) { self.qpath_all(self_type, trait_path, ident, vec![], vec![], vec![]) } @@ -357,7 +361,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn qpath_all(&self, self_type: P, trait_path: ast::Path, - ident: ast::Ident, + ident: ast::SpannedIdent, lifetimes: Vec, types: Vec>, bindings: Vec) @@ -369,7 +373,8 @@ impl<'a> AstBuilder for ExtCtxt<'a> { bindings: bindings, }; path.segments.push(ast::PathSegment { - identifier: ident, + identifier: ident.node, + span: ident.span, parameters: Some(P(ast::PathParameters::AngleBracketed(parameters))), }); diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 4242b0f8b9803..665f48ab45679 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -434,8 +434,9 @@ pub fn noop_fold_usize(i: usize, _: &mut T) -> usize { pub fn noop_fold_path(Path { segments, span }: Path, fld: &mut T) -> Path { Path { - segments: segments.move_map(|PathSegment {identifier, parameters}| PathSegment { + segments: segments.move_map(|PathSegment {identifier, span, parameters}| PathSegment { identifier: fld.fold_ident(identifier), + span: fld.new_span(span), parameters: parameters.map(|ps| ps.map(|ps| fld.fold_path_parameters(ps))), }), span: fld.new_span(span) diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index c00d2952b3b42..88535f91379f7 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -617,13 +617,17 @@ mod tests { Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION} } + fn str2seg(s: &str, lo: u32, hi: u32) -> ast::PathSegment { + ast::PathSegment::from_ident(Ident::from_str(s), sp(lo, hi)) + } + #[test] fn path_exprs_1() { assert!(string_to_expr("a".to_string()) == P(ast::Expr{ id: ast::DUMMY_NODE_ID, node: ast::ExprKind::Path(None, ast::Path { span: sp(0, 1), - segments: vec![Ident::from_str("a").into()], + segments: vec![str2seg("a", 0, 1)], }), span: sp(0, 1), attrs: ThinVec::new(), @@ -637,8 +641,8 @@ mod tests { node: ast::ExprKind::Path(None, ast::Path { span: sp(0, 6), segments: vec![ast::PathSegment::crate_root(), - Ident::from_str("a").into(), - Ident::from_str("b").into()] + str2seg("a", 2, 3), + str2seg("b", 5, 6)] }), span: sp(0, 6), attrs: ThinVec::new(), @@ -744,7 +748,7 @@ mod tests { id: ast::DUMMY_NODE_ID, node:ast::ExprKind::Path(None, ast::Path{ span: sp(7, 8), - segments: vec![Ident::from_str("d").into()], + segments: vec![str2seg("d", 7, 8)], }), span:sp(7,8), attrs: ThinVec::new(), @@ -761,7 +765,7 @@ mod tests { id: ast::DUMMY_NODE_ID, node: ast::ExprKind::Path(None, ast::Path { span:sp(0,1), - segments: vec![Ident::from_str("b").into()], + segments: vec![str2seg("b", 0, 1)], }), span: sp(0,1), attrs: ThinVec::new()})), @@ -802,7 +806,7 @@ mod tests { ty: P(ast::Ty{id: ast::DUMMY_NODE_ID, node: ast::TyKind::Path(None, ast::Path{ span:sp(10,13), - segments: vec![Ident::from_str("i32").into()], + segments: vec![str2seg("i32", 10, 13)], }), span:sp(10,13) }), @@ -844,7 +848,7 @@ mod tests { node: ast::ExprKind::Path(None, ast::Path{ span:sp(17,18), - segments: vec![Ident::from_str("b").into()], + segments: vec![str2seg("b", 17, 18)], }), span: sp(17,18), attrs: ThinVec::new()})), diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 6c566dab1d606..002f1359b6fa5 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -27,7 +27,7 @@ use ast::Local; use ast::MacStmtStyle; use ast::Mac_; use ast::{MutTy, Mutability}; -use ast::{Pat, PatKind}; +use ast::{Pat, PatKind, PathSegment}; use ast::{PolyTraitRef, QSelf}; use ast::{Stmt, StmtKind}; use ast::{VariantData, StructField}; @@ -1811,7 +1811,7 @@ impl<'a> Parser<'a> { }; if is_global { - segments.insert(0, ast::PathSegment::crate_root()); + segments.insert(0, PathSegment::crate_root()); } // Assemble the span. @@ -1829,11 +1829,12 @@ impl<'a> Parser<'a> { /// - `a::b::c` /// - `a::b::c(V) -> W` /// - `a::b::c(V)` - pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec> { + pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec> { let mut segments = Vec::new(); loop { // First, parse an identifier. let identifier = self.parse_path_segment_ident()?; + let ident_span = self.prev_span; if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) { self.bump(); @@ -1881,7 +1882,11 @@ impl<'a> Parser<'a> { }; // Assemble and push the result. - segments.push(ast::PathSegment { identifier: identifier, parameters: parameters }); + segments.push(PathSegment { + identifier: identifier, + span: ident_span, + parameters: parameters + }); // Continue only if we see a `::` if !self.eat(&token::ModSep) { @@ -1892,15 +1897,16 @@ impl<'a> Parser<'a> { /// Examples: /// - `a::b::::c` - pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec> { + pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec> { let mut segments = Vec::new(); loop { // First, parse an identifier. let identifier = self.parse_path_segment_ident()?; + let ident_span = self.prev_span; // If we do not see a `::`, stop. if !self.eat(&token::ModSep) { - segments.push(identifier.into()); + segments.push(PathSegment::from_ident(identifier, ident_span)); return Ok(segments); } @@ -1909,8 +1915,9 @@ impl<'a> Parser<'a> { // Consumed `a::b::<`, go look for types let (lifetimes, types, bindings) = self.parse_generic_args()?; self.expect_gt()?; - segments.push(ast::PathSegment { + segments.push(PathSegment { identifier: identifier, + span: ident_span, parameters: ast::AngleBracketedParameterData { lifetimes: lifetimes, types: types, @@ -1924,7 +1931,7 @@ impl<'a> Parser<'a> { } } else { // Consumed `a::`, go look for `b` - segments.push(identifier.into()); + segments.push(PathSegment::from_ident(identifier, ident_span)); } } } @@ -1932,14 +1939,14 @@ impl<'a> Parser<'a> { /// Examples: /// - `a::b::c` pub fn parse_path_segments_without_types(&mut self) - -> PResult<'a, Vec> { + -> PResult<'a, Vec> { let mut segments = Vec::new(); loop { // First, parse an identifier. let identifier = self.parse_path_segment_ident()?; // Assemble and push the result. - segments.push(identifier.into()); + segments.push(PathSegment::from_ident(identifier, self.prev_span)); // If we do not see a `::` or see `::{`/`::*`, stop. if !self.check(&token::ModSep) || self.is_import_coupler() { @@ -5902,7 +5909,7 @@ impl<'a> Parser<'a> { // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`. self.eat(&token::ModSep); let prefix = ast::Path { - segments: vec![ast::PathSegment::crate_root()], + segments: vec![PathSegment::crate_root()], span: mk_sp(lo, self.span.hi), }; let view_path_kind = if self.eat(&token::BinOp(token::Star)) { diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 4a2dfaf61247c..2192d203cdc23 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -82,7 +82,7 @@ pub fn maybe_inject_crates_ref(sess: &ParseSess, vis: ast::Visibility::Inherited, node: ast::ItemKind::Use(P(codemap::dummy_spanned(ast::ViewPathGlob(ast::Path { segments: ["{{root}}", name, "prelude", "v1"].into_iter().map(|name| { - ast::Ident::from_str(name).into() + ast::PathSegment::from_ident(ast::Ident::from_str(name), DUMMY_SP) }).collect(), span: span, })))), diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index dd2756cd2b22c..e052d2cda3a42 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -580,7 +580,7 @@ fn nospan(t: T) -> codemap::Spanned { fn path_node(ids: Vec) -> ast::Path { ast::Path { span: DUMMY_SP, - segments: ids.into_iter().map(Into::into).collect(), + segments: ids.into_iter().map(|id| ast::PathSegment::from_ident(id, DUMMY_SP)).collect(), } } diff --git a/src/libsyntax_ext/concat_idents.rs b/src/libsyntax_ext/concat_idents.rs index 1fc1bdff593c2..dc4b8eb24cd0a 100644 --- a/src/libsyntax_ext/concat_idents.rs +++ b/src/libsyntax_ext/concat_idents.rs @@ -61,7 +61,7 @@ pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, fn path(&self) -> ast::Path { ast::Path { span: self.span, - segments: vec![self.ident.into()], + segments: vec![ast::PathSegment::from_ident(self.ident, self.span)], } } } From 7cfe20c676e3f17a065a24cc7da8647c135cc70e Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Wed, 8 Mar 2017 22:15:12 +0300 Subject: [PATCH 12/19] resolve: Use path segment spans in smart_resolve_path --- src/librustc_resolve/lib.rs | 50 +++++++++---------- src/librustc_resolve/macros.rs | 1 - .../ui/resolve/enums-are-namespaced-xc.stderr | 12 ++--- src/test/ui/resolve/levenshtein.stderr | 10 ++-- ...uggest-path-instead-of-mod-dot-item.stderr | 36 +++++++++---- ...xed-closure-sugar-nonexistent-trait.stderr | 2 +- 6 files changed, 64 insertions(+), 47 deletions(-) diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 105af23d05c05..99061747832ec 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -407,7 +407,7 @@ enum PathSource<'a> { // Trait paths in bounds or impls. Trait, // Expression paths `path`, with optional parent context. - Expr(Option<&'a ExprKind>), + Expr(Option<&'a Expr>), // Paths in path patterns `Path`. Pat, // Paths in struct expressions and patterns `Path { .. }`. @@ -464,7 +464,7 @@ impl<'a> PathSource<'a> { ValueNS => "method or associated constant", MacroNS => bug!("associated macro"), }, - PathSource::Expr(parent) => match parent { + PathSource::Expr(parent) => match parent.map(|p| &p.node) { // "function" here means "anything callable" rather than `Def::Fn`, // this is not precise but usually more helpful than just "value". Some(&ExprKind::Call(..)) => "function", @@ -2194,7 +2194,8 @@ impl<'a> Resolver<'a> { source: PathSource) -> PathResolution { let segments = &path.segments.iter().map(|seg| seg.identifier).collect::>(); - self.smart_resolve_path_fragment(id, qself, segments, path.span, source) + let ident_span = path.segments.last().map_or(path.span, |seg| seg.span); + self.smart_resolve_path_fragment(id, qself, segments, path.span, ident_span, source) } fn smart_resolve_path_fragment(&mut self, @@ -2202,6 +2203,7 @@ impl<'a> Resolver<'a> { qself: Option<&QSelf>, path: &[Ident], span: Span, + ident_span: Span, source: PathSource) -> PathResolution { let ns = source.namespace(); @@ -2213,9 +2215,9 @@ impl<'a> Resolver<'a> { let expected = source.descr_expected(); let path_str = names_to_string(path); let code = source.error_code(def.is_some()); - let (base_msg, fallback_label) = if let Some(def) = def { + let (base_msg, fallback_label, base_span) = if let Some(def) = def { (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str), - format!("not a {}", expected)) + format!("not a {}", expected), span) } else { let item_str = path[path.len() - 1]; let (mod_prefix, mod_str) = if path.len() == 1 { @@ -2231,9 +2233,9 @@ impl<'a> Resolver<'a> { (mod_prefix, format!("`{}`", names_to_string(mod_path))) }; (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str), - format!("not found in {}", mod_str)) + format!("not found in {}", mod_str), ident_span) }; - let mut err = this.session.struct_span_err_with_code(span, &base_msg, code); + let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code); // Emit special messages for unresolved `Self` and `self`. if is_self_type(path, ns) { @@ -2291,15 +2293,15 @@ impl<'a> Resolver<'a> { err.span_label(span, &format!("type aliases cannot be used for traits")); return err; } - (Def::Mod(..), PathSource::Expr(Some(parent))) => match *parent { + (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node { ExprKind::Field(_, ident) => { - err.span_label(span, &format!("did you mean `{}::{}`?", - path_str, ident.node)); + err.span_label(parent.span, &format!("did you mean `{}::{}`?", + path_str, ident.node)); return err; } ExprKind::MethodCall(ident, ..) => { - err.span_label(span, &format!("did you mean `{}::{}(...)`?", - path_str, ident.node)); + err.span_label(parent.span, &format!("did you mean `{}::{}(...)`?", + path_str, ident.node)); return err; } _ => {} @@ -2324,12 +2326,12 @@ impl<'a> Resolver<'a> { // Try Levenshtein if nothing else worked. if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected) { - err.span_label(span, &format!("did you mean `{}`?", candidate)); + err.span_label(ident_span, &format!("did you mean `{}`?", candidate)); return err; } // Fallback label. - err.span_label(span, &fallback_label); + err.span_label(base_span, &fallback_label); err }; let report_errors = |this: &mut Self, def: Option| { @@ -2449,7 +2451,7 @@ impl<'a> Resolver<'a> { // Make sure `A::B` in `::B::C` is a trait item. let ns = if qself.position + 1 == path.len() { ns } else { TypeNS }; let res = self.smart_resolve_path_fragment(id, None, &path[..qself.position + 1], - span, PathSource::TraitItem(ns)); + span, span, PathSource::TraitItem(ns)); return Some(PathResolution::with_unresolved_segments( res.base_def(), res.unresolved_segments() + path.len() - qself.position - 1 )); @@ -2807,7 +2809,7 @@ impl<'a> Resolver<'a> { path: &[Ident], ns: Namespace, filter_fn: FilterFn) - -> Option + -> Option where FilterFn: Fn(Def) -> bool { let add_module_candidates = |module: Module, names: &mut Vec| { @@ -2821,7 +2823,7 @@ impl<'a> Resolver<'a> { }; let mut names = Vec::new(); - let prefix_str = if path.len() == 1 { + if path.len() == 1 { // Search in lexical scope. // Walk backwards up the ribs in scope and collect candidates. for rib in self.ribs[ns].iter().rev() { @@ -2855,21 +2857,19 @@ impl<'a> Resolver<'a> { names.push(*name); } } - String::new() } else { // Search in module. let mod_path = &path[..path.len() - 1]; if let PathResult::Module(module) = self.resolve_path(mod_path, Some(TypeNS), None) { add_module_candidates(module, &mut names); } - names_to_string(mod_path) + "::" - }; + } let name = path[path.len() - 1].name; // Make sure error reporting is deterministic. names.sort_by_key(|name| name.as_str()); match find_best_match_for_name(names.iter(), &name.as_str(), None) { - Some(found) if found != name => Some(format!("{}{}", prefix_str, found)), + Some(found) if found != name => Some(found), _ => None, } } @@ -2892,7 +2892,7 @@ impl<'a> Resolver<'a> { self.with_resolved_label(label, id, |this| this.visit_block(block)); } - fn resolve_expr(&mut self, expr: &Expr, parent: Option<&ExprKind>) { + fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) { // First, record candidate traits for this expression if it could // result in the invocation of a method call. @@ -2973,11 +2973,11 @@ impl<'a> Resolver<'a> { // Equivalent to `visit::walk_expr` + passing some context to children. ExprKind::Field(ref subexpression, _) => { - self.resolve_expr(subexpression, Some(&expr.node)); + self.resolve_expr(subexpression, Some(expr)); } ExprKind::MethodCall(_, ref types, ref arguments) => { let mut arguments = arguments.iter(); - self.resolve_expr(arguments.next().unwrap(), Some(&expr.node)); + self.resolve_expr(arguments.next().unwrap(), Some(expr)); for argument in arguments { self.resolve_expr(argument, None); } @@ -2993,7 +2993,7 @@ impl<'a> Resolver<'a> { }); } ExprKind::Call(ref callee, ref arguments) => { - self.resolve_expr(callee, Some(&expr.node)); + self.resolve_expr(callee, Some(expr)); for argument in arguments { self.resolve_expr(argument, None); } diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index d81bdf17034e6..9d4779a06baf6 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -502,7 +502,6 @@ impl<'a> Resolver<'a> { }; let ident = Ident::from_str(name); self.lookup_typo_candidate(&vec![ident], MacroNS, is_macro) - .as_ref().map(|s| Symbol::intern(s)) }); if let Some(suggestion) = suggestion { diff --git a/src/test/ui/resolve/enums-are-namespaced-xc.stderr b/src/test/ui/resolve/enums-are-namespaced-xc.stderr index d541aa599a48b..dd04c5ce356c6 100644 --- a/src/test/ui/resolve/enums-are-namespaced-xc.stderr +++ b/src/test/ui/resolve/enums-are-namespaced-xc.stderr @@ -1,26 +1,26 @@ error[E0425]: cannot find value `A` in module `namespaced_enums` - --> $DIR/enums-are-namespaced-xc.rs:15:13 + --> $DIR/enums-are-namespaced-xc.rs:15:31 | 15 | let _ = namespaced_enums::A; - | ^^^^^^^^^^^^^^^^^^^ not found in `namespaced_enums` + | ^ not found in `namespaced_enums` | = help: possible candidate is found in another module, you can import it into scope: `use namespaced_enums::Foo::A;` error[E0425]: cannot find function `B` in module `namespaced_enums` - --> $DIR/enums-are-namespaced-xc.rs:18:13 + --> $DIR/enums-are-namespaced-xc.rs:18:31 | 18 | let _ = namespaced_enums::B(10); - | ^^^^^^^^^^^^^^^^^^^ not found in `namespaced_enums` + | ^ not found in `namespaced_enums` | = help: possible candidate is found in another module, you can import it into scope: `use namespaced_enums::Foo::B;` error[E0422]: cannot find struct, variant or union type `C` in module `namespaced_enums` - --> $DIR/enums-are-namespaced-xc.rs:21:13 + --> $DIR/enums-are-namespaced-xc.rs:21:31 | 21 | let _ = namespaced_enums::C { a: 10 }; - | ^^^^^^^^^^^^^^^^^^^ not found in `namespaced_enums` + | ^ not found in `namespaced_enums` | = help: possible candidate is found in another module, you can import it into scope: `use namespaced_enums::Foo::C;` diff --git a/src/test/ui/resolve/levenshtein.stderr b/src/test/ui/resolve/levenshtein.stderr index c7c42bcf23940..4dff2620319e4 100644 --- a/src/test/ui/resolve/levenshtein.stderr +++ b/src/test/ui/resolve/levenshtein.stderr @@ -14,7 +14,7 @@ error[E0412]: cannot find type `Opiton` in this scope --> $DIR/levenshtein.rs:20:10 | 20 | type B = Opiton; // Misspelled type name from the prelude. - | ^^^^^^^^^^ did you mean `Option`? + | ^^^^^^ did you mean `Option`? error[E0412]: cannot find type `Baz` in this scope --> $DIR/levenshtein.rs:23:14 @@ -35,16 +35,16 @@ error[E0425]: cannot find function `foobar` in this scope | ^^^^^^ did you mean `foo_bar`? error[E0412]: cannot find type `first` in module `m` - --> $DIR/levenshtein.rs:32:12 + --> $DIR/levenshtein.rs:32:15 | 32 | let b: m::first = m::second; // Misspelled item in module. - | ^^^^^^^^ did you mean `m::First`? + | ^^^^^ did you mean `First`? error[E0425]: cannot find value `second` in module `m` - --> $DIR/levenshtein.rs:32:23 + --> $DIR/levenshtein.rs:32:26 | 32 | let b: m::first = m::second; // Misspelled item in module. - | ^^^^^^^^^ did you mean `m::Second`? + | ^^^^^^ did you mean `Second`? error: aborting due to 8 previous errors diff --git a/src/test/ui/resolve/suggest-path-instead-of-mod-dot-item.stderr b/src/test/ui/resolve/suggest-path-instead-of-mod-dot-item.stderr index 57c0ecc813505..85fb1777dea23 100644 --- a/src/test/ui/resolve/suggest-path-instead-of-mod-dot-item.stderr +++ b/src/test/ui/resolve/suggest-path-instead-of-mod-dot-item.stderr @@ -2,55 +2,73 @@ error[E0423]: expected value, found module `a` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:27:5 | 27 | a.I - | ^ did you mean `a::I`? + | ^-- + | | + | did you mean `a::I`? error[E0423]: expected value, found module `a` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:33:5 | 33 | a.g() - | ^ did you mean `a::g(...)`? + | ^---- + | | + | did you mean `a::g(...)`? error[E0423]: expected value, found module `a` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:39:5 | 39 | a.b.J - | ^ did you mean `a::b`? + | ^-- + | | + | did you mean `a::b`? error[E0423]: expected value, found module `a::b` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:45:5 | 45 | a::b.J - | ^^^^ did you mean `a::b::J`? + | ^^^^-- + | | + | did you mean `a::b::J`? error[E0423]: expected value, found module `a` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:51:5 | 51 | a.b.f(); - | ^ did you mean `a::b`? + | ^-- + | | + | did you mean `a::b`? error[E0423]: expected value, found module `a::b` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:55:12 | 55 | v.push(a::b); - | ^^^^ did you mean `a::I`? + | ^^^- + | | + | did you mean `I`? error[E0423]: expected value, found module `a::b` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:61:5 | 61 | a::b.f() - | ^^^^ did you mean `a::b::f(...)`? + | ^^^^---- + | | + | did you mean `a::b::f(...)`? error[E0423]: expected value, found module `a::b` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:67:5 | 67 | a::b - | ^^^^ did you mean `a::I`? + | ^^^- + | | + | did you mean `I`? error[E0423]: expected function, found module `a::b` --> $DIR/suggest-path-instead-of-mod-dot-item.rs:73:5 | 73 | a::b() - | ^^^^ did you mean `a::I`? + | ^^^- + | | + | did you mean `I`? error: main function not found diff --git a/src/test/ui/resolve/unboxed-closure-sugar-nonexistent-trait.stderr b/src/test/ui/resolve/unboxed-closure-sugar-nonexistent-trait.stderr index f0d363f7335f7..015dbfc3dc775 100644 --- a/src/test/ui/resolve/unboxed-closure-sugar-nonexistent-trait.stderr +++ b/src/test/ui/resolve/unboxed-closure-sugar-nonexistent-trait.stderr @@ -2,7 +2,7 @@ error[E0405]: cannot find trait `Nonexist` in this scope --> $DIR/unboxed-closure-sugar-nonexistent-trait.rs:11:8 | 11 | fn f isize>(x: F) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope + | ^^^^^^^^ not found in this scope error[E0404]: expected trait, found type alias `Typedef` --> $DIR/unboxed-closure-sugar-nonexistent-trait.rs:17:8 From 79a7ee8d831d7bacc4d52cd76bbc0dcd15fddfe5 Mon Sep 17 00:00:00 2001 From: Tim Neumann Date: Wed, 8 Mar 2017 21:17:55 +0100 Subject: [PATCH 13/19] fix UB in repr(packed) tests --- .../extern-fn-with-packed-struct/test.rs | 24 ++++++++++++++++++- src/test/run-pass/packed-struct-vec.rs | 21 +++++++++++++++- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/test/run-make/extern-fn-with-packed-struct/test.rs b/src/test/run-make/extern-fn-with-packed-struct/test.rs index c0f55893a3abe..9e81636e36703 100644 --- a/src/test/run-make/extern-fn-with-packed-struct/test.rs +++ b/src/test/run-make/extern-fn-with-packed-struct/test.rs @@ -8,14 +8,36 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; + #[repr(packed)] -#[derive(Copy, Clone, PartialEq, Debug)] +#[derive(Copy, Clone)] struct Foo { a: i8, b: i16, c: i8 } +impl PartialEq for Foo { + fn eq(&self, other: &Foo) -> bool { + self.a == other.a && self.b == other.b && self.c == other.c + } +} + +impl fmt::Debug for Foo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let a = self.a; + let b = self.b; + let c = self.c; + + f.debug_struct("Foo") + .field("a", &a) + .field("b", &b) + .field("c", &c) + .finish() + } +} + #[link(name = "test", kind = "static")] extern { fn foo(f: Foo) -> Foo; diff --git a/src/test/run-pass/packed-struct-vec.rs b/src/test/run-pass/packed-struct-vec.rs index 4b32b881be738..57407b8422371 100644 --- a/src/test/run-pass/packed-struct-vec.rs +++ b/src/test/run-pass/packed-struct-vec.rs @@ -8,15 +8,34 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; use std::mem; #[repr(packed)] -#[derive(Copy, Clone, PartialEq, Debug)] +#[derive(Copy, Clone)] struct Foo { bar: u8, baz: u64 } +impl PartialEq for Foo { + fn eq(&self, other: &Foo) -> bool { + self.bar == other.bar && self.baz == other.baz + } +} + +impl fmt::Debug for Foo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let bar = self.bar; + let baz = self.baz; + + f.debug_struct("Foo") + .field("bar", &bar) + .field("baz", &baz) + .finish() + } +} + pub fn main() { let foos = [Foo { bar: 1, baz: 2 }; 10]; From c51a39de7c8cb8e138f07d1e0f4798068cad251d Mon Sep 17 00:00:00 2001 From: Joshua Horwitz Date: Tue, 7 Mar 2017 23:04:59 -0500 Subject: [PATCH 14/19] Removed RustFMT changes --- src/libstd/process.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/libstd/process.rs b/src/libstd/process.rs index f846ef3e69e09..e5ce30c5539fc 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -343,6 +343,23 @@ impl Command { /// Add an argument to pass to the program. /// + /// Only one argument can be passed per use. So instead of: + /// + /// ```ignore + /// .arg("-C /path/to/repo") + /// ``` + /// + /// usage would be: + /// + /// ```ignore + /// .arg("-C") + /// .arg("/path/to/repo") + /// ``` + /// + /// To pass multiple arguments see [`args`]. + /// + /// [`args`]: #method.args + /// /// # Examples /// /// Basic usage: @@ -364,6 +381,10 @@ impl Command { /// Add multiple arguments to pass to the program. /// + /// To pass a single argument see [`arg`]. + /// + /// [`arg`]: #method.arg + /// /// # Examples /// /// Basic usage: From edf5dc66c1ec243bb2a60385b094cde719c0a492 Mon Sep 17 00:00:00 2001 From: Clar Charr Date: Wed, 8 Mar 2017 21:53:28 -0500 Subject: [PATCH 15/19] Box docs: no allocation is done for ZSTs. --- src/liballoc/boxed.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index d0fce70612868..43b0d72186a29 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -225,6 +225,8 @@ impl Drop for IntermediateBox { impl Box { /// Allocates memory on the heap and then places `x` into it. /// + /// This doesn't actually allocate if `T` is zero-sized. + /// /// # Examples /// /// ``` From 14e9313ece743d866889215ec954013e6f310bd1 Mon Sep 17 00:00:00 2001 From: Ariel Ben-Yehuda Date: Thu, 9 Mar 2017 13:28:26 +0200 Subject: [PATCH 16/19] emit !align attributes on stores of operand pairs cc #40373 --- src/librustc_trans/mir/block.rs | 17 ++++++++++++++-- src/librustc_trans/mir/operand.rs | 11 +++++++++-- src/test/codegen/packed.rs | 33 +++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/librustc_trans/mir/block.rs b/src/librustc_trans/mir/block.rs index 34d8c6500b926..9d40419d338b8 100644 --- a/src/librustc_trans/mir/block.rs +++ b/src/librustc_trans/mir/block.rs @@ -833,8 +833,21 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { self.trans_lvalue(bcx, dest) }; if fn_ret_ty.is_indirect() { - llargs.push(dest.llval); - ReturnDest::Nothing + match dest.alignment { + Alignment::AbiAligned => { + llargs.push(dest.llval); + ReturnDest::Nothing + }, + Alignment::Packed => { + // Currently, MIR code generation does not create calls + // that store directly to fields of packed structs (in + // fact, the calls it creates write only to temps), + // + // If someone changes that, please update this code path + // to create a temporary. + span_bug!(self.mir.span, "can't directly store to unaligned value"); + } + } } else { ReturnDest::Store(dest.llval) } diff --git a/src/librustc_trans/mir/operand.rs b/src/librustc_trans/mir/operand.rs index cb77fcbbff85d..3f29545ecf45a 100644 --- a/src/librustc_trans/mir/operand.rs +++ b/src/librustc_trans/mir/operand.rs @@ -268,10 +268,17 @@ impl<'a, 'tcx> MirContext<'a, 'tcx> { bcx.store(base::from_immediate(bcx, s), lldest, align); } OperandValue::Pair(a, b) => { + let f_align = match *bcx.ccx.layout_of(operand.ty) { + Layout::Univariant { ref variant, .. } if variant.packed => { + Some(1) + } + _ => align + }; + let a = base::from_immediate(bcx, a); let b = base::from_immediate(bcx, b); - bcx.store(a, bcx.struct_gep(lldest, 0), align); - bcx.store(b, bcx.struct_gep(lldest, 1), align); + bcx.store(a, bcx.struct_gep(lldest, 0), f_align); + bcx.store(b, bcx.struct_gep(lldest, 1), f_align); } } } diff --git a/src/test/codegen/packed.rs b/src/test/codegen/packed.rs index db2cd3b41656d..4bd471d05c711 100644 --- a/src/test/codegen/packed.rs +++ b/src/test/codegen/packed.rs @@ -27,3 +27,36 @@ pub fn write_pkd(pkd: &mut Packed) -> u32 { pkd.data = 42; result } + +pub struct Array([i32; 8]); +#[repr(packed)] +pub struct BigPacked { + dealign: u8, + data: Array +} + +// CHECK-LABEL: @call_pkd +#[no_mangle] +pub fn call_pkd(f: fn() -> Array) -> BigPacked { +// CHECK: [[ALLOCA:%[_a-z0-9]+]] = alloca %Array +// CHECK: call void %{{.*}}(%Array* noalias nocapture sret dereferenceable(32) [[ALLOCA]]) +// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 32, i32 1, i1 false) + // check that calls whose destination is a field of a packed struct + // go through an alloca rather than calling the function with an + // unaligned destination. + BigPacked { dealign: 0, data: f() } +} + +#[repr(packed)] +#[derive(Copy, Clone)] +pub struct PackedPair(u8, u32); + +// CHECK-LABEL: @pkd_pair +#[no_mangle] +pub fn pkd_pair(pair1: &mut PackedPair, pair2: &mut PackedPair) { + // CHECK: [[V1:%[a-z0-9]+]] = load i8, i8* %{{.*}}, align 1 + // CHECK: [[V2:%[a-z0-9]+]] = load i32, i32* %{{.*}}, align 1 + // CHECK: store i8 [[V1]], i8* {{.*}}, align 1 + // CHECK: store i32 [[V2]], i32* {{.*}}, align 1 + *pair2 = *pair1; +} From 8062cfb37294082ad5825a105e47e0b7b50a7269 Mon Sep 17 00:00:00 2001 From: Charlie Fan Date: Thu, 9 Mar 2017 07:50:48 +0000 Subject: [PATCH 17/19] Implement placement-in protocol for and `VecDeque` --- src/libcollections/vec_deque.rs | 185 ++++++++++++++++++++++++---- src/libcollectionstest/lib.rs | 1 + src/libcollectionstest/vec_deque.rs | 24 +++- 3 files changed, 184 insertions(+), 26 deletions(-) diff --git a/src/libcollections/vec_deque.rs b/src/libcollections/vec_deque.rs index 8d42045ff1637..24f57c506304c 100644 --- a/src/libcollections/vec_deque.rs +++ b/src/libcollections/vec_deque.rs @@ -22,7 +22,7 @@ use core::cmp::Ordering; use core::fmt; use core::iter::{repeat, FromIterator, FusedIterator}; use core::mem; -use core::ops::{Index, IndexMut}; +use core::ops::{Index, IndexMut, Place, Placer, InPlace}; use core::ptr; use core::ptr::Shared; use core::slice; @@ -1087,14 +1087,7 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn push_front(&mut self, value: T) { - if self.is_full() { - let old_cap = self.cap(); - self.buf.double(); - unsafe { - self.handle_cap_increase(old_cap); - } - debug_assert!(!self.is_full()); - } + self.grow_if_necessary(); self.tail = self.wrap_sub(self.tail, 1); let tail = self.tail; @@ -1117,14 +1110,7 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn push_back(&mut self, value: T) { - if self.is_full() { - let old_cap = self.cap(); - self.buf.double(); - unsafe { - self.handle_cap_increase(old_cap); - } - debug_assert!(!self.is_full()); - } + self.grow_if_necessary(); let head = self.head; self.head = self.wrap_add(self.head, 1); @@ -1257,14 +1243,7 @@ impl VecDeque { #[stable(feature = "deque_extras_15", since = "1.5.0")] pub fn insert(&mut self, index: usize, value: T) { assert!(index <= self.len(), "index out of bounds"); - if self.is_full() { - let old_cap = self.cap(); - self.buf.double(); - unsafe { - self.handle_cap_increase(old_cap); - } - debug_assert!(!self.is_full()); - } + self.grow_if_necessary(); // Move the least number of elements in the ring buffer and insert // the given object @@ -1762,6 +1741,69 @@ impl VecDeque { self.truncate(len - del); } } + + // This may panic or abort + #[inline] + fn grow_if_necessary(&mut self) { + if self.is_full() { + let old_cap = self.cap(); + self.buf.double(); + unsafe { + self.handle_cap_increase(old_cap); + } + debug_assert!(!self.is_full()); + } + } + + /// Returns a place for insertion at the back of the `VecDeque`. + /// + /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back), + /// but may be more efficient. + /// + /// # Examples + /// + /// ``` + /// #![feature(collection_placement)] + /// #![feature(placement_in_syntax)] + /// + /// use std::collections::VecDeque; + /// + /// let mut buf = VecDeque::new(); + /// buf.place_back() <- 3; + /// buf.place_back() <- 4; + /// assert_eq!(&buf, &[3, 4]); + /// ``` + #[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] + pub fn place_back(&mut self) -> PlaceBack { + PlaceBack { vec_deque: self } + } + + /// Returns a place for insertion at the front of the `VecDeque`. + /// + /// Using this method with placement syntax is equivalent to [`push_front`](#method.push_front), + /// but may be more efficient. + /// + /// # Examples + /// + /// ``` + /// #![feature(collection_placement)] + /// #![feature(placement_in_syntax)] + /// + /// use std::collections::VecDeque; + /// + /// let mut buf = VecDeque::new(); + /// buf.place_front() <- 3; + /// buf.place_front() <- 4; + /// assert_eq!(&buf, &[4, 3]); + /// ``` + #[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] + pub fn place_front(&mut self) -> PlaceFront { + PlaceFront { vec_deque: self } + } } impl VecDeque { @@ -2442,6 +2484,98 @@ impl From> for Vec { } } +/// A place for insertion at the back of a `VecDeque`. +/// +/// See [`VecDeque::place_back`](struct.VecDeque.html#method.place_back) for details. +#[must_use = "places do nothing unless written to with `<-` syntax"] +#[unstable(feature = "collection_placement", + reason = "struct name and placement protocol are subject to change", + issue = "30172")] +#[derive(Debug)] +pub struct PlaceBack<'a, T: 'a> { + vec_deque: &'a mut VecDeque, +} + +#[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] +impl<'a, T> Placer for PlaceBack<'a, T> { + type Place = PlaceBack<'a, T>; + + fn make_place(self) -> Self { + self.vec_deque.grow_if_necessary(); + self + } +} + +#[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] +impl<'a, T> Place for PlaceBack<'a, T> { + fn pointer(&mut self) -> *mut T { + unsafe { self.vec_deque.ptr().offset(self.vec_deque.head as isize) } + } +} + +#[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] +impl<'a, T> InPlace for PlaceBack<'a, T> { + type Owner = &'a mut T; + + unsafe fn finalize(mut self) -> &'a mut T { + let head = self.vec_deque.head; + self.vec_deque.head = self.vec_deque.wrap_add(head, 1); + &mut *(self.vec_deque.ptr().offset(head as isize)) + } +} + +/// A place for insertion at the front of a `VecDeque`. +/// +/// See [`VecDeque::place_front`](struct.VecDeque.html#method.place_front) for details. +#[must_use = "places do nothing unless written to with `<-` syntax"] +#[unstable(feature = "collection_placement", + reason = "struct name and placement protocol are subject to change", + issue = "30172")] +#[derive(Debug)] +pub struct PlaceFront<'a, T: 'a> { + vec_deque: &'a mut VecDeque, +} + +#[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] +impl<'a, T> Placer for PlaceFront<'a, T> { + type Place = PlaceFront<'a, T>; + + fn make_place(self) -> Self { + self.vec_deque.grow_if_necessary(); + self + } +} + +#[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] +impl<'a, T> Place for PlaceFront<'a, T> { + fn pointer(&mut self) -> *mut T { + let tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1); + unsafe { self.vec_deque.ptr().offset(tail as isize) } + } +} + +#[unstable(feature = "collection_placement", + reason = "placement protocol is subject to change", + issue = "30172")] +impl<'a, T> InPlace for PlaceFront<'a, T> { + type Owner = &'a mut T; + + unsafe fn finalize(mut self) -> &'a mut T { + self.vec_deque.tail = self.vec_deque.wrap_sub(self.vec_deque.tail, 1); + &mut *(self.vec_deque.ptr().offset(self.vec_deque.tail as isize)) + } +} + #[cfg(test)] mod tests { use test; @@ -2797,4 +2931,5 @@ mod tests { } } } + } diff --git a/src/libcollectionstest/lib.rs b/src/libcollectionstest/lib.rs index 849d240169169..d97d9b8ab83f6 100644 --- a/src/libcollectionstest/lib.rs +++ b/src/libcollectionstest/lib.rs @@ -32,6 +32,7 @@ extern crate collections; extern crate test; extern crate std_unicode; +extern crate core; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; diff --git a/src/libcollectionstest/vec_deque.rs b/src/libcollectionstest/vec_deque.rs index 1541061a19842..f2935c05d4f7a 100644 --- a/src/libcollectionstest/vec_deque.rs +++ b/src/libcollectionstest/vec_deque.rs @@ -10,7 +10,7 @@ use std::collections::VecDeque; use std::fmt::Debug; -use std::collections::vec_deque::Drain; +use std::collections::vec_deque::{Drain}; use self::Taggy::*; use self::Taggypar::*; @@ -1000,3 +1000,25 @@ fn test_is_empty() { assert!(v.iter_mut().is_empty()); assert!(v.into_iter().is_empty()); } + +#[test] +fn test_placement_in() { + let mut buf: VecDeque = VecDeque::new(); + buf.place_back() <- 1; + buf.place_back() <- 2; + assert_eq!(buf, [1,2]); + + buf.place_front() <- 3; + buf.place_front() <- 4; + assert_eq!(buf, [4,3,1,2]); + + { + let ptr_head = buf.place_front() <- 5; + assert_eq!(*ptr_head, 5); + } + { + let ptr_tail = buf.place_back() <- 6; + assert_eq!(*ptr_tail, 6); + } + assert_eq!(buf, [5,4,3,1,2,6]); +} From 84d1f6aa82123c2951042aff99e43bdb894d3d81 Mon Sep 17 00:00:00 2001 From: Simonas Kazlauskas Date: Wed, 8 Mar 2017 22:17:42 +0200 Subject: [PATCH 18/19] Do not bother creating StorageLive for TyNever Keeps MIR cleaner, `StorageLive(_: !)` makes no sense anyway. --- src/librustc_mir/build/expr/as_temp.rs | 2 +- src/test/mir-opt/issue-38669.rs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/librustc_mir/build/expr/as_temp.rs b/src/librustc_mir/build/expr/as_temp.rs index 69b9570200921..42d9ab4d2bf27 100644 --- a/src/librustc_mir/build/expr/as_temp.rs +++ b/src/librustc_mir/build/expr/as_temp.rs @@ -55,7 +55,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { (https://github.com/rust-lang/rust/issues/39283)"); } - if temp_lifetime.is_some() { + if !expr_ty.is_never() && temp_lifetime.is_some() { this.cfg.push(block, Statement { source_info: source_info, kind: StatementKind::StorageLive(temp.clone()) diff --git a/src/test/mir-opt/issue-38669.rs b/src/test/mir-opt/issue-38669.rs index 1d452907cf59a..fbbffe8953b38 100644 --- a/src/test/mir-opt/issue-38669.rs +++ b/src/test/mir-opt/issue-38669.rs @@ -35,7 +35,6 @@ fn main() { // } // // bb2: { -// StorageLive(_6); // _0 = (); // StorageDead(_4); // StorageDead(_1); From 4078b255897d0cdba8a864bd8bb1da92d827a32d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 9 Mar 2017 19:02:59 +0100 Subject: [PATCH 19/19] Clean up rustdoc css --- src/librustdoc/html/static/rustdoc.css | 33 ++---- src/librustdoc/html/static/styles/main.css | 114 +++++++++++++++------ 2 files changed, 89 insertions(+), 58 deletions(-) diff --git a/src/librustdoc/html/static/rustdoc.css b/src/librustdoc/html/static/rustdoc.css index 6bd9cf6620b0e..4047f6045bcc5 100644 --- a/src/librustdoc/html/static/rustdoc.css +++ b/src/librustdoc/html/static/rustdoc.css @@ -377,13 +377,13 @@ h4 > code, h3 > code, .invisible > code { .content .method .where, .content .fn .where, .content .where.fmt-newline { - display: block; + display: block; } /* Bit of whitespace to indent it */ .content .method .where::before, .content .fn .where::before, .content .where.fmt-newline::before { - content: ' '; + content: ' '; } .content .methods > div { margin-left: 40px; } @@ -506,17 +506,15 @@ body.blur > :not(#help) { } #help > div { flex: 0 0 auto; - background: #e9e9e9; box-shadow: 0 0 6px rgba(0,0,0,.2); width: 550px; height: 330px; - border: 1px solid #bfbfbf; + border: 1px solid; } #help dt { float: left; border-radius: 4px; - border: 1px solid #bfbfbf; - background: #fff; + border: 1px solid; width: 23px; text-align: center; clear: left; @@ -567,7 +565,6 @@ body.blur > :not(#help) { .since { font-weight: normal; font-size: initial; - color: grey; position: absolute; right: 0; top: 0; @@ -589,24 +586,12 @@ td.summary-column { padding-right: 0px; } -.line-numbers :target { background-color: transparent; } - -/* Code highlighting */ -pre.rust .kw { color: #8959A8; } -pre.rust .kw-2, pre.rust .prelude-ty { color: #4271AE; } -pre.rust .number, pre.rust .string { color: #718C00; } -pre.rust .self, pre.rust .bool-val, pre.rust .prelude-val, -pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; } -pre.rust .macro, pre.rust .macro-nonterminal { color: #3E999F; } -pre.rust .lifetime { color: #B76514; } pre.rust .question-mark { - color: #ff9011; font-weight: bold; } pre.rust { position: relative; } a.test-arrow { - background-color: rgba(78, 139, 202, 0.2); display: inline-block; position: absolute; padding: 5px 10px 5px 10px; @@ -616,7 +601,6 @@ a.test-arrow { right: 5px; } a.test-arrow:hover{ - background-color: #4e8bca; text-decoration: none; } @@ -660,10 +644,6 @@ a.test-arrow:hover{ text-align: center; } -.toggle-label { - color: #999; -} - .ghost { display: none; } @@ -719,8 +699,7 @@ span.since { } :target > code { - background: #FDFFD3; - opacity: 1; + opacity: 1; } /* Media Queries */ @@ -793,4 +772,4 @@ span.since { nav.sub, .content .out-of-band, .collapse-toggle { display: none; } -} +} \ No newline at end of file diff --git a/src/librustdoc/html/static/styles/main.css b/src/librustdoc/html/static/styles/main.css index f1e81900d1eec..40561597e93e0 100644 --- a/src/librustdoc/html/static/styles/main.css +++ b/src/librustdoc/html/static/styles/main.css @@ -13,28 +13,36 @@ /* General structure and fonts */ body { - background-color: white; - color: black; + background-color: white; + color: black; } h1, h2, h3:not(.impl):not(.method):not(.type):not(.tymethod), h4:not(.method):not(.type):not(.tymethod) { - color: black; + color: black; } h1.fqn { - border-bottom-color: #D5D5D5; + border-bottom-color: #D5D5D5; } h2, h3:not(.impl):not(.method):not(.type):not(.tymethod), h4:not(.method):not(.type):not(.tymethod) { - border-bottom-color: #DDDDDD; + border-bottom-color: #DDDDDD; } .in-band { - background-color: white; + background-color: white; } .docblock code, .docblock-short code { - background-color: #F5F5F5; + background-color: #F5F5F5; } pre { - background-color: #F5F5F5; + background-color: #F5F5F5; +} + +.sidebar { + background-color: #F1F1F1; +} + +.sidebar .current { + background-color: #fff; } .sidebar { @@ -46,24 +54,24 @@ pre { } .sidebar .location { - border-color: #000; - background-color: #fff; - color: #333; + border-color: #000; + background-color: #fff; + color: #333; } .block a:hover { - background: #F5F5F5; + background: #F5F5F5; } .line-numbers span { color: #c67e2d; } .line-numbers .line-highlighted { - background-color: #f6fdb0 !important; + background-color: #f6fdb0 !important; } :target { background: #FDFFD3; } .content .highlighted { - color: #000 !important; - background-color: #ccc; + color: #000 !important; + background-color: #ccc; } .content .highlighted a, .content .highlighted span { color: #000 !important; } .content .highlighted.trait { background-color: #fece7e; } @@ -76,21 +84,21 @@ pre { .content .highlighted.type { background-color: #c6afb3; } .docblock h1, .docblock h2, .docblock h3, .docblock h4, .docblock h5 { - border-bottom-color: #DDD; + border-bottom-color: #DDD; } .docblock table { - border-color: #ddd; + border-color: #ddd; } .docblock table td { - border-top-color: #ddd; - border-bottom-color: #ddd; + border-top-color: #ddd; + border-bottom-color: #ddd; } .docblock table th { - border-top-color: #ddd; - border-bottom-color: #ddd; + border-top-color: #ddd; + border-bottom-color: #ddd; } .content span.primitive, .content a.primitive, .block a.current.primitive { color: #39a7bf; } @@ -105,34 +113,78 @@ pre.rust .comment { color: #8E908C; } pre.rust .doccomment { color: #4D4D4C; } nav { - border-bottom-color: #e0e0e0; + border-bottom-color: #e0e0e0; } nav.main .current { - border-top-color: #000; - border-bottom-color: #000; + border-top-color: #000; + border-bottom-color: #000; } nav.main .separator { - border: 1px solid #000; + border: 1px solid #000; } a { - color: #000; + color: #000; } .docblock a, .docblock-short a, .stability a { - color: #3873AD; + color: #3873AD; } a.test-arrow { - color: #f5f5f5; + color: #f5f5f5; } .content span.trait, .content a.trait, .block a.current.trait { color: #7c5af3; } .search-input { - color: #555; - box-shadow: 0 0 0 1px #e0e0e0, 0 0 0 2px transparent; - background-color: white; + color: #555; + box-shadow: 0 0 0 1px #e0e0e0, 0 0 0 2px transparent; + background-color: white; } .stab.unstable { background: #FFF5D6; border-color: #FFC600; } .stab.deprecated { background: #F3DFFF; border-color: #7F0087; } + +#help > div { + background: #e9e9e9; + border-color: #bfbfbf;; +} + +#help dt { + border-color: #bfbfbf; + background: #fff; +} + +.since { + color: grey; +} + +.line-numbers :target { background-color: transparent; } + +/* Code highlighting */ +pre.rust .kw { color: #8959A8; } +pre.rust .kw-2, pre.rust .prelude-ty { color: #4271AE; } +pre.rust .number, pre.rust .string { color: #718C00; } +pre.rust .self, pre.rust .bool-val, pre.rust .prelude-val, +pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; } +pre.rust .macro, pre.rust .macro-nonterminal { color: #3E999F; } +pre.rust .lifetime { color: #B76514; } +pre.rust .question-mark { + color: #ff9011; +} + +a.test-arrow { + background-color: rgba(78, 139, 202, 0.2); +} + +a.test-arrow:hover{ + background-color: #4e8bca; +} + +.toggle-label { + color: #999; +} + +:target > code { + background: #FDFFD3; +} \ No newline at end of file