Skip to content

Commit 35ed69c

Browse files
committed
Auto merge of #13048 - weihanglo:rustfix-doc, r=epage
docs: add doc comments for rustfix
2 parents 9b13310 + 358b7ae commit 35ed69c

File tree

4 files changed

+85
-14
lines changed

4 files changed

+85
-14
lines changed

crates/rustfix/src/diagnostics.rs

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1-
//! Rustc Diagnostic JSON Output
1+
//! Rustc Diagnostic JSON Output.
22
//!
3-
//! The following data types are copied from [rust-lang/rust](https://github.com/rust-lang/rust/blob/de78655bca47cac8e783dbb563e7e5c25c1fae40/src/libsyntax/json.rs)
3+
//! The following data types are copied from [rust-lang/rust](https://github.com/rust-lang/rust/blob/4fd68eb47bad1c121417ac4450b2f0456150db86/compiler/rustc_errors/src/json.rs).
4+
//!
5+
//! For examples of the JSON output, see JSON fixture files under `tests/` directory.
46
57
use serde::Deserialize;
68

9+
/// The root diagnostic JSON output emitted by the compiler.
710
#[derive(Clone, Deserialize, Debug, Hash, Eq, PartialEq)]
811
pub struct Diagnostic {
912
/// The primary error message.
@@ -14,12 +17,11 @@ pub struct Diagnostic {
1417
pub spans: Vec<DiagnosticSpan>,
1518
/// Associated diagnostic messages.
1619
pub children: Vec<Diagnostic>,
17-
/// The message as rustc would render it. Currently this is only
18-
/// `Some` for "suggestions", but eventually it will include all
19-
/// snippets.
20+
/// The message as rustc would render it.
2021
pub rendered: Option<String>,
2122
}
2223

24+
/// Span information of a diagnostic item.
2325
#[derive(Clone, Deserialize, Debug, Hash, Eq, PartialEq)]
2426
pub struct DiagnosticSpan {
2527
pub file_name: String,
@@ -39,23 +41,43 @@ pub struct DiagnosticSpan {
3941
/// Label that should be placed at this location (if any)
4042
label: Option<String>,
4143
/// If we are suggesting a replacement, this will contain text
42-
/// that should be sliced in atop this span. You may prefer to
43-
/// load the fully rendered version from the parent `Diagnostic`,
44-
/// however.
44+
/// that should be sliced in atop this span.
4545
pub suggested_replacement: Option<String>,
46+
/// If the suggestion is approximate
4647
pub suggestion_applicability: Option<Applicability>,
4748
/// Macro invocations that created the code at this span, if any.
4849
expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
4950
}
5051

52+
/// Indicates the confidence in the correctness of a suggestion.
53+
///
54+
/// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
55+
/// to determine whether it should be automatically applied or if the user should be consulted
56+
/// before applying the suggestion.
5157
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Hash, Eq)]
5258
pub enum Applicability {
59+
/// The suggestion is definitely what the user intended, or maintains the exact meaning of the code.
60+
/// This suggestion should be automatically applied.
61+
///
62+
/// In case of multiple `MachineApplicable` suggestions (whether as part of
63+
/// the same `multipart_suggestion` or not), all of them should be
64+
/// automatically applied.
5365
MachineApplicable,
54-
HasPlaceholders,
66+
67+
/// The suggestion may be what the user intended, but it is uncertain. The suggestion should
68+
/// result in valid Rust code if it is applied.
5569
MaybeIncorrect,
70+
71+
/// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
72+
/// cannot be applied automatically because it will not result in valid Rust code. The user
73+
/// will need to fill in the placeholders.
74+
HasPlaceholders,
75+
76+
/// The applicability of the suggestion is unknown.
5677
Unspecified,
5778
}
5879

80+
/// Span information of a single line.
5981
#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)]
6082
pub struct DiagnosticSpanLine {
6183
pub text: String,
@@ -66,6 +88,7 @@ pub struct DiagnosticSpanLine {
6688
pub highlight_end: usize,
6789
}
6890

91+
/// Span information for macro expansions.
6992
#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)]
7093
struct DiagnosticSpanMacroExpansion {
7194
/// span where macro was applied to generate this code; note that
@@ -80,6 +103,9 @@ struct DiagnosticSpanMacroExpansion {
80103
def_site_span: Option<DiagnosticSpan>,
81104
}
82105

106+
/// The error code emitted by the compiler. See [Rust error codes index].
107+
///
108+
/// [Rust error codes index]: https://doc.rust-lang.org/error_codes/error-index.html
83109
#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Hash)]
84110
pub struct DiagnosticCode {
85111
/// The code itself.

crates/rustfix/src/lib.rs

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
//! Library for applying diagnostic suggestions to source code.
22
//!
3-
//! This is a low-level library. You pass it the JSON output from `rustc`, and
4-
//! you can then use it to apply suggestions to in-memory strings. This
5-
//! library doesn't execute commands, or read or write from the filesystem.
3+
//! This is a low-level library. You pass it the [JSON output] from `rustc`,
4+
//! and you can then use it to apply suggestions to in-memory strings.
5+
//! This library doesn't execute commands, or read or write from the filesystem.
66
//!
77
//! If you are looking for the [`cargo fix`] implementation, the core of it is
88
//! located in [`cargo::ops::fix`].
99
//!
1010
//! [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1111
//! [`cargo::ops::fix`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/ops/fix.rs
12+
//! [JSON output]: diagnostics
1213
//!
1314
//! The general outline of how to use this library is:
1415
//!
1516
//! 1. Call `rustc` and collect the JSON data.
1617
//! 2. Pass the json data to [`get_suggestions_from_json`].
1718
//! 3. Create a [`CodeFix`] with the source of a file to modify.
1819
//! 4. Call [`CodeFix::apply`] to apply a change.
19-
//! 5. Write the source back to disk.
20+
//! 5. Call [`CodeFix::finish`] to get the result and write it back to disk.
2021
2122
use std::collections::HashSet;
2223
use std::ops::Range;
@@ -27,12 +28,20 @@ pub mod diagnostics;
2728
use crate::diagnostics::{Diagnostic, DiagnosticSpan};
2829
mod replace;
2930

31+
/// A filter to control which suggestion should be applied.
3032
#[derive(Debug, Clone, Copy)]
3133
pub enum Filter {
34+
/// For [`diagnostics::Applicability::MachineApplicable`] only.
3235
MachineApplicableOnly,
36+
/// Everything is included. YOLO!
3337
Everything,
3438
}
3539

40+
/// Collects code [`Suggestion`]s from one or more compiler diagnostic lines.
41+
///
42+
/// Fails if any of diagnostic line `input` is not a valid [`Diagnostic`] JSON.
43+
///
44+
/// * `only` --- only diagnostics with code in a set of error codes would be collected.
3645
pub fn get_suggestions_from_json<S: ::std::hash::BuildHasher>(
3746
input: &str,
3847
only: &HashSet<String, S>,
@@ -70,20 +79,24 @@ impl std::fmt::Display for LineRange {
7079
}
7180
}
7281

73-
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
7482
/// An error/warning and possible solutions for fixing it
83+
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
7584
pub struct Suggestion {
7685
pub message: String,
7786
pub snippets: Vec<Snippet>,
7887
pub solutions: Vec<Solution>,
7988
}
8089

90+
/// Solution to a diagnostic item.
8191
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
8292
pub struct Solution {
93+
/// The error message of the diagnostic item.
8394
pub message: String,
95+
/// Possible solutions to fix the error.
8496
pub replacements: Vec<Replacement>,
8597
}
8698

99+
/// Represents code that will get replaced.
87100
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
88101
pub struct Snippet {
89102
pub file_name: String,
@@ -95,12 +108,16 @@ pub struct Snippet {
95108
pub text: (String, String, String),
96109
}
97110

111+
/// Represents a replacement of a `snippet`.
98112
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
99113
pub struct Replacement {
114+
/// Code snippet that gets replaced.
100115
pub snippet: Snippet,
116+
/// The replacement of the snippet.
101117
pub replacement: String,
102118
}
103119

120+
/// Parses a [`Snippet`] from a diagnostic span item.
104121
fn parse_snippet(span: &DiagnosticSpan) -> Option<Snippet> {
105122
// unindent the snippet
106123
let indent = span
@@ -168,6 +185,7 @@ fn parse_snippet(span: &DiagnosticSpan) -> Option<Snippet> {
168185
})
169186
}
170187

188+
/// Converts a [`DiagnosticSpan`] into a [`Replacement`].
171189
fn collect_span(span: &DiagnosticSpan) -> Option<Replacement> {
172190
let snippet = parse_snippet(span)?;
173191
let replacement = span.suggested_replacement.clone()?;
@@ -177,6 +195,9 @@ fn collect_span(span: &DiagnosticSpan) -> Option<Replacement> {
177195
})
178196
}
179197

198+
/// Collects code [`Suggestion`]s from a single compiler diagnostic line.
199+
///
200+
/// * `only` --- only diagnostics with code in a set of error codes would be collected.
180201
pub fn collect_suggestions<S: ::std::hash::BuildHasher>(
181202
diagnostic: &Diagnostic,
182203
only: &HashSet<String, S>,
@@ -237,17 +258,26 @@ pub fn collect_suggestions<S: ::std::hash::BuildHasher>(
237258
}
238259
}
239260

261+
/// Represents a code fix. This doesn't write to disks but is only in memory.
262+
///
263+
/// The general way to use this is:
264+
///
265+
/// 1. Feeds the source of a file to [`CodeFix::new`].
266+
/// 2. Calls [`CodeFix::apply`] to apply suggestions to the source code.
267+
/// 3. Calls [`CodeFix::finish`] to get the "fixed" code.
240268
pub struct CodeFix {
241269
data: replace::Data,
242270
}
243271

244272
impl CodeFix {
273+
/// Creates a `CodeFix` with the source of a file to modify.
245274
pub fn new(s: &str) -> CodeFix {
246275
CodeFix {
247276
data: replace::Data::new(s.as_bytes()),
248277
}
249278
}
250279

280+
/// Applies a suggestion to the code.
251281
pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> {
252282
for sol in &suggestion.solutions {
253283
for r in &sol.replacements {
@@ -258,11 +288,13 @@ impl CodeFix {
258288
Ok(())
259289
}
260290

291+
/// Gets the result of the "fixed" code.
261292
pub fn finish(&self) -> Result<String, Error> {
262293
Ok(String::from_utf8(self.data.to_vec())?)
263294
}
264295
}
265296

297+
/// Applies multiple `suggestions` to the given `code`.
266298
pub fn apply_suggestions(code: &str, suggestions: &[Suggestion]) -> Result<String, Error> {
267299
let mut fix = CodeFix::new(code);
268300
for suggestion in suggestions.iter().rev() {

crates/rustfix/src/replace.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
use anyhow::{anyhow, ensure, Error};
66
use std::rc::Rc;
77

8+
/// Indicates the change state of a [`Span`].
89
#[derive(Debug, Clone, PartialEq, Eq)]
910
enum State {
11+
/// The initial state. No change applied.
1012
Initial,
13+
/// Has been replaced.
1114
Replaced(Rc<[u8]>),
15+
/// Has been inserted.
1216
Inserted(Rc<[u8]>),
1317
}
1418

@@ -18,19 +22,23 @@ impl State {
1822
}
1923
}
2024

25+
/// Span with a change [`State`].
2126
#[derive(Debug, Clone, PartialEq, Eq)]
2227
struct Span {
2328
/// Start of this span in parent data
2429
start: usize,
2530
/// up to end excluding
2631
end: usize,
32+
/// Whether the span is inserted, replaced or still fresh.
2733
data: State,
2834
}
2935

3036
/// A container that allows easily replacing chunks of its data
3137
#[derive(Debug, Clone, Default)]
3238
pub struct Data {
39+
/// Original data.
3340
original: Vec<u8>,
41+
/// [`Span`]s covering the full range of the original data.
3442
parts: Vec<Span>,
3543
}
3644

src/cargo/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,11 @@
7070
//! This is not directly depended upon with a `path` dependency; cargo uses the version from crates.io.
7171
//! It is intended to be versioned and published independently of Rust's release system.
7272
//! Whenever a change needs to be made, bump the version in Cargo.toml and `cargo publish` it manually, and then update cargo's `Cargo.toml` to depend on the new version.
73+
//! - [`rustfix`](https://crates.io/crates/rustfix)
74+
//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/rustfix)):
75+
//! This defines structures that represent fix suggestions from rustc,
76+
//! as well as generates "fixed" code from suggestions.
77+
//! Operations in `rustfix` are all in memory and won't write to disks.
7378
//! - [`cargo-test-support`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-support)
7479
//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_support/index.html)):
7580
//! This contains a variety of code to support writing tests

0 commit comments

Comments
 (0)