Skip to content

Implement RFC 2011 (nicer assert messages) #48973

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

Closed
wants to merge 7 commits into from
Closed
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
84 changes: 84 additions & 0 deletions src/libcore/lib.rs
Original file line number Diff line number Diff line change
@@ -208,3 +208,87 @@ pub use coresimd::simd;
#[unstable(feature = "stdsimd", issue = "48556")]
#[cfg(not(stage0))]
pub use coresimd::arch;

// FIXME: move to appropriate location
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please move this to libcore/asserting.rs (by analogy with runtime support for panicking in libcore/panicking.rs).

#[doc(hidden)]
#[allow(missing_docs)]
#[unstable(feature = "generic_assert_internals", issue = "44838")]
pub mod assert_helper {
use fmt::{self, Debug, Formatter};

#[unstable(feature = "generic_assert_internals", issue = "44838")]
#[allow(missing_debug_implementations)]
pub enum Captured<T> {
Value(T),
NotCopy,
Unevaluated,
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
pub struct DebugFallback<T> {
value: Captured<T>,
alt: &'static str,
}

impl<T> DebugFallback<T> {
#[inline]
#[unstable(feature = "generic_assert_internals", issue = "44838")]
pub fn new(value: Captured<T>, alt: &'static str) -> Self {
DebugFallback { value, alt }
}
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
impl<T> Debug for DebugFallback<T> {
default fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str(match self.value {
Captured::Value(_) | Captured::NotCopy => self.alt,
Captured::Unevaluated => "(unevaluated)",
})
}
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
impl<T: Debug> Debug for DebugFallback<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.value {
Captured::Value(ref value) => Debug::fmt(value, f),
Captured::NotCopy => f.write_str(self.alt),
Captured::Unevaluated => f.write_str("(unevaluated)"),
}
}
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
pub trait TryCapture: Sized {
fn try_capture(&self, to: &mut Captured<Self>) -> &Self;
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
impl<T> TryCapture for T {
#[inline]
default fn try_capture(&self, to: &mut Captured<Self>) -> &Self {
*to = Captured::NotCopy;
self
}
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
impl<T: Copy> TryCapture for T {
#[inline]
fn try_capture(&self, to: &mut Captured<Self>) -> &Self {
*to = Captured::Value(*self);
self
}
}

#[unstable(feature = "generic_assert_internals", issue = "44838")]
pub struct Unevaluated;

#[unstable(feature = "generic_assert_internals", issue = "44838")]
impl Debug for Unevaluated {
default fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("(unevaluated)")
}
}
}
4 changes: 4 additions & 0 deletions src/libstd/lib.rs
Original file line number Diff line number Diff line change
@@ -322,6 +322,7 @@
#![feature(doc_cfg)]
#![feature(doc_masked)]
#![feature(doc_spotlight)]
#![feature(generic_assert_internals)]
#![cfg_attr(test, feature(update_panic_count))]
#![cfg_attr(windows, feature(used))]
#![cfg_attr(stage0, feature(never_type))]
@@ -536,3 +537,6 @@ pub use stdsimd::arch;
// the rustdoc documentation for primitive types. Using `include!`
// because rustdoc only looks for these modules at the crate level.
include!("primitive_docs.rs");

#[unstable(feature = "generic_assert_internals", issue = "44838")]
pub use core::assert_helper;
16 changes: 16 additions & 0 deletions src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
@@ -621,6 +621,22 @@ pub enum BindingMode {
ByValue(Mutability),
}

impl BindingMode {
pub fn is_by_ref(&self) -> bool {
match *self {
BindingMode::ByRef(..) => true,
_ => false,
}
}

pub fn is_by_value(&self) -> bool {
match *self {
BindingMode::ByValue(..) => true,
_ => false,
}
}
}

#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum RangeEnd {
Included(RangeSyntax),
741 changes: 708 additions & 33 deletions src/libsyntax_ext/assert.rs

Large diffs are not rendered by default.

140 changes: 140 additions & 0 deletions src/libsyntax_ext/assert_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::ops::Add;

#[test]
fn misc() {
assert!(!false);
assert!(-3 == 3 * (-1));
assert!(!r"\b\w{13}\b".is_empty());

{
let x = &3;
let y = &1;
assert!(*x << *y == 6);
}
{
use std::cell::RefCell;
let x = RefCell::new(0);
assert!(*(&0 as &PartialEq<i32>) == *x.borrow());
}
{
fn x() {}
let y: fn() = x;
assert!(y == x);
}
{
#[derive(PartialEq)]
struct Foo;
impl<'a> Add<&'a mut Foo> for Foo {
type Output = Self;
fn add(self, _: &mut Foo) -> Self {
Foo
}
}
assert!(Foo == Foo + &mut Foo);
}
}

#[cfg(not(stage0))]
#[test]
#[should_panic(expected=
"1 == 1 && (y) + (NonDebug(1)) == (NonDebug(0)) && (unevaluated) == 1 && (unevaluated)")]
fn capture() {
#[derive(Ord, Eq, PartialOrd, PartialEq)]
struct NonDebug(i32);
impl Add for NonDebug {
type Output = Self;
fn add(self, rhs: Self) -> Self {
NonDebug(self.0 + rhs.0)
}
}

let x = 1;
let y = NonDebug(0);
assert!(x == 1 && y + NonDebug(1) == NonDebug(0) && x == 1 && { 1 == 0 });
}

#[cfg(not(stage0))]
#[test]
#[should_panic(expected="(Foo) != (Foo) && (unevaluated) == (unevaluated)")]
fn debug_unevaluated() {
#[derive(PartialEq)]
struct Foo;
assert!(Foo != Foo && Foo == Foo);
}

#[cfg(not(stage0))]
#[test]
#[should_panic(expected=r#"assertion failed: "☃\n" == "☀\n""#)]
fn escape_expr() {
assert!("☃\n" == "☀\n");
}

#[cfg(not(stage0))]
#[test]
#[should_panic(expected=r#"with expansion: "☃\n" == "☀\n""#)]
fn escape_expn() {
assert!("☃\n" == "☀\n");
}

#[test]
fn evaluation_order() {
let mut it = vec![1, 2, 4, 8, 16].into_iter();
assert!(
it.next().unwrap() != 1
|| it.next().unwrap() == 2
&& (it.next().unwrap() + it.next().unwrap() == 12 && it.next().unwrap() == 16)
);

let mut it = vec![2, 3, 16].into_iter();
assert!(it.next().unwrap() << it.next().unwrap() == it.next().unwrap());

let mut b = false;
assert!(
true || {
b = true;
false
}
);
assert!(!b);
assert!(
!(false && {
b = true;
false
})
);
assert!(!b);

let mut n = 0;
assert!(
true && (false || {
n += 1;
true
} || {
n += 2;
true
}) && (({
n += 4;
false
} && {
n += 8;
true
}) != ({
n += 16;
false
} || {
n += 32;
true
}))
);
assert!(n == 1 + 4 + 16 + 32);
}
13 changes: 11 additions & 2 deletions src/libsyntax_ext/lib.rs
Original file line number Diff line number Diff line change
@@ -28,6 +28,8 @@ extern crate rustc_data_structures;
extern crate rustc_errors as errors;

mod assert;
#[cfg(test)]
mod assert_tests;
mod asm;
mod cfg;
mod compile_error;
@@ -114,10 +116,9 @@ pub fn register_builtins(resolver: &mut syntax::ext::base::Resolver,
log_syntax: log_syntax::expand_syntax_ext,
trace_macros: trace_macros::expand_trace_macros,
compile_error: compile_error::expand_compile_error,
assert: assert::expand_assert,
}

// format_args uses `unstable` things internally.
// uses `unstable` things internally.
register(Symbol::intern("format_args"),
NormalTT {
expander: Box::new(format::expand_format_args),
@@ -126,6 +127,14 @@ pub fn register_builtins(resolver: &mut syntax::ext::base::Resolver,
allow_internal_unsafe: false,
unstable_feature: None
});
register(Symbol::intern("assert"),
NormalTT {
expander: Box::new(assert::expand_assert),
def_info: None,
allow_internal_unstable: true,
allow_internal_unsafe: false,
unstable_feature: None
});

for (name, ext) in user_exts {
register(name, ext);
2 changes: 1 addition & 1 deletion src/test/run-fail/assert-macro-explicit.rs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// error-pattern:panicked at 'assertion failed: false'
// error-pattern:panicked at 'assertion failed: false

fn main() {
assert!(false);
2 changes: 1 addition & 1 deletion src/test/run-make-fulldeps/libtest-json/output.json
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
{ "type": "test", "event": "started", "name": "a" }
{ "type": "test", "name": "a", "event": "ok" }
{ "type": "test", "event": "started", "name": "b" }
{ "type": "test", "name": "b", "event": "failed", "stdout": "thread 'b' panicked at 'assertion failed: false', f.rs:18:5\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n" }
{ "type": "test", "name": "b", "event": "failed", "stdout": "thread 'b' panicked at 'assertion failed: false\nwith expansion: false', f.rs:18:5\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n" }
{ "type": "test", "event": "started", "name": "c" }
{ "type": "test", "name": "c", "event": "ok" }
{ "type": "test", "event": "started", "name": "d" }
2 changes: 1 addition & 1 deletion src/test/ui/codemap_tests/issue-28308.rs
Original file line number Diff line number Diff line change
@@ -10,5 +10,5 @@

fn main() {
assert!("foo");
//~^ ERROR cannot apply unary operator `!`
//~^ ERROR mismatched types
}
9 changes: 6 additions & 3 deletions src/test/ui/codemap_tests/issue-28308.stderr
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
error[E0600]: cannot apply unary operator `!` to type `&'static str`
error[E0308]: mismatched types
--> $DIR/issue-28308.rs:12:5
|
LL | assert!("foo");
| ^^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^^ expected bool, found reference
|
= note: expected type `bool`
found type `&'static str`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0600`.
For more information about this error, try `rustc --explain E0308`.