Cargo refused to format the code. Is it by design?

Cargo refuses to format the following code:

macro_rules! demo {
    (format: $fmt:expr, $($args:expr),*)=>{println!($fmt, $($args),*)}
}

fn main() {
    demo!(format:                    "Hello {}", "world!");
}

Is it by design?

the short answer is: it is expected.

correctly formatting every macros is challenging because they can contain arbitrary tokens which can be potentially invalid rust syntax, so rustfmt will try its best to parse and format macros, but it is not guaranteed to work.

Not sure why, but the following code couldn't be formatted as well:

use std::path::Path;

fn main() {
    (0..1).for_each(|_| {
        println!(
                "A very long text A very long text A very long text A very long text A very long text A very long text A very long text : {}",
                                    Path::new("foo.txt").display()
            ) // This wouldn't be formatted.
    });
    println!(
        "A very long text A very long text A very long text A very long text A very long text A very long text A very long text : {}",
        Path::new("foo.txt").display()
    ); // But this will.
}

This code doesn't have any macros. Is it by design as well?

Println is a macro.

My fault. But even if println! is a macro, the following code would be formatted as well:

    println!(
        "A very long text A very long text A very long text A very long text A very long text A very long text A very long text : {}",
        Path::new("foo.txt").display()
    );

But the following wouldn't:

    (0..1).for_each(|_| {
        println!(
                "A very long text A very long text A very long text A very long text A very long text A very long text A very long text : {}",
                                    Path::new("foo.txt").display()
            )
    });

although macros generally are not guaranteed to work, usually standard library macros are recognized.

but there are many edge cases with overly long strings, I think your example is related to e.g. these reports: rust-lang/rustfmt/issues/6735, rust-lang/rustfmt/issues/6870, but the main tracking issue is rust-lang/rustfmt/issues/3863 for the long string problem.

if you are on nightly, you can try enable format_strings = true which allows rustfmt to break up long strings into shorter pieces.

Cargo doesn't format anything, it just call a format utility.

If the problem is the default line length at which fmt breaks lines, you can increase it with a rustfmt.toml file, e.g.:

max_width = 200