What does the syntax "~[ * * * ]" mean in the rust reference?

I wonder how the grammar in the rust reference is used to denote the literal string

"abc"

however, I cannot find out the explicit one in the reference. The only possible one that is supposed to be is:

STRING_LITERAL :

  • ~[" \ IsolatedCR]

However, I'm not sure. What does this syntax mean in the rust reference? Where and how does the rust reference introduce this syntax?

The notation page at the beginning explains the notation. In this case,

Notation Examples Meaning
~[ ] ~[b B] Any characters, except those listed

So in the string grammar

STRING_LITERAL :
  " (
    ~[" \ IsolatedCR]
    | QUOTE_ESCAPE
    | ASCII_ESCAPE
    | UNICODE_ESCAPE
    | STRING_CONTINUE
  )* " SUFFIX?

this means that the contents of a string literal between " can be any number of

  • any character other than ", \, or an IsolatedCR;
  • a QUOTE_ESCAPE;
  • an ASCII_ESCAPE;
  • a UNICODE_ESCAPE; or
  • a STRING_CONTINUE.

Thanks. Another question is: what is IsolatedCR? I didn't find its introduction.

It's introduced as part of Comments syntax:

IsolatedCR :
A \r not followed by a \n

1 Like

I wrote a program to generate such a invalid string

fn main() {
	let s = "fn main(){
       let s = \"\rabc\";
	}";
	std::fs::write("./out.rs", s).unwrap();
}

If we use rustc out.rs, then the compiler will emit the error, however, if we use cargo run to run the resulting code, there is no error. What's the reason?

Not sure how do you do that. cargo run by default compiles and runs the binary crate rooted at src/main.rs, how did you direct it to use out.rs?

1 Like

That's my oversight. Paste the code from out.rs to main.rs in vscode will change \r to \n, and saving the code in vscode editor also does. If directly copy out.rs into src directory and rename its name to main.rs, the compiler will emit the error

error: bare CR not allowed in string, use \r instead

Note that it is not possible that rustc emits an error while cargo compiles happily. Cargo is not a separate compiler! It's merely an orchestration program that calls the compiler on packages/files. If invoking rustc directly fails due to a syntax or semantic error, then invoking it through cargo will fail as well.

3 Likes

I agree in principle. At least for syntax errors; possible errors when using rustc manually (and incorrectly) are errors regarding missing dependencies that cargo would resolve by passing the appropriate command line arguments to rustc. And actually… even for syntax errors… say… the code fails with rustc because its syntax isn’t compatible with edition 2015 (the default chosen when rustc is invoked without the --edition=… argument), whilst the Cargo.toml specifies a later edition; that’s a possibility.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.