profile
viewpoint
Mara Bos m-ou-se Fusion Engineering Delft, The Netherlands https://m-ou.se/ she/her

fusion-engineering/inline-python 394

Inline Python code directly in your Rust code

de-vri-es/assert2-rs 29

assert!() and check!() macros for Rust, inspired by Catch2

fusion-engineering/setup-git-credentials 26

GitHub action to clone private respositories.

m-ou-se/config 18

The one and only perfect configuration for Vim, Zsh, Bash, Git, etc.

fusion-engineering/rust-git-version 17

Compile the Git version (tag name, or hash otherwise) and dirty state into your Rust program.

m-ou-se/bootlib 17

A minimalistic library to help making your x86 assembly program bootable.

m-ou-se/linux-futex 6

Rust interface for Linux futexes, the fast user-space locking primitive.

m-ou-se/git-prompt-path 5

Display git information next to every path component in your prompt.

m-ou-se/floatconv 4

Fast implementations of integer/floating point conversion operations.

m-ou-se/cloudabi-cpp 2

C++ bindings for CloudABI.

pull request commentrust-lang/rust

Avoid panic_bounds_check in fmt::write.

@Mark-Simulacrum sounds good. Will add that when I have time.

@rustbot modify labels: +S-waiting-on-author -S-waiting-on-review

m-ou-se

comment created time in 15 hours

pull request commentrust-lang/rust

Avoid panic_bounds_check in fmt::write.

@rustbot modify labels: +A-fmt +I-heavy +T-libs

m-ou-se

comment created time in 15 hours

pull request commentrust-lang/rust

Avoid panic_bounds_check in fmt::write.

@rustbot modify labels: +A-fmt +I-heavy +libs-impl

m-ou-se

comment created time in 15 hours

pull request commentrust-lang/rust

Avoid panic_bounds_check in fmt::write.

Related optimization:

https://github.com/rust-lang/rust/blob/a85e94927622665a9e9022de0d33a890a2e32d43/library/core/src/panicking.rs#L44-L50

That optimzation would not be very effective if even writing the most trivial fmt::Arguments pulls in formatting code for usizes, like it does now.

Not sure if this can (or should) be tested for. Checking if some code results in a binary smaller than some threshold would not be a good test. Coming up with a list of symbols that 'should not be there' is also not easy.

m-ou-se

comment created time in 15 hours

PR opened rust-lang/rust

Avoid panic_bounds_check in fmt::write.

Writing any fmt::Arguments would trigger the inclusion of usize formatting and padding code in the resulting binary, because indexing used in fmt::write would generate code using panic_bounds_check, which prints the index and length.

These bounds checks are not necessary, as fmt::Arguments never contains any out-of-bounds indexes.

This change replaces them with unsafe get_unchecked, to reduce the amount of generated code, which is especially important for embedded targets.


Demonstration of the size of and the symbols in a 'hello world' no_std binary:

Before:

   text	   data	    bss	    dec	    hex	filename
   6059	    736	      8	   6803	   1a93	before
0000000000001e00 T <T as core::any::Any>::type_id
0000000000003dd0 D core::fmt::num::DEC_DIGITS_LUT
0000000000001ce0 T core::fmt::num::imp::<impl core::fmt::Display for u64>::fmt
0000000000001ce0 T core::fmt::num::imp::<impl core::fmt::Display for usize>::fmt
0000000000001370 T core::fmt::write
0000000000001b30 t core::fmt::Formatter::pad_integral::write_prefix
0000000000001660 T core::fmt::Formatter::pad_integral
0000000000001350 T core::ops::function::FnOnce::call_once
0000000000001b80 t core::ptr::drop_in_place
0000000000001120 t core::ptr::drop_in_place
0000000000001c50 t core::iter::adapters::zip::Zip<A,B>::new
0000000000001c90 t core::iter::adapters::zip::Zip<A,B>::new
0000000000001b90 T core::panicking::panic_bounds_check
0000000000001c10 T core::panicking::panic_fmt
0000000000001130 t <&mut W as core::fmt::Write>::write_char
0000000000001200 t <&mut W as core::fmt::Write>::write_fmt
0000000000001250 t <&mut W as core::fmt::Write>::write_str

After:

   text	   data	    bss	    dec	    hex	filename
   3068	    600	      8	   3676	    e5c	after
0000000000001360 T core::fmt::write
0000000000001340 T core::ops::function::FnOnce::call_once
0000000000001120 t core::ptr::drop_in_place
0000000000001620 t core::iter::adapters::zip::Zip<A,B>::new
0000000000001660 t core::iter::adapters::zip::Zip<A,B>::new
0000000000001130 t <&mut W as core::fmt::Write>::write_char
0000000000001200 t <&mut W as core::fmt::Write>::write_fmt
0000000000001250 t <&mut W as core::fmt::Write>::write_str
+20 -7

0 comment

1 changed file

pr created time in 16 hours

push eventfusion-engineering-forks/rust

Mara Bos

commit sha d80f127a75017dcdc91f4535b26a668976e2cfc7

Avoid panic_bounds_check in fmt::write. Writing any fmt::Arguments would trigger the inclusion of usize formatting and padding code in the resulting binary, because indexing used in fmt::write would generate code using panic_bounds_check, which prints the index and length. These bounds checks are not necessary, as fmt::Arguments never contains any out-of-bounds indexes. This change replaces them with unsafe get_unchecked, to reduce the amount of generated code, which is especially important for embedded targets.

view details

push time in 16 hours

create barnchfusion-engineering-forks/rust

branch : fmt-write-bounds-check

created branch time in 16 hours

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 9890217c0eedcbe4742e412ea59e851ecd500bf5

Fix ui test for updated core::panic behaviour. It now throws a &str instead of a String.

view details

push time in 17 hours

PR opened rust-lang/rust

Throw core::panic!("message") as &str instead of String.

This makes core::panic!("message") consistent with std::panic!("message"), which throws a &str and not a String.


Demonstration:

use std::panic;
use std::any::Any;

fn main() {
    panic::set_hook(Box::new(|panic_info| check(panic_info.payload())));

    check(&*panic::catch_unwind(|| core::panic!("core")).unwrap_err());
    check(&*panic::catch_unwind(|| std::panic!("std")).unwrap_err());
}

fn check(msg: &(dyn Any + Send)) {
    if let Some(s) = msg.downcast_ref::<String>() {
        println!("Got a String: {:?}", s);
    } else if let Some(s) = msg.downcast_ref::<&str>() {
        println!("Got a &str: {:?}", s);
    }
}

Before:

Got a String: "panic"
Got a String: "panic"
Got a &str: "panic"
Got a &str: "panic"

After:

Got a &str: "core"
Got a &str: "core"
Got a &str: "std"
Got a &str: "std"
+19 -2

0 comment

3 changed files

pr created time in 17 hours

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 3c3ea5c1e38eb6763953d8a7724a0ed5570f4774

Fix ui test for updated core::panic behaviour. It now throws a &str instead of a String.

view details

push time in 17 hours

create barnchfusion-engineering-forks/rust

branch : panic-use-as-str

created branch time in 17 hours

push eventfusion-engineering-forks/rust

Mara Bos

commit sha dfd329158e79bb12ba7de72ca2e098b687b88891

Small cleanups in assert!() and panic_fmt lint. (From the PR feedback.) Co-authored-by: Esteban Küber <esteban@kuber.com.ar>

view details

push time in 18 hours

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let mut expn = f.span.ctxt().outer_expn_data();+            if let Some(id) = expn.macro_def_id {+                if cx.tcx.is_diagnostic_item(sym::std_panic_macro, id)+                    || cx.tcx.is_diagnostic_item(sym::core_panic_macro, id)+                {

The let_chains feature would be nice. But looks like that one still needs more work before it's usable.

m-ou-se

comment created time in 18 hours

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

 pub fn expand_assert<'cx>(     // `core::panic` and `std::panic` are different macros, so we use call-site     // context to pick up whichever is currently in scope.     let sp = cx.with_call_site_ctxt(sp);-    let tokens = custom_message.unwrap_or_else(|| {-        TokenStream::from(TokenTree::token(-            TokenKind::lit(-                token::Str,-                Symbol::intern(&format!(-                    "assertion failed: {}",-                    pprust::expr_to_string(&cond_expr).escape_debug()-                )),-                None,-            ),-            DUMMY_SP,-        ))-    });-    let args = P(MacArgs::Delimited(DelimSpan::from_single(sp), MacDelimiter::Parenthesis, tokens));-    let panic_call = MacCall {-        path: Path::from_ident(Ident::new(sym::panic, sp)),-        args,-        prior_type_ascription: None,++    let panic_call = {

Nope. Thanks.

m-ou-se

comment created time in 19 hours

PullRequestReviewEvent

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 8ec537e97ab696d88a0485c15d7beacb8e0cce42

Small cleanups in assert!() and panic_fmt lint. (From the PR feedback.) Co-authored-by: Esteban Küber <esteban@kuber.com.ar>

view details

push time in 19 hours

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

 pub fn expand_assert<'cx>(     // `core::panic` and `std::panic` are different macros, so we use call-site     // context to pick up whichever is currently in scope.     let sp = cx.with_call_site_ctxt(sp);-    let tokens = custom_message.unwrap_or_else(|| {-        TokenStream::from(TokenTree::token(-            TokenKind::lit(-                token::Str,-                Symbol::intern(&format!(-                    "assertion failed: {}",-                    pprust::expr_to_string(&cond_expr).escape_debug()-                )),-                None,-            ),-            DUMMY_SP,-        ))-    });-    let args = P(MacArgs::Delimited(DelimSpan::from_single(sp), MacDelimiter::Parenthesis, tokens));-    let panic_call = MacCall {-        path: Path::from_ident(Ident::new(sym::panic, sp)),-        args,-        prior_type_ascription: None,++    let panic_call = {+        if let Some(tokens) = custom_message {+            // Pass the custom message to panic!().+            cx.expr(+                sp,+                ExprKind::MacCall(MacCall {+                    path: Path::from_ident(Ident::new(sym::panic, sp)),+                    args: P(MacArgs::Delimited(+                        DelimSpan::from_single(sp),+                        MacDelimiter::Parenthesis,+                        tokens,+                    )),+                    prior_type_ascription: None,+                }),+            )+        } else {+            // Pass our own message directly to $crate::panicking::panic(),+            // because it might contain `{` and `}` that should always be

Nope. That's the format string it gives to format!() at compile time, inside rustc. It's the resulting string that is put in the macro expansion as string literal.

I could change that to do that at runtime, (produce the tokens "assertion failed: {}", "stringified source here") but then const_panic will no longer work on assert!(expr). See https://github.com/rust-lang/rust/pull/78069.

m-ou-se

comment created time in 19 hours

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let mut expn = f.span.ctxt().outer_expn_data();+            if let Some(id) = expn.macro_def_id {+                if cx.tcx.is_diagnostic_item(sym::std_panic_macro, id)+                    || cx.tcx.is_diagnostic_item(sym::core_panic_macro, id)+                {+                    let s = sym.as_str();+                    if !s.contains(&['{', '}'][..]) {+                        return;+                    }+                    let s = s.replace("{{", "").replace("}}", "");+                    let looks_like_placeholder =+                        s.find('{').map_or(false, |i| s[i + 1..].contains('}'));+                    // Unwrap another level of macro expansion if this panic!()+                    // was expanded from assert!() or debug_assert!().+                    for &assert in &[sym::assert_macro, sym::debug_assert_macro] {+                        let parent = expn.call_site.ctxt().outer_expn_data();+                        if parent+                            .macro_def_id+                            .map_or(false, |id| cx.tcx.is_diagnostic_item(assert, id))+                        {+                            expn = parent;+                        }+                    }+                    if looks_like_placeholder {+                        cx.struct_span_lint(PANIC_FMT, arg.span.source_callsite(), |lint| {+                            let mut l = lint.build("Panic message contains an unused formatting placeholder");+                            l.note("This message is not used as a format string when given without arguments, but will be in a future Rust version");+                            if expn.call_site.contains(arg.span) {+                                l.span_suggestion(+                                    arg.span.shrink_to_hi(),+                                    "add the missing argument(s)",+                                    ", argument".into(),+                                    Applicability::HasPlaceholders,

Re-using the fmt string parser that format_args!() uses looks like a lot of work. Would be great though. Then it can properly suggest adding hello=.. for {hello}, etc.

m-ou-se

comment created time in 19 hours

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+warning: Panic message contains a brace+  --> $DIR/panic-brace.rs:5:5+   |+LL |     panic!("here's a brace: {");+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^+   |+   = note: `#[warn(panic_fmt)]` on by default+   = note: This message is not used as a format string, but will be in a future Rust version+help: add a "{}" format string to use the message literally+   |+LL |     panic!("{}", "here's a brace: {");+   |            ^^^^^++warning: Panic message contains a brace+  --> $DIR/panic-brace.rs:6:5+   |+LL |     std::panic!("another one: }");+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+   |+   = note: This message is not used as a format string, but will be in a future Rust version+help: add a "{}" format string to use the message literally+   |+LL |     std::panic!("{}", "another one: }");+   |                 ^^^^^++warning: Panic message contains an unused formatting placeholder+  --> $DIR/panic-brace.rs:7:18+   |+LL |     core::panic!("Hello {}");+   |                  ^^^^^^^^^^+   |+   = note: This message is not used as a format string when given without arguments, but will be in a future Rust version+help: add the missing argument(s)+   |+LL |     core::panic!("Hello {}", argument);+   |                            ^^^^^^^^^^+help: or add a "{}" format string to use the message literally+   |+LL |     core::panic!("{}", "Hello {}");+   |                  ^^^^^++warning: Panic message contains an unused formatting placeholder+  --> $DIR/panic-brace.rs:8:20+   |+LL |     assert!(false, "{:03x} bla");+   |                    ^^^^^^^^^^^^+   |+   = note: This message is not used as a format string when given without arguments, but will be in a future Rust version+help: add the missing argument(s)+   |+LL |     assert!(false, "{:03x} bla", argument);+   |                                ^^^^^^^^^^+help: or add a "{}" format string to use the message literally+   |+LL |     assert!(false, "{}", "{:03x} bla");+   |                    ^^^^^

That would literally output "{{:03x}} bla", with double braces. See my other comment.

m-ou-se

comment created time in 20 hours

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {         mbe::TokenTree::MetaVar(_, name) => format!("${}", name),         mbe::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),         _ => panic!(-            "unexpected mbe::TokenTree::{{Sequence or Delimited}} \+            "{}",+            "unexpected mbe::TokenTree::{Sequence or Delimited} \              in follow set checker"         ),

It'd be properly escaped if it was used as a formatting argument, yes. The problem is that it isn't. With "{{" it literally outputs "{{". panic!() does not use its argument as a format string if there's no additional arguments. That's why I want to add this lint, so it can be fixed in Rust 2021 while giving warnings about incompatible uses (and mistakes) in Rust 2018/2015.

m-ou-se

comment created time in 20 hours

PullRequestReviewEvent

push eventfusion-engineering-forks/rust

Mara Bos

commit sha ea9f47b58ac017807f6207a1875edb36f55f7192

Add cfg(not(test)) to std_panic_macro rustc_diagnostic_item.

view details

push time in a day

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 1d50902b6f46eae0a0965c5cad9dc8eafe78ed41

Fix braces in panic message in test.

view details

push time in a day

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 18ca514a3b0882987afbc9c1dcd18de03740f218

Update mir-opt test output for new assert macro implementation.

view details

push time in a day

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 1d37b385f8bd559daaef7aca55ad0002d1ecf88b

Also apply panic_fmt lint suggestions to debug_assert!().

view details

Mara Bos

commit sha 83bb49f2a29f524ee8238fde6e0f0e82a94e6fb6

Ignore panic_fmt lint in format-args-capture ui test.

view details

push time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 379600c72297deb8541c1a97126974110281695e

Also apply panic_fmt lint suggestions to debug_assert!().

view details

Mara Bos

commit sha ef4a0d506622f395735aabe5ecec8e23a5dabd76

Ignore panic_fmt lint in format-args-capture ui test.

view details

push time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 350188da76e4c74ff37980dd387b3180f0cab384

Ignore panic_fmt lint in macro-comma-behavior-rpass ui test.

view details

push time in 2 days

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let s = sym.as_str();+            let open = s.find('{');+            let close = s[open.unwrap_or(0)..].find('}');+            let looks_like_placeholder = match (open, close) {

Implemented the same check to not see {{ and }} as a formatting placeholder.

m-ou-se

comment created time in 2 days

PullRequestReviewEvent

pull request commentrust-lang/rust

Add lint for panic!("{}")

Clippy already has a lint for panic!("{}") https://rust-lang.github.io/rust-clippy/master/index.html#panic_params (not sure about assert! though..)

Clippy does not warn for panic!("{") though, only if it actually looks like a placeholder. This lint is part of moving towards consistent behaviour for panic!() in Rust 2021, so just a Clippy lint isn't enough.

This lint should be extended later to also provide advice on panic!(123) and other uses that should be discouraged (or removed in Rust 2021).

m-ou-se

comment created time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha b8d460b3a86973c87c8051dcf1ec20f509e4257e

Don't see `{{}}` as placeholder in panic_fmt lint.

view details

Mara Bos

commit sha 8c142a1a5267ae5782f7abc75bb42c7cbd82025b

Fix brace problem in panic message in rustc_expand.

view details

push time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 760357fe7cf7017b5ce58ba644daa97962bd25d5

Don't see `{{}}` as placeholder in panic_fmt lint.

view details

Mara Bos

commit sha d971a8ca36881cf09ed48b9beb8a1eeb6944d491

Fix brace problem in panic message in rustc_expand.

view details

push time in 2 days

pull request commentrust-lang/rust

Add lint for panic!("{}")

Heh, interesting. The CI build is failing, because the lint found a problem in existing Rustc code:

image

Looks like it's working as it should. :)

m-ou-se

comment created time in 2 days

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let s = sym.as_str();+            let open = s.find('{');+            let close = s[open.unwrap_or(0)..].find('}');+            let looks_like_placeholder = match (open, close) {

Clippy does almost the same, except it first removes all occurences of {{ and }}. (It does not check the text between any { and } to see if it might be a valid placeholder.)

m-ou-se

comment created time in 2 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let s = sym.as_str();+            let open = s.find('{');+            let close = s[open.unwrap_or(0)..].find('}');+            let looks_like_placeholder = match (open, close) {

This check is very primitive, and has false positives for things like {{}}. Re-using rustc_parse_format::Parser would be a lot better.

m-ou-se

comment created time in 2 days

PullRequestReviewEvent

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 538b466d0f0d1851bfc996975b57bd70e057746e

Add cfg(not(bootstrap)) on the new rustc_diagnostic_item attributes. The beta compiler doesn't accept rustc_diagnostic_items on macros yet.

view details

push time in 2 days

PR opened rust-lang/rust

Add lint for panic!("{}")

This adds a lint that warns about panic!("{}").

panic!(msg) invocations with a single argument use their argument as panic payload literally, without using it as a format string. The same holds for assert!(expr, msg).

This lints checks if msg is a string literal (after expansion), and warns in case it contained braces. It suggests to insert "{}", to use the message literally, or to add arguments to use it as a format string.

image

This lint is also a good starting point for adding warnings about panic!(not_a_string) later, once panic_any() becomes a stable alternative.

+234 -26

0 comment

9 changed files

pr created time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 2056f25866a7ce901161e66cc0b66e4aedb69955

Test for formating placeholders in panic_fmt lint test.

view details

push time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 49cc6c1f148ace8395aeca25c905596aa8e95f31

Formatting.

view details

push time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha b78f00de4a7698dbc1994afd291f59bb0aa2863c

Improve panic_fmt message for panic!("{}") with a fmt placeholder.

view details

push time in 2 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 495ddfa3963a51dea38b259863c3d0fd84329ce8

Add test for the panic_fmt lint.

view details

push time in 2 days

create barnchfusion-engineering-forks/rust

branch : panic-fmt-lint

created branch time in 2 days

delete branch m-ou-se/bstr

delete branch : utf8-chunk-incomplete

delete time in 2 days

delete branch m-ou-se/bstr

delete branch : to-string-lossy

delete time in 2 days

Pull request review commentBurntSushi/bstr

Make ByteVec::into_string_lossy() more efficient.

 pub trait ByteVec: Sealed {     where         Self: Sized,     {-        let v = self.as_vec();-        if let Ok(allutf8) = v.to_str() {-            return allutf8.to_string();+        match self.as_vec().to_str_lossy() {+            Cow::Borrowed(_) => unsafe { self.into_string_unchecked() },

Thanks for the quick review. Added the comment. :)

m-ou-se

comment created time in 2 days

PullRequestReviewEvent

push eventm-ou-se/bstr

Mara Bos

commit sha 4843b181acf08dfe76593ce9c56ffc81f8d73daa

Add SAFETY comment to into_string_lossy.

view details

push time in 2 days

PR opened rust-lang/rust

Add #[inline] to some functions in core::str.

Almost all str functions already had #[inline].

+12 -0

0 comment

3 changed files

pr created time in 2 days

create barnchfusion-engineering-forks/rust

branch : inline

created branch time in 2 days

PR opened BurntSushi/bstr

Make ByteVec::into_string_lossy() more efficient.

It now re-uses to_str_lossy() (which is more efficient than looping over v.chars() like this did), and does no longer allocate in the case it was already valid utf-8.

+3 -8

0 comment

1 changed file

pr created time in 2 days

create barnchm-ou-se/bstr

branch : to-string-lossy

created branch time in 2 days

pull request commentrust-lang/rust

Fix const core::panic!(non_literal_str).

I cherry-picked your commit into this PR. I'll rebase that once your PR gets merged. Or alternatively: Approving and merging this PR as it is now will merge both changes at once.

m-ou-se

comment created time in 2 days

push eventfusion-engineering-forks/rust

Dylan DPC

commit sha 85e77edc82f8052b865cf35f9aaade2d668ea4f1

Rollup merge of #77371 - camelid:remove-extra-space-in-diagnostic, r=varkor Remove trailing space in error message - Add test for error message - Remove trailing space in error message

view details

bors

commit sha b218b952f800c1160b8b5e764ca651b02d678565

Auto merge of #77381 - Dylan-DPC:rollup-0sr6p5p, r=Dylan-DPC Rollup of 12 pull requests Successful merges: - #76909 (Add Iterator::advance_by and DoubleEndedIterator::advance_back_by) - #77153 (Fix recursive nonterminal expansion during pretty-print/reparse check) - #77202 (Defer Apple SDKROOT detection to link time.) - #77303 (const evaluatable: improve `TooGeneric` handling) - #77305 (move candidate_from_obligation_no_cache) - #77315 (Rename AllocErr to AllocError) - #77319 (Stable hashing: add comments and tests concerning platform-independence) - #77324 (Don't fire `const_item_mutation` lint on writes through a pointer) - #77343 (Validate `rustc_args_required_const`) - #77349 (Update cargo) - #77360 (References to ZSTs may be at arbitrary aligned addresses) - #77371 (Remove trailing space in error message) Failed merges: r? `@ghost`

view details

Carol (Nichols || Goulding)

commit sha 2033eb1495b4a0386a0ab08815769477baf20c89

Write manifest for MAJOR.MINOR channel to enable rustup convenience This connects to https://github.com/rust-lang/rustup/issues/794. It's hard to remember if there have been patch releases for old versions when you'd like to install the latest in a MAJOR.MINOR series. When we're doing a stable release, we write duplicate manifests to `stable`. With this change, only when we're doing a stable release, also write duplicate manifests to `MAJOR.MINOR` to eventually enable rustup (and any other tooling that builds Rust release URLs) to request, say, `1.45` and get `1.45.2` (assuming `1.45.2` is the latest available `1.45` and assuming that we never publish patch releases out of order).

view details

Ivan Tham

commit sha 86e30b605c585f2841dfd4bddb5afb696ab03cb5

Fix typo in vec doc "tries to reserves"

view details

Scott McMurray

commit sha 20202da09e86bd15ffcd0ce22b5ebe8a27ef17a0

Improve the example for ptr::copy Fixes #77220

view details

bors

commit sha 3bbc443cc6657b5df623101f74688ec92e35f35d

Auto merge of #77379 - camelid:improve-wording-crate-resolution-error, r=davidtwco Improve wording for external crate resolution error I think it reads better this way.

view details

David Tolnay

commit sha 17db1cb5d5a864d611e17d6e2466731c3b50a794

Bypass const_item_mutation if const's type has Drop impl

view details

David Tolnay

commit sha 0dfe7b6434f6aabbe9673a891ba74c7c7922661d

Add justification of the destructor filter

view details

David Tolnay

commit sha bb760b53bf7f9593c09a03e5dea28ef5f31065d7

Simplify defid destructor check

view details

David Tolnay

commit sha 0f6284c88d521904bb0ada34325a0372a1ea26f1

Add test of const item mutation with Drop impl

view details

David Tolnay

commit sha 352ce8b29990d62465675b46b42a695a4206d5be

Test a type with drop glue but no Drop impl

view details

David Tolnay

commit sha 41baa090ad1c40a7fc96f96664543ce4c26746c2

Skip dropck::check_drop_impl in is_const_item_without_destructor adt_destructor by default also validates the Drop impl using dropck::check_drop_impl, which contains an expect_local(). This leads to ICE in check_const_item_mutation if the const's type is not a local type. thread 'rustc' panicked at 'DefId::expect_local: `DefId(5:4805 ~ alloc[d7e9]::vec::{impl#50})` isn't local', compiler/rustc_span/src/def_id.rs:174:43 stack backtrace: 0: rust_begin_unwind 1: rustc_span::def_id::DefId::expect_local::{{closure}} 2: rustc_typeck::check::dropck::check_drop_impl 3: rustc_middle::ty::util::<impl rustc_middle::ty::context::TyCtxt>::calculate_dtor::{{closure}} 4: rustc_middle::ty::trait_def::<impl rustc_middle::ty::context::TyCtxt>::for_each_relevant_impl 5: rustc_middle::ty::util::<impl rustc_middle::ty::context::TyCtxt>::calculate_dtor 6: rustc_typeck::check::adt_destructor 7: rustc_middle::ty::query::<impl rustc_query_system::query::config::QueryAccessors<rustc_middle::ty::context::TyCtxt> for rustc_middle::ty::query::queries::adt_destructor>::compute 8: rustc_query_system::dep_graph::graph::DepGraph<K>::with_task_impl 9: rustc_query_system::query::plumbing::get_query_impl 10: rustc_mir::transform::check_const_item_mutation::ConstMutationChecker::is_const_item_without_destructor

view details

Yuki Okushi

commit sha c1e17f56ea1d3cc64cd7d1be6fc2557d0fd65f06

Add a regression test for issue-66501

view details

Yuki Okushi

commit sha 8631e1c57504624824add1b059d12cdc86cdd87c

Add a regression test for issue-68951

view details

Yuki Okushi

commit sha 50ffd6b7cbdf6baedbd3a22f4ea79ebdf7c48af9

Add a regression test for issue-72565

view details

Yuki Okushi

commit sha d4fdf6e7542941ab8d5b0d43f9c5bc0b278f638d

Add a regression test for issue-74244

view details

Yuki Okushi

commit sha 38f460f8669de8ee0d975ec89f06e89a5849ab65

Add a regression test for issue-75299

view details

David Tolnay

commit sha eef5104c53114bf9a074fe8d83cfd782bd78652d

Add test of VEC.push on a const

view details

David Tolnay

commit sha 75c2fdf34a5384627db9ba240c5dcc0723aea763

Warn on method call mutating const, even if it has destructor

view details

Joshua Nelson

commit sha 8164218181d8fc22a7247a686ec9af9d61f70d44

Fix some clippy issues Found while working on https://github.com/rust-lang/rust/pull/77351; these are just the ones that could be fixed automatically.

view details

push time in 2 days

PR opened rust-lang/rust

Fix const core::panic!(non_literal_str).

Invocations of core::panic!(x) where x is not a string literal expand to panic!("{}", x), which is not understood by the const panic logic right now. This adds panic_str as a lang item, and modifies the const eval implementation to hook into this item as well.

This fixes the issue mentioned here: https://github.com/rust-lang/rust/issues/51999#issuecomment-687604248

r? @RalfJung

@rustbot modify labels: +A-const-eval

+15 -3

0 comment

6 changed files

pr created time in 2 days

push eventfusion-engineering-forks/rust

Dylan DPC

commit sha cc1513b860900f87a1077193f0a1dd4e1beeb577

Rollup merge of #77360 - oli-obk:zst_const_pat_regression, r=RalfJung References to ZSTs may be at arbitrary aligned addresses fixes #77320 r? @RalfJung

view details

Dylan DPC

commit sha 85e77edc82f8052b865cf35f9aaade2d668ea4f1

Rollup merge of #77371 - camelid:remove-extra-space-in-diagnostic, r=varkor Remove trailing space in error message - Add test for error message - Remove trailing space in error message

view details

bors

commit sha b218b952f800c1160b8b5e764ca651b02d678565

Auto merge of #77381 - Dylan-DPC:rollup-0sr6p5p, r=Dylan-DPC Rollup of 12 pull requests Successful merges: - #76909 (Add Iterator::advance_by and DoubleEndedIterator::advance_back_by) - #77153 (Fix recursive nonterminal expansion during pretty-print/reparse check) - #77202 (Defer Apple SDKROOT detection to link time.) - #77303 (const evaluatable: improve `TooGeneric` handling) - #77305 (move candidate_from_obligation_no_cache) - #77315 (Rename AllocErr to AllocError) - #77319 (Stable hashing: add comments and tests concerning platform-independence) - #77324 (Don't fire `const_item_mutation` lint on writes through a pointer) - #77343 (Validate `rustc_args_required_const`) - #77349 (Update cargo) - #77360 (References to ZSTs may be at arbitrary aligned addresses) - #77371 (Remove trailing space in error message) Failed merges: r? `@ghost`

view details

Carol (Nichols || Goulding)

commit sha 2033eb1495b4a0386a0ab08815769477baf20c89

Write manifest for MAJOR.MINOR channel to enable rustup convenience This connects to https://github.com/rust-lang/rustup/issues/794. It's hard to remember if there have been patch releases for old versions when you'd like to install the latest in a MAJOR.MINOR series. When we're doing a stable release, we write duplicate manifests to `stable`. With this change, only when we're doing a stable release, also write duplicate manifests to `MAJOR.MINOR` to eventually enable rustup (and any other tooling that builds Rust release URLs) to request, say, `1.45` and get `1.45.2` (assuming `1.45.2` is the latest available `1.45` and assuming that we never publish patch releases out of order).

view details

Ivan Tham

commit sha 86e30b605c585f2841dfd4bddb5afb696ab03cb5

Fix typo in vec doc "tries to reserves"

view details

Scott McMurray

commit sha 20202da09e86bd15ffcd0ce22b5ebe8a27ef17a0

Improve the example for ptr::copy Fixes #77220

view details

bors

commit sha 3bbc443cc6657b5df623101f74688ec92e35f35d

Auto merge of #77379 - camelid:improve-wording-crate-resolution-error, r=davidtwco Improve wording for external crate resolution error I think it reads better this way.

view details

David Tolnay

commit sha 17db1cb5d5a864d611e17d6e2466731c3b50a794

Bypass const_item_mutation if const's type has Drop impl

view details

David Tolnay

commit sha 0dfe7b6434f6aabbe9673a891ba74c7c7922661d

Add justification of the destructor filter

view details

David Tolnay

commit sha bb760b53bf7f9593c09a03e5dea28ef5f31065d7

Simplify defid destructor check

view details

David Tolnay

commit sha 0f6284c88d521904bb0ada34325a0372a1ea26f1

Add test of const item mutation with Drop impl

view details

David Tolnay

commit sha 352ce8b29990d62465675b46b42a695a4206d5be

Test a type with drop glue but no Drop impl

view details

David Tolnay

commit sha 41baa090ad1c40a7fc96f96664543ce4c26746c2

Skip dropck::check_drop_impl in is_const_item_without_destructor adt_destructor by default also validates the Drop impl using dropck::check_drop_impl, which contains an expect_local(). This leads to ICE in check_const_item_mutation if the const's type is not a local type. thread 'rustc' panicked at 'DefId::expect_local: `DefId(5:4805 ~ alloc[d7e9]::vec::{impl#50})` isn't local', compiler/rustc_span/src/def_id.rs:174:43 stack backtrace: 0: rust_begin_unwind 1: rustc_span::def_id::DefId::expect_local::{{closure}} 2: rustc_typeck::check::dropck::check_drop_impl 3: rustc_middle::ty::util::<impl rustc_middle::ty::context::TyCtxt>::calculate_dtor::{{closure}} 4: rustc_middle::ty::trait_def::<impl rustc_middle::ty::context::TyCtxt>::for_each_relevant_impl 5: rustc_middle::ty::util::<impl rustc_middle::ty::context::TyCtxt>::calculate_dtor 6: rustc_typeck::check::adt_destructor 7: rustc_middle::ty::query::<impl rustc_query_system::query::config::QueryAccessors<rustc_middle::ty::context::TyCtxt> for rustc_middle::ty::query::queries::adt_destructor>::compute 8: rustc_query_system::dep_graph::graph::DepGraph<K>::with_task_impl 9: rustc_query_system::query::plumbing::get_query_impl 10: rustc_mir::transform::check_const_item_mutation::ConstMutationChecker::is_const_item_without_destructor

view details

Yuki Okushi

commit sha c1e17f56ea1d3cc64cd7d1be6fc2557d0fd65f06

Add a regression test for issue-66501

view details

Yuki Okushi

commit sha 8631e1c57504624824add1b059d12cdc86cdd87c

Add a regression test for issue-68951

view details

Yuki Okushi

commit sha 50ffd6b7cbdf6baedbd3a22f4ea79ebdf7c48af9

Add a regression test for issue-72565

view details

Yuki Okushi

commit sha d4fdf6e7542941ab8d5b0d43f9c5bc0b278f638d

Add a regression test for issue-74244

view details

Yuki Okushi

commit sha 38f460f8669de8ee0d975ec89f06e89a5849ab65

Add a regression test for issue-75299

view details

David Tolnay

commit sha eef5104c53114bf9a074fe8d83cfd782bd78652d

Add test of VEC.push on a const

view details

David Tolnay

commit sha 75c2fdf34a5384627db9ba240c5dcc0723aea763

Warn on method call mutating const, even if it has destructor

view details

push time in 2 days

fork m-ou-se/rfcs

RFCs for changes to Rust

https://rust-lang.github.io/rfcs/

fork in 3 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 0b062887db9be8fe05791411dd08ca35683cedc8

Remove shrink_to_fit from default ToString::to_string implementation. Co-authored-by: scottmcm <scottmcm@users.noreply.github.com>

view details

push time in 4 days

pull request commentrust-lang/rust

Remove shrink_to_fit from default ToString::to_string implementation.

image

That is looking good!

m-ou-se

comment created time in 4 days

pull request commentrust-lang/rust

Vxworks / Unix deduplication

@rustbot modify labels: +S-waiting-on-review -S-waiting-on-author

m-ou-se

comment created time in 4 days

push eventfusion-engineering-forks/rust

Mateusz Mikuła

commit sha 0ad3da06843089c0bf10d6caa3fbbc72fa67787a

Enable ASLR for windows-gnu

view details

Nathan West

commit sha a02014280586b53997622c501db00398376967a8

Refactor io/buffered.rs into submodules

view details

Nathan West

commit sha 96229f02402e82914ec6100b28ad2cbdd273a0d4

move buffered.rs to mod.rs

view details

Nathan West

commit sha 6d75cdfc9ed9e6987bd23add6cf3954d2499dce2

Added updated compiler diagnostic

view details

Amjad Alsharafi

commit sha da700cba08a2b194d19e63d3c51ebadce96fe46b

Stabilize move_ref_pattern

view details

Amjad Alsharafi

commit sha afb9eeb1b9ea16ca65e38673a0ef3e7be81d7252

Disabled error `E0007` from rustc_error_codes

view details

Nathan West

commit sha c4280af8285c61b367a87c8f6eef9876011a8150

Retry fix error reporting suggestions

view details

Aaron Hill

commit sha cfe07cd42a92610219d6ffc1ae5eefef42f5254a

Use llvm::computeLTOCacheKey to determine post-ThinLTO CGU reuse During incremental ThinLTO compilation, we attempt to re-use the optimized (post-ThinLTO) bitcode file for a module if it is 'safe' to do so. Up until now, 'safe' has meant that the set of modules that our current modules imports from/exports to is unchanged from the previous compilation session. See PR #67020 and PR #71131 for more details. However, this turns out be insufficient to guarantee that it's safe to reuse the post-LTO module (i.e. that optimizing the pre-LTO module would produce the same result). When LLVM optimizes a module during ThinLTO, it may look at other information from the 'module index', such as whether a (non-imported!) global variable is used. If this information changes between compilation runs, we may end up re-using an optimized module that (for example) had dead-code elimination run on a function that is now used by another module. Fortunately, LLVM implements its own ThinLTO module cache, which is used when ThinLTO is performed by a linker plugin (e.g. when clang is used to compile a C proect). Using this cache directly would require extensive refactoring of our code - but fortunately for us, LLVM provides a function that does exactly what we need. The function `llvm::computeLTOCacheKey` is used to compute a SHA-1 hash from all data that might influence the result of ThinLTO on a module. In addition to the module imports/exports that we manually track, it also hashes information about global variables (e.g. their liveness) which might be used during optimization. By using this function, we shouldn't have to worry about new LLVM passes breaking our module re-use behavior. In LLVM, the output of this function forms part of the filename used to store the post-ThinLTO module. To keep our current filename structure intact, this PR just writes out the mapping 'CGU name -> Hash' to a file. To determine if a post-LTO module should be reused, we compare hashes from the previous session. This should unblock PR #75199 - by sheer chance, it seems to have hit this issue due to the particular CGU partitioning and optimization decisions that end up getting made.

view details

follower

commit sha e4943ac81163db364bd8c8ad1ea9c65b4adabcd3

Link to documentation-specific guidelines. Changed because it's not obvious how to get from the previously used URL to the documentation-specific content. This is partly because the original URL was previously changed to point to different content: * https://github.com/rust-lang/rust/pull/74037/files#diff-242481015141f373dcb178e93cffa850L88 * https://github.com/rust-lang/rust/commit/3f6928f1f6eff367e6ddbfb63ebc5e568ffe0eb1#diff-6a3371457528722a734f3c51d9238c13L12

view details

Arlo Siemsen

commit sha 0a4dc8bc161c68320a60a6bde525adae258b6252

Adds a GitHub Actions CI build for aarch64-pc-windows-msvc via cross-compilation on an x86_64 host. This promotes aarch64-pc-windows-msvc from a Tier 2 Compilation Target (std) to a Tier 2 Development Platform (std+rustc+cargo+tools). Fixes #72881

view details

Lzu Tao

commit sha 446f86e370884df01cbbacc584d67859c6c2a10b

Remove useless stringify

view details

Jake Goulding

commit sha 225ec813a9b25cdf94811d5b6c5207848cfef829

Add a cross-compiling aarch64-apple-darwin CI builder

view details

Jake Goulding

commit sha 2fe271e4c2b5f89108314177348d7732f533582f

Move aarch64-apple-darwin to tier 2 Drive-by fixes to update the naming of "OSX" [sic] to "macOS".

view details

Waffle

commit sha 0b923d3ca0b7f5a1a611564ee48c1e92f896d79e

add `str::{Split,RSplit}::as_str` methods This commit introduses 2 methods under "str_split_as_str" gate with common signature of `&Split<'a, _> -> &'a str'`. Both of them work like `Chars::as_str` - return unyield part of the inner string.

view details

Waffle

commit sha 4747215d778abd9f280202d07f279fdeaea519f8

add `str::{SplitN, RSplitN, SplitTerminator, RSplitTerminator}::as_str` methods This commit entroduce 4 methods smililar to `Split::as_str` all under the same gate "str_split_as_str".

view details

Waffle

commit sha 076514c8a82591547116a7a2212c4de4bdc56f76

add `str::SplitInclusive::as_str` method This commit entroduces `core::str::SplitInclusive::as_str` method similar to `core::str::Split::as_str`, but under different gate - "str_split_inclusive_as_str" (this is done so because `SplitInclusive` is itself unstable).

view details

Lzu Tao

commit sha 6cb062dacfed8e647361bc94694c7177beb17390

mips32: Add f64 hard-float support co-authored-by: Amanieu <amanieu@gmail.com>

view details

Lzu Tao

commit sha 79f477bb1fe81385aebde628e5a3f5c9168b24e0

Add asm! support for mips64

view details

Lzu Tao

commit sha 4d570fb45e7650f274853a2f47f86d17c2aa0784

Removes reg aliases since there are many ABIs: o32/n32/n64

view details

Bastian Kauschke

commit sha 536674fb69ea161f50f68f3fdb65950feffd92a4

cleanup WithOptConstParam queries

view details

push time in 4 days

create barnchfusion-engineering-forks/rust

branch : to-string-no-shrink

created branch time in 5 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha df95dcebf5f98cefdc60c9b9d818fb285ac07d5b

Add missing `mut`. Co-authored-by: David Tolnay <dtolnay@gmail.com>

view details

push time in 5 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha b9db54b3a238124b19856a03eccef7ae3ae86d91

Bump nzint_try_from_nzint_conv stabilization version to 1.49. Missed the 1.48 cycle.

view details

push time in 5 days

pull request commentrust-lang/rust

revise Hermit's mutex interface to support the behaviour of StaticMutex

@m-ou-se When should I use type MovableMutex = Box<Mutex>;?

A Box should only be used there if a Mutex object may not be moved (while not borrowed/used), e.g. because it might have internal pointers. Posix pthread_mutex_t needs it. Most Mutex implementations don't need it and should use type MovableMutex = Mutex;.

If I don't used a boxed type, the kernel triggers some exceptions because a few data types aren't aligned.

That sounds like a type (Mutex, SpinLock, or PriorityQueue?) is missing a #[repr(align(..))].

stlankes

comment created time in 6 days

push eventfusion-engineering-forks/rust

Matt Brubeck

commit sha b4b383981abac7ca8aa180c7ae3e28876615b887

Add PartialEq impls for Vec <-> slice

view details

Mateusz Mikuła

commit sha 0ad3da06843089c0bf10d6caa3fbbc72fa67787a

Enable ASLR for windows-gnu

view details

Tim Nielens

commit sha 390a13b06c79d4177b829097b06453e38188081f

needless-lifetime - fix nested elision site FPs

view details

Tim Nielens

commit sha a60e5de90c7370d4fb3e6561d3cb55495cda2e2a

needless-lifetime / nested elision sites / PR remarks

view details

Tim Nielens

commit sha c8e9e52303da6dff4bc5cc4db3021d608fca6c70

needless-lifetime / add test cases for nested elision sites

view details

Takayuki Nakata

commit sha 1778a1ec4615a42a8ba9497006b07859186c08a1

Restrict `same_item_push` to suppress false positives It emits a lint when the pushed item is a literal, a constant and an immutable binding that are initialized with those.

view details

Takayuki Nakata

commit sha 0117ea2b016133145f9e02e27421ac3672b42f57

Refactoring: use inner function

view details

Takayuki Nakata

commit sha b80576fba633e1fc214c9f6900d7ca3424bda6d0

Some refactoring

view details

Takayuki Nakata

commit sha 14faebe20ea82392f393c3ff5efaab7250e51989

Add some tests to `same_item_push` Add tests in which the variable is initialized with a match expression and function call

view details

Takayuki Nakata

commit sha 2972ad3ef661071531a61ec8999b668a6b734b74

Refactoring: tests in `same_item_push`

view details

Takayuki Nakata

commit sha 730ca457f580247667ed0cd5965bc08752ebc0b3

Address `items_after_statement`

view details

Dylan MacKenzie

commit sha 72b402ed38f0c71461038aef8a49a02e49280788

Add pass names to some common dataflow analyses

view details

Aaron Hill

commit sha cfe07cd42a92610219d6ffc1ae5eefef42f5254a

Use llvm::computeLTOCacheKey to determine post-ThinLTO CGU reuse During incremental ThinLTO compilation, we attempt to re-use the optimized (post-ThinLTO) bitcode file for a module if it is 'safe' to do so. Up until now, 'safe' has meant that the set of modules that our current modules imports from/exports to is unchanged from the previous compilation session. See PR #67020 and PR #71131 for more details. However, this turns out be insufficient to guarantee that it's safe to reuse the post-LTO module (i.e. that optimizing the pre-LTO module would produce the same result). When LLVM optimizes a module during ThinLTO, it may look at other information from the 'module index', such as whether a (non-imported!) global variable is used. If this information changes between compilation runs, we may end up re-using an optimized module that (for example) had dead-code elimination run on a function that is now used by another module. Fortunately, LLVM implements its own ThinLTO module cache, which is used when ThinLTO is performed by a linker plugin (e.g. when clang is used to compile a C proect). Using this cache directly would require extensive refactoring of our code - but fortunately for us, LLVM provides a function that does exactly what we need. The function `llvm::computeLTOCacheKey` is used to compute a SHA-1 hash from all data that might influence the result of ThinLTO on a module. In addition to the module imports/exports that we manually track, it also hashes information about global variables (e.g. their liveness) which might be used during optimization. By using this function, we shouldn't have to worry about new LLVM passes breaking our module re-use behavior. In LLVM, the output of this function forms part of the filename used to store the post-ThinLTO module. To keep our current filename structure intact, this PR just writes out the mapping 'CGU name -> Hash' to a file. To determine if a post-LTO module should be reused, we compare hashes from the previous session. This should unblock PR #75199 - by sheer chance, it seems to have hit this issue due to the particular CGU partitioning and optimization decisions that end up getting made.

view details

Hanif Bin Ariffin

commit sha dc655b28424549a4775bc2e8c9021d44482bccb1

Prevent stackoverflow

view details

rail

commit sha 5e393c7747d081c45414060f81016e9ea3cb961f

Fix a FP in `explicit_counter_loop` Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented, adjust the test so that counters are incremented at the end of the loop and add the test for this false positive.

view details

Eduardo Broto

commit sha 3e294b22a43be349262405715cf4885296c284ba

Revert "or_fn_call: ignore nullary associated const fns" This reverts commit 7a66e6502dc3c7085b3f4078c01d4957d96175ed.

view details

Eduardo Broto

commit sha ce83d8d4d1b28e73888a616d3ffbf19c6a620588

Revert "Avoid or_fun_call for const_fn with no args" This reverts commit 5d66bd7bb3fd701d70ec11217e3f89fabe5cb0a7.

view details

Eduardo Broto

commit sha 9365660a2fc57210996df733efe468019c671b2f

unnecessary sort by: avoid dereferencing closure param

view details

flip1995

commit sha d1f9cad102b5686f2b827f3c62a02dfe419128a6

Merge commit 'e636b88aa180e8cab9e28802aac90adbc984234d' into clippyup

view details

bors

commit sha 019c0d5f7f90f959ff92684a04b0d766b22527a5

Auto merge of #6076 - rail-rain:fix_fp_explicit_counter_loop, r=matthiaskrgr Fix a FP in `explicit_counter_loop` Fixes #4677 and #6074 Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented, adjust the test so that counters are incremented at the end of the loop and add the test for this false positive. --- changelog: Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented

view details

push time in 6 days

pull request commentrust-lang/rust

Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn).

Ah, thanks! Was just about to post a comment because I didn't understand what failed.

By the way, looks like all the relevant platforms for this PR passed their tests, so rollup should be fine now. ^^

m-ou-se

comment created time in 7 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha af414dc274d30bc3f4aea1d396ac2663e0c08c56

Deny unsafe_op_in_unsafe_fn for unsupported/common.rs through sys/wasm too.

view details

push time in 7 days

pull request commentrust-lang/rust

Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn).

@rustbot modify labels: +S-waiting-on-review -S-waiting-on-author

Checked locally that std now compiles for wasm32-unknown-unknown. I only applied the attribute to the one mondule where it was necessary. Looks like sys/wasm will be applying the attribute to everything soon as well: https://github.com/rust-lang/rust/pull/74477

m-ou-se

comment created time in 7 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha f92b36a75e885b72cfbd7ee61b816067ba364852

Deny unsafe_op_in_unsafe_fn for unsupported/common.rs through sys/wasm too.

view details

push time in 7 days

pull request commentrust-lang/rust

Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn).

Ah, apparently sys/wasm takes some stuff directly from sys/unsupported. Then sys/unsupported/mod.rs gets bypassed and the deny(unsafe_op_in_unsafe_fn) attribute does not apply.

m-ou-se

comment created time in 7 days

pull request commentrust-lang/rust

Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn).

@rustbot modify labels: +S-waiting-on-review -S-waiting-on-author

m-ou-se

comment created time in 7 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha b26aa5d97353bed9ace56d8f247c88b2f9d4f8fd

Add note about using cells in the locks on the 'unsupported' platform.

view details

push time in 7 days

pull request commentrust-lang/rust

Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn).

Sure. Will add a comment.

It's obviously untrue...

Well they're safe to share between all the threads your program can have on those platforms: just the one main thread. ^^'

Without Sync, you couldn't use one in a static like on other platforms.

m-ou-se

comment created time in 7 days

Pull request review commentrust-lang/rust

Use Pin to pin RWLock.

 impl<'a, T: ?Sized> Pin<&'a mut T> {     } } +impl<T: ?Sized> Pin<&'static T> {+    /// Get a pinned reference from a static reference.+    ///+    /// This is safe, because the `'static` lifetime guarantees the data will+    /// never be moved.

Thanks!

This is part of #77726. Applied the change there.

m-ou-se

comment created time in 7 days

PullRequestReviewEvent

push eventfusion-engineering-forks/rust

Mara Bos

commit sha f83446b836900ce9afbaa0816a5b4feda654b51e

Reword safety guarantee of Pin::static_{ref,mut}. Co-authored-by: Peter Todd <pete@petertodd.org>

view details

push time in 7 days

pull request commentrust-lang/rust

revise Hermit's mutex interface to support the behaviour of StaticMutex

Does std compile for hermit now? Because it looks like type MovableMutex = Box<Mutex>; (or type MovableMutex = Mutex;) is missing for this platform in sys/hermit/mutex.rs.

stlankes

comment created time in 8 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha f7d0dd02d905f940638d775d9ad276d81b12eda5

Use PhantomPinned in RWLock to enforce Pin usage.

view details

push time in 8 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha de2db6ddaed32748f2d8185b6a1dc60726614a90

Use PhantomPinned in RWLock to enforce Pin usage.

view details

push time in 8 days

PR opened rust-lang/rust

Use Pin to pin RWLock.

Use Pin to guarantee the no-moving requirement of sys_common::RWLock.

This makes some things safe that were unsafe before.

sys_common::RWLock::destroy is now changed to a regular (safe) Drop implementation, because it no longer has unsafe requirements.

This change leaves the unsafe sys::RwLock untouched. Those implementations should probably also use a Pin to make them a bit safer, and move their destroy() to Drop. But that can be a later change.


r? @withoutboats

Following our conversation on Zulip, this is a better example where Pin<&Self> is useful.

(This includes #77726 as a merge commit for now.)

+78 -67

0 comment

5 changed files

pr created time in 8 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 3090cecceffe9f3a13384d0fa7582c348cb7b672

Use Pin to pin RwLock.

view details

push time in 8 days

create barnchfusion-engineering-forks/rust

branch : pin-rwlock

created branch time in 8 days

push eventfusion-engineering-forks/rust

Mara Bos

commit sha 104c0f0194177442ff16cf14907a96d2f8d200dd

Rename Pin::new_static to Pin::static_ref.

view details

Mara Bos

commit sha 2c71f682d74d13ae6673dc701a9bb3a0562f57c0

Add Pin::static_mut.

view details

push time in 8 days

pull request commentrust-lang/rust

Enforce no-move rule of ReentrantMutex using Pin and fix UB in stdio

Oh and also: In ReentrantMutex::init I now take a mutable reference (Pin<&mut Self>), to make sure it hasn't been shared yet. It wouldn't be possible to take a &'static mut there, because then it's forever mutably (re)borrowed.

m-ou-se

comment created time in 8 days

pull request commentrust-lang/rust

Enforce no-move rule of ReentrantMutex using Pin and fix UB in stdio

Another option for this API, which seems more easy to make public, might be to use MaybeUninit:

That's exactly what I had in my first version (before pushing) ^^. I can probably find it somewhere in my git reflog if you really want that one. Though, I found it a bit tricky to properly explain the safety requirements that version, so I changed it to the one with Pin instead. This Pin version is way less dangerous, as it can't be misused from the outside without unsafe: This get_or_init_pin is a safe function.

Do you think there's an argument for having the extra flexibility of Pin?

So indeed, this ReentrantMutex is only used right now with a static lifetime (since very recently: #77154), so we could turn this into a StaticReentrantMutex and do the same as for sys_common::StaticMutex: Use the 'static lifetime for the 'don't move me'-guarantee: #77648

However, it does restrict any future usage of this ReentrantMutex to static ones. I like the Pin version better, because then you can also Box::pin it, which is another proper way to make the 'no move' guarantee.

And regardless of ReentrantMutex, I'd also really like to apply the Pin logic to all the sys::Mutex, sys::RWLock, sys::ReentrantMutex and sys::Condvar implementations that need it. Those are extremely unsafe to use now, and Pin could guarantee one of the trickiest safety guarantees to get wrong for them. (Even the unit tests had it wrong.) So even if committing to a 'static-only sys_common::ReentrantMutex, it'd still be good to think about using Pin for these kind of unmovable objects.

Note that a sys_common::ReentrantMutex cannot be created with a const fn, as it requires .init() before any use. So by also requiring 'static, the ways it can be made and used is very limited. It can't be used as a static because it has no const constructor, but it also can't be used in many other ways because of the static lifetime. It'd restrict it basically to a static SyncOnceCell (or a leaked box).

m-ou-se

comment created time in 8 days

issue commentjamesmunns/anachro

Combined request-go line idea

But if REQ is low in idle, the output of the AND port will be low, enabling the buffer and enabling the GO signal.

m-ou-se

comment created time in 8 days

issue commentjamesmunns/anachro

Combined request-go line idea

in floating state

How could that work? How would the arbitrator tell if there's an incoming request if the pin is floating? It'll just randomly measure high or low if that pin is floating. Same for the nCS pin.

m-ou-se

comment created time in 8 days

issue commentjamesmunns/anachro

Combined request-go line idea

That wouldn't work: With this AND port, the nGO pin would be low whenever the REQ is low. Meaning the communication is enabled while the device isn't even asking to communicate.

In my schematic, I tried to minimize both the number of pins that have to go the device (the lines that cross the leftmost blue line: just one go/req line next to the three spi lines), and the amount of extra components needed on the device (just one resistor).

m-ou-se

comment created time in 8 days

issue openedjamesmunns/anachro

Combined request-go line idea

Just some idea: With a few resistors, transistors, and a diode, it would be possible to use a single GPIO pin on the arbitrator to get a transfer request from a device, and accept that request using the same pin, while also controlling the buffer enable line and the chip select of the arbitrator:

image

created time in 9 days

pull request commentrust-lang/rust

Avoid SeqCst or static mut in mach_timebase_info and QueryPerformanceFrequency caches

:broken_heart: Test failed - checks-actions

This was a spurious error:

warning: spurious network error (2 tries remaining): failed to get 200 response from `https://crates.io/api/v1/crates/crossbeam-utils/0.6.6/download`, got 503
warning: spurious network error (1 tries remaining): failed to get 200 response from `https://crates.io/api/v1/crates/crossbeam-utils/0.6.6/download`, got 503
error: failed to download from `https://crates.io/api/v1/crates/crossbeam-utils/0.6.6/download`

Caused by:
  failed to get 200 response from `https://crates.io/api/v1/crates/crossbeam-utils/0.6.6/download`, got 503
thomcc

comment created time in 9 days

Pull request review commentrust-lang/rust

Enforce no-move rule of ReentrantMutex using Pin and fix UB in stdio

 impl<T> Drop for ReentrantMutex<T> {     } } -impl<T: fmt::Debug + 'static> fmt::Debug for ReentrantMutex<T> {

I removed the Debug implementation for ReentrantMutex because it wasn't used anywhere and it doesn't enforce the pinnedness.

m-ou-se

comment created time in 10 days

PullRequestReviewEvent

PR opened rust-lang/rust

Enforce no-move rule of ReentrantMutex using Pin and fix UB in stdio

A sys_common::ReentrantMutex may not be moved after initializing it with .init(). This was not enforced, but only stated as a requirement in the comments on the unsafe functions. This change enforces this no-moving rule using Pin, by changing &self to a Pin in the init() and lock() functions.

This uncovered a bug I introduced in #77154: stdio.rs (the only user of ReentrantMutex) called init() on its ReentrantMutexes while constructing them in the intializer of SyncOnceCell::get_or_init, which would move them afterwards. Interestingly, the ReentrantMutex unit tests already had the same bug, so this invalid usage has been tested on all (CI-tested) platforms for a long time. Apparently this doesn't break badly on any of the major platforms, but it does break the rules.*

To be able to keep using SyncOnceCell, this adds a SyncOnceCell::get_or_init_pin function, which makes it possible to work with pinned values inside a (pinned) SyncOnceCell. Whether this function should be public or not and what its exact behaviour and interface should be if it would be public is something I'd like to leave for a separate issue or PR. In this PR, this function is internal-only and marked with pub(crate).


* That bug is now included in 1.48, while this patch can only make it to 1.49. We should consider the implications of 1.48 shipping with a wrong usage of pthread_mutex_t / CRITICAL_SECTION / .. which technically invokes UB according to their specification. The risk is very low, considering the objects are not 'used' (locked) before the move, and the ReentrantMutex unit tests have verified this works fine in practice.


This depends on #77726, which is for now included in this PR with a merge commit. I'll rebase this once that PR is merged. Until then, this is a draft PR.

@rustbot modify labels: +T-libs

+143 -82

0 comment

6 changed files

pr created time in 10 days

more