Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Rollup of 5 pull requests #101617

Merged
merged 16 commits into from
Sep 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 3 additions & 33 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use rustc_span::source_map::{respan, Spanned};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{Span, DUMMY_SP};
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt;
use std::mem;
Expand Down Expand Up @@ -324,46 +323,17 @@ pub type GenericBounds = Vec<GenericBound>;
/// Specifies the enforced ordering for generic parameters. In the future,
/// if we wanted to relax this order, we could override `PartialEq` and
/// `PartialOrd`, to allow the kinds to be unordered.
#[derive(Hash, Clone, Copy)]
#[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ParamKindOrd {
Lifetime,
Type,
Const,
// `Infer` is not actually constructed directly from the AST, but is implicitly constructed
// during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
Infer,
}

impl Ord for ParamKindOrd {
fn cmp(&self, other: &Self) -> Ordering {
use ParamKindOrd::*;
let to_int = |v| match v {
Lifetime => 0,
Infer | Type | Const => 1,
};

to_int(*self).cmp(&to_int(*other))
}
}
impl PartialOrd for ParamKindOrd {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for ParamKindOrd {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
TypeOrConst,
}
impl Eq for ParamKindOrd {}

impl fmt::Display for ParamKindOrd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParamKindOrd::Lifetime => "lifetime".fmt(f),
ParamKindOrd::Type => "type".fmt(f),
ParamKindOrd::Const { .. } => "const".fmt(f),
ParamKindOrd::Infer => "infer".fmt(f),
ParamKindOrd::TypeOrConst => "type and const".fmt(f),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,10 +839,10 @@ fn validate_generic_param_order(
let (kind, bounds, span) = (&param.kind, &param.bounds, ident.span);
let (ord_kind, ident) = match &param.kind {
GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
GenericParamKind::Type { default: _ } => (ParamKindOrd::Type, ident.to_string()),
GenericParamKind::Type { default: _ } => (ParamKindOrd::TypeOrConst, ident.to_string()),
GenericParamKind::Const { ref ty, kw_span: _, default: _ } => {
let ty = pprust::ty_to_string(ty);
(ParamKindOrd::Const, format!("const {}: {}", ident, ty))
(ParamKindOrd::TypeOrConst, format!("const {}: {}", ident, ty))
}
};
param_idents.push((kind, ord_kind, bounds, idx, ident));
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_codegen_llvm/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,11 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
}

fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
try_as_const_integral(v).map(|v| unsafe { llvm::LLVMConstIntGetZExtValue(v) })
try_as_const_integral(v).and_then(|v| unsafe {
let mut i = 0u64;
let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
success.then_some(i)
})
}

fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/llvm/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,7 +1096,7 @@ extern "C" {
pub fn LLVMConstInt(IntTy: &Type, N: c_ulonglong, SignExtend: Bool) -> &Value;
pub fn LLVMConstIntOfArbitraryPrecision(IntTy: &Type, Wn: c_uint, Ws: *const u64) -> &Value;
pub fn LLVMConstReal(RealTy: &Type, N: f64) -> &Value;
pub fn LLVMConstIntGetZExtValue(ConstantVal: &ConstantInt) -> c_ulonglong;
pub fn LLVMRustConstIntGetZExtValue(ConstantVal: &ConstantInt, Value: &mut u64) -> bool;
pub fn LLVMRustConstInt128Get(
ConstantVal: &ConstantInt,
SExt: bool,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_ssa/src/mir/rvalue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
let size = bx.const_usize(dest.layout.size.bytes());

// Use llvm.memset.p0i8.* to initialize all zero arrays
if bx.cx().const_to_opt_uint(v) == Some(0) {
if bx.cx().const_to_opt_u128(v, false) == Some(0) {
let fill = bx.cx().const_u8(0);
bx.memset(start, fill, size, dest.align, MemFlags::empty());
return bx;
Expand Down
14 changes: 11 additions & 3 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,9 +300,9 @@ impl GenericArg<'_> {
pub fn to_ord(&self) -> ast::ParamKindOrd {
match self {
GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
GenericArg::Type(_) => ast::ParamKindOrd::Type,
GenericArg::Const(_) => ast::ParamKindOrd::Const,
GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
GenericArg::Type(_) | GenericArg::Const(_) | GenericArg::Infer(_) => {
ast::ParamKindOrd::TypeOrConst
}
}
}

Expand Down Expand Up @@ -2401,6 +2401,14 @@ impl<'hir> Ty<'hir> {
_ => None,
}
}

pub fn peel_refs(&self) -> &Self {
let mut final_ty = self;
while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
final_ty = &ty;
}
final_ty
}
}

/// Not represented directly in the AST; referred to by name through a `ty_path`.
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1618,6 +1618,14 @@ extern "C" LLVMValueRef LLVMRustConstInBoundsGEP2(LLVMTypeRef Ty,
return wrap(ConstantExpr::getInBoundsGetElementPtr(unwrap(Ty), Val, IdxList));
}

extern "C" bool LLVMRustConstIntGetZExtValue(LLVMValueRef CV, uint64_t *value) {
auto C = unwrap<llvm::ConstantInt>(CV);
if (C->getBitWidth() > 64)
return false;
*value = C->getZExtValue();
return true;
}

// Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
// the common sizes (1, 8, 16, 32, 64, 128 bits)
extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_middle/src/ty/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ impl GenericParamDefKind {
pub fn to_ord(&self) -> ast::ParamKindOrd {
match self {
GenericParamDefKind::Lifetime => ast::ParamKindOrd::Lifetime,
GenericParamDefKind::Type { .. } => ast::ParamKindOrd::Type,
GenericParamDefKind::Const { .. } => ast::ParamKindOrd::Const,
GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
ast::ParamKindOrd::TypeOrConst
}
}
}

Expand Down
47 changes: 23 additions & 24 deletions compiler/rustc_typeck/src/check/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1305,31 +1305,30 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}

fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
if let Some(parent_hir_id) = self.tcx.hir().find_parent_node(expr.hir_id) {
let ty = match self.tcx.hir().find(parent_hir_id) {
Some(
hir::Node::Local(hir::Local { ty: Some(ty), .. })
| hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. }),
) => Some(ty),
_ => None,
};
if let Some(ty) = ty
&& let hir::TyKind::Array(_, length) = ty.kind
&& let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length
&& let Some(span) = self.tcx.hir().opt_span(hir_id)
{
match self.tcx.sess.diagnostic().steal_diagnostic(span, StashKey::UnderscoreForArrayLengths) {
Some(mut err) => {
err.span_suggestion(
span,
"consider specifying the array length",
array_len,
Applicability::MaybeIncorrect,
);
err.emit();
}
None => ()
let parent_node = self.tcx.hir().parent_iter(expr.hir_id).find(|(_, node)| {
!matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
});
let Some((_,
hir::Node::Local(hir::Local { ty: Some(ty), .. })
| hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. }))
) = parent_node else {
return
};
if let hir::TyKind::Array(_, length) = ty.peel_refs().kind
&& let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length
&& let Some(span) = self.tcx.hir().opt_span(hir_id)
{
match self.tcx.sess.diagnostic().steal_diagnostic(span, StashKey::UnderscoreForArrayLengths) {
Some(mut err) => {
err.span_suggestion(
span,
"consider specifying the array length",
array_len,
Applicability::MaybeIncorrect,
);
err.emit();
}
None => ()
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_typeck/src/collect/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<
let ty = item_ctxt.ast_ty_to_ty(hir_ty);

// Iterate through the generics of the projection to find the one that corresponds to
// the def_id that this query was called with. We filter to only const args here as a
// precaution for if it's ever allowed to elide lifetimes in GAT's. It currently isn't
// the def_id that this query was called with. We filter to only type and const args here
// as a precaution for if it's ever allowed to elide lifetimes in GAT's. It currently isn't
// but it can't hurt to be safe ^^
if let ty::Projection(projection) = ty.kind() {
let generics = tcx.generics_of(projection.item_def_id);
Expand Down
3 changes: 2 additions & 1 deletion library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1819,14 +1819,15 @@ impl<'a> Formatter<'a> {
/// write!(formatter,
/// "Foo({}{})",
/// if self.0 < 0 { '-' } else { '+' },
/// self.0)
/// self.0.abs())
/// } else {
/// write!(formatter, "Foo({})", self.0)
/// }
/// }
/// }
///
/// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
/// assert_eq!(&format!("{:+}", Foo(-23)), "Foo(-23)");
/// assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
/// ```
#[must_use]
Expand Down
9 changes: 1 addition & 8 deletions library/std/src/sys/windows/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,14 +198,7 @@ fn parse_next_component(path: &OsStr, verbatim: bool) -> (&OsStr, &OsStr) {

match path.bytes().iter().position(|&x| separator(x)) {
Some(separator_start) => {
let mut separator_end = separator_start + 1;

// a series of multiple separator characters is treated as a single separator,
// except in verbatim paths
while !verbatim && separator_end < path.len() && separator(path.bytes()[separator_end])
{
separator_end += 1;
}
let separator_end = separator_start + 1;

let component = &path.bytes()[..separator_start];

Expand Down
29 changes: 19 additions & 10 deletions library/std/src/sys/windows/path/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,6 @@ fn test_parse_next_component() {
parse_next_component(OsStr::new(r"servershare"), false),
(OsStr::new(r"servershare"), OsStr::new(""))
);

assert_eq!(
parse_next_component(OsStr::new(r"server/\//\/\\\\/////\/share"), false),
(OsStr::new(r"server"), OsStr::new(r"share"))
);

assert_eq!(
parse_next_component(OsStr::new(r"server\\\\\\\\\\\\\\share"), true),
(OsStr::new(r"server"), OsStr::new(r"\\\\\\\\\\\\\share"))
);
}

#[test]
Expand Down Expand Up @@ -126,3 +116,22 @@ fn test_windows_prefix_components() {
assert_eq!(drive.as_os_str(), OsStr::new("C:"));
assert_eq!(components.as_path(), Path::new(""));
}

/// See #101358.
///
/// Note that the exact behaviour here may change in the future.
/// In which case this test will need to adjusted.
#[test]
fn broken_unc_path() {
use crate::path::Component;

let mut components = Path::new(r"\\foo\\bar\\").components();
assert_eq!(components.next(), Some(Component::RootDir));
assert_eq!(components.next(), Some(Component::Normal("foo".as_ref())));
assert_eq!(components.next(), Some(Component::Normal("bar".as_ref())));

let mut components = Path::new("//foo//bar//").components();
assert_eq!(components.next(), Some(Component::RootDir));
assert_eq!(components.next(), Some(Component::Normal("foo".as_ref())));
assert_eq!(components.next(), Some(Component::Normal("bar".as_ref())));
}
12 changes: 12 additions & 0 deletions src/test/ui/array-slice-vec/suggest-array-length.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,22 @@ fn main() {
const Foo: [i32; 3] = [1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
const REF_FOO: &[u8; 1] = &[1];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let foo: [i32; 3] = [1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let bar: [i32; 3] = [0; 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let ref_foo: &[i32; 3] = &[1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let ref_bar: &[i32; 3] = &[0; 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let multiple_ref_foo: &&[i32; 3] = &&[1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
}
12 changes: 12 additions & 0 deletions src/test/ui/array-slice-vec/suggest-array-length.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,22 @@ fn main() {
const Foo: [i32; _] = [1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
const REF_FOO: &[u8; _] = &[1];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let foo: [i32; _] = [1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let bar: [i32; _] = [0; 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let ref_foo: &[i32; _] = &[1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let ref_bar: &[i32; _] = &[0; 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
let multiple_ref_foo: &&[i32; _] = &&[1, 2, 3];
//~^ ERROR in expressions, `_` can only be used on the left-hand side of an assignment
//~| ERROR using `_` for array lengths is unstable
}
Loading