Skip to content

doctests: unhelpful error messages for non-Rust code blocks #88590

Open
@torfsen

Description

@torfsen

I recently added the a docstring to one of my functions that looked similar to this:

/**
This function does the following:

    1. Print `foo`
    2. Return
*/
pub fn foo() {
    println!("foo");
}

When I then ran cargo test to execute tests defined in other parts of the project, I got the error messages

---- src/lib.rs - foo (line 4) stdout ----
error: unknown start of token: `
 --> src/lib.rs:5:10
  |
3 | 1. Print `foo`
  |          ^
  |
help: Unicode character '`' (Grave Accent) looks like ''' (Single Quote), but it is not
  |
3 | 1. Print 'foo`
  |          ^

error: unknown start of token: `
 --> src/lib.rs:5:14
  |
3 | 1. Print `foo`
  |              ^
  |
help: Unicode character '`' (Grave Accent) looks like ''' (Single Quote), but it is not
  |
3 | 1. Print `foo'
  |              ^

error: expected one of `.`, `;`, `?`, `}`, or an operator, found `Print`
 --> src/lib.rs:5:4
  |
3 | 1. Print `foo`
  |    ^^^^^ expected one of `.`, `;`, `?`, `}`, or an operator

error: aborting due to 3 previous errors

It took me a while to figure out the issue: the list items shouldn't be indented, because the indentation makes them a code block instead of a list. With the indentation, Rust tries to run the list as a doctest, and the error messages are due to the list content not being valid Rust code.

cargo check didn't yield any insights, either -- in fact it did not produce any warning at all.

cargo doc, on the other hand, produced the following very helpful output:

warning: could not parse code block as Rust code
 --> src/lib.rs:4:5
  |
4 | /     1. Print `foo`
5 | |     2. Return
  | |_____________^
  |
  = note: error from rustc: unknown start of token: `
  = note: error from rustc: unknown start of token: `

This pointed me directly in the right direction of something being parsed as Rust code.

I know that this is a minor issue, but so far I have been amazed by the incredibly helpful error message in the Rust eco system, and this was one of the few times where the original message was of little help. I don't know anything about how cargo test and cargo doc differ in their parsing, but the helpful output of cargo doc shows that a similar message should be possible for cargo test.

This is with Cargo 1.50.0 (f04e7fab7 2021-02-04).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-doctestsArea: Documentation tests, run by rustdocT-rustdocRelevant to the rustdoc team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions