Skip to content

Commit fb00cbe

Browse files
committed
Auto merge of #11711 - weihanglo:more-doc, r=epage
doc: doc comments and intra-doc links for `core::compiler`
2 parents 4262636 + 63d97e5 commit fb00cbe

File tree

9 files changed

+163
-22
lines changed

9 files changed

+163
-22
lines changed

src/cargo/core/compiler/compilation.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Type definitions for the result of a compilation.
2+
13
use std::collections::{BTreeSet, HashMap};
24
use std::env;
35
use std::ffi::{OsStr, OsString};

src/cargo/core/compiler/compile_kind.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Type definitions for cross-compilation.
2+
13
use crate::core::Target;
24
use crate::util::errors::CargoResult;
35
use crate::util::interning::InternedString;

src/cargo/core/compiler/context/mod.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,11 +161,6 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
161161
}
162162

163163
for unit in &self.bcx.roots {
164-
// Build up a list of pending jobs, each of which represent
165-
// compiling a particular package. No actual work is executed as
166-
// part of this, that's all done next as part of the `execute`
167-
// function which will run everything in order with proper
168-
// parallelism.
169164
let force_rebuild = self.bcx.build_config.force_rebuild;
170165
super::compile(&mut self, &mut queue, &mut plan, unit, exec, force_rebuild)?;
171166
}

src/cargo/core/compiler/future_incompat.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,37 @@
1-
//! Support for future-incompatible warning reporting.
1+
//! Support for [future-incompatible warning reporting][1].
2+
//!
3+
//! Here is an overview of how Cargo handles future-incompatible reports.
4+
//!
5+
//! ## Receive reports from the compiler
6+
//!
7+
//! When receiving a compiler message during a build, if it is effectively
8+
//! a [`FutureIncompatReport`], Cargo gathers and forwards it as a
9+
//! `Message::FutureIncompatReport` to the main thread.
10+
//!
11+
//! To have the correct layout of strucutures for deserializing a report
12+
//! emitted by the compiler, most of structure definitions, for example
13+
//! [`FutureIncompatReport`], are copied either partially or entirely from
14+
//! [compiler/rustc_errors/src/json.rs][2] in rust-lang/rust repository.
15+
//!
16+
//! ## Persist reports on disk
17+
//!
18+
//! When a build comes to an end, by calling [`save_and_display_report`]
19+
//! Cargo saves the report on disk, and displays it directly if requested
20+
//! via command line or configuration. The information of the on-disk file can
21+
//! be found in [`FUTURE_INCOMPAT_FILE`].
22+
//!
23+
//! During the persistent process, Cargo will attempt to query the source of
24+
//! each package emitting the report, for the sake of providing an upgrade
25+
//! information as a solution to fix the incompatibility.
26+
//!
27+
//! ## Display reports to users
28+
//!
29+
//! Users can run `cargo report future-incompat` to retrieve a report. This is
30+
//! done by [`OnDiskReports::load`]. Cargo simply prints reports to the
31+
//! standard output.
32+
//!
33+
//! [1]: https://doc.rust-lang.org/nightly/cargo/reference/future-incompat-report.html
34+
//! [2]: https://github.com/rust-lang/rust/blob/9bb6e60d1f1360234aae90c97964c0fa5524f141/compiler/rustc_errors/src/json.rs#L312-L315
235
336
use crate::core::compiler::BuildContext;
437
use crate::core::{Dependency, PackageId, QueryKind, Workspace};

src/cargo/core/compiler/links.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,20 @@ use crate::core::{PackageId, Resolve};
44
use crate::util::errors::CargoResult;
55
use std::collections::{HashMap, HashSet};
66

7-
/// Validate `links` field does not conflict between packages.
7+
/// Validates [`package.links`] field in the manifest file does not conflict
8+
/// between packages.
9+
///
10+
/// NOTE: This is the *old* links validator. Links are usually validated in the
11+
/// resolver. However, the `links` field was added to the index in early 2018
12+
/// (see [rust-lang/cargo#4978]). However, `links` has been around since 2014,
13+
/// so there are still many crates in the index that don't have `links`
14+
/// properly set in the index (over 600 at the time of this writing in 2019).
15+
/// This can probably be removed at some point in the future, though it might
16+
/// be worth considering fixing the index.
17+
///
18+
/// [rust-lang/cargo#4978]: https://github.com/rust-lang/cargo/pull/4978
19+
/// [`package.links`]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#the-links-manifest-key
820
pub fn validate_links(resolve: &Resolve, unit_graph: &UnitGraph) -> CargoResult<()> {
9-
// NOTE: This is the *old* links validator. Links are usually validated in
10-
// the resolver. However, the `links` field was added to the index in
11-
// early 2018 (see https://github.com/rust-lang/cargo/pull/4978). However,
12-
// `links` has been around since 2014, so there are still many crates in
13-
// the index that don't have `links` properly set in the index (over 600
14-
// at the time of this writing in 2019). This can probably be removed at
15-
// some point in the future, though it might be worth considering fixing
16-
// the index.
1721
let mut validated: HashSet<PackageId> = HashSet::new();
1822
let mut links: HashMap<String, PackageId> = HashMap::new();
1923
let mut units: Vec<_> = unit_graph.keys().collect();

src/cargo/core/compiler/mod.rs

Lines changed: 90 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,36 @@
1+
//! # Interact with the compiler
2+
//!
3+
//! If you consider [`ops::cargo_compile::compile`] as a `rustc` driver but on
4+
//! Cargo side, this module is kinda the `rustc_interface` for that merits.
5+
//! It contains all the interaction between Cargo and the rustc compiler,
6+
//! from preparing the context for the entire build process, to scheduling
7+
//! and executing each unit of work (e.g. running `rustc`), to managing and
8+
//! caching the output artifact of a build.
9+
//!
10+
//! However, it hasn't yet exposed a clear definition of each phase or session,
11+
//! like what rustc has done[^1]. Also, no one knows if Cargo really needs that.
12+
//! To be pragmatic, here we list a handful of items you may want to learn:
13+
//!
14+
//! * [`BuildContext`] is a static context containg all information you need
15+
//! before a build gets started.
16+
//! * [`Context`] is the center of the world, coordinating a running build and
17+
//! collecting information from it.
18+
//! * [`custom_build`] is the home of build script executions and output parsing.
19+
//! * [`fingerprint`] not only defines but also executes a set of rules to
20+
//! determine if a re-compile is needed.
21+
//! * [`job_queue`] is where the parallelism, job scheduling, and communication
22+
//! machinary happen between Cargo and the compiler.
23+
//! * [`layout`] defines and manages output artifacts of a build in the filesystem.
24+
//! * [`unit_dependencies`] is for building a dependency graph for compilation
25+
//! from a result of dependency resolution.
26+
//! * [`Unit`] contains sufficient information to build something, usually
27+
//! turning into a compiler invocation in a later phase.
28+
//!
29+
//! [^1]: Maybe [`-Zbuild-plan`](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-plan)
30+
//! was designed to serve that purpose but still [in flux](https://github.com/rust-lang/cargo/issues/7614).
31+
//!
32+
//! [`ops::cargo_compile::compile`]: crate::ops::compile
33+
134
pub mod artifact;
235
mod build_config;
336
mod build_context;
@@ -67,18 +100,31 @@ use rustfix::diagnostics::Applicability;
67100

68101
const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
69102

103+
// TODO: Rename this to `ExtraLinkArgFor` or else, and move to compiler/custom_build.rs?
104+
/// Represents one of the instruction from `cargo:rustc-link-arg-*` build script
105+
/// instruction family.
106+
///
107+
/// In other words, indicates targets that custom linker arguments applies to.
70108
#[derive(Clone, Hash, Debug, PartialEq, Eq)]
71109
pub enum LinkType {
110+
/// Represents `cargo:rustc-link-arg=FLAG`.
72111
All,
112+
/// Represents `cargo:rustc-cdylib-link-arg=FLAG`.
73113
Cdylib,
114+
/// Represents `cargo:rustc-link-arg-bins=FLAG`.
74115
Bin,
116+
/// Represents `cargo:rustc-link-arg-bin=BIN=FLAG`.
75117
SingleBin(String),
118+
/// Represents `cargo:rustc-link-arg-tests=FLAG`.
76119
Test,
120+
/// Represents `cargo:rustc-link-arg-benches=FLAG`.
77121
Bench,
122+
/// Represents `cargo:rustc-link-arg-examples=FLAG`.
78123
Example,
79124
}
80125

81126
impl LinkType {
127+
/// Checks if this link type applies to a given [`Target`].
82128
pub fn applies_to(&self, target: &Target) -> bool {
83129
match self {
84130
LinkType::All => true,
@@ -140,6 +186,15 @@ impl Executor for DefaultExecutor {
140186
}
141187
}
142188

189+
/// Builds up and enqueue a list of pending jobs onto the `job` queue.
190+
///
191+
/// Starting from the `unit`, this function recursively calls itself to build
192+
/// all jobs for dependencies of the `unit`. Each of these jobs represents
193+
/// compiling a particular package.
194+
///
195+
/// Note that **no actual work is executed as part of this**, that's all done
196+
/// next as part of [`JobQueue::execute`] function which will run everything
197+
/// in order with proper parallelism.
143198
fn compile<'cfg>(
144199
cx: &mut Context<'_, 'cfg>,
145200
jobs: &mut JobQueue<'cfg>,
@@ -230,6 +285,7 @@ fn make_failed_scrape_diagnostic(
230285
)
231286
}
232287

288+
/// Creates a unit of work invoking `rustc` for building the `unit`.
233289
fn rustc(cx: &mut Context<'_, '_>, unit: &Unit, exec: &Arc<dyn Executor>) -> CargoResult<Work> {
234290
let mut rustc = prepare_rustc(cx, &unit.target.rustc_crate_types(), unit)?;
235291
let build_plan = cx.bcx.build_config.build_plan;
@@ -638,6 +694,8 @@ where
638694
search_path
639695
}
640696

697+
// TODO: do we really need this as a separate function?
698+
// Maybe we should reorganize `rustc` fn to make it more traceable and readable.
641699
fn prepare_rustc(
642700
cx: &mut Context<'_, '_>,
643701
crate_types: &[CrateType],
@@ -672,6 +730,7 @@ fn prepare_rustc(
672730
Ok(base)
673731
}
674732

733+
/// Creates a unit of work invoking `rustdoc` for documenting the `unit`.
675734
fn rustdoc(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Work> {
676735
let bcx = cx.bcx;
677736
// script_metadata is not needed here, it is only for tests.
@@ -857,6 +916,9 @@ fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
857916
.arg(unit.pkg.version().to_string());
858917
}
859918

919+
/// Adds [`--cap-lints`] to the command to execute.
920+
///
921+
/// [`--cap-lints`]: https://doc.rust-lang.org/nightly/rustc/lints/levels.html#capping-lints
860922
fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
861923
// If this is an upstream dep we don't want warnings from, turn off all
862924
// lints.
@@ -870,7 +932,9 @@ fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuild
870932
}
871933
}
872934

873-
/// Forward -Zallow-features if it is set for cargo.
935+
/// Forwards [`-Zallow-features`] if it is set for cargo.
936+
///
937+
/// [`-Zallow-features`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#allow-features
874938
fn add_allow_features(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
875939
if let Some(allow) = &cx.bcx.config.cli_unstable().allow_features {
876940
let mut arg = String::from("-Zallow-features=");
@@ -879,14 +943,16 @@ fn add_allow_features(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
879943
}
880944
}
881945

882-
/// Add error-format flags to the command.
946+
/// Adds [`--error-format`] to the command to execute.
883947
///
884948
/// Cargo always uses JSON output. This has several benefits, such as being
885949
/// easier to parse, handles changing formats (for replaying cached messages),
886950
/// ensures atomic output (so messages aren't interleaved), allows for
887951
/// intercepting messages like rmeta artifacts, etc. rustc includes a
888952
/// "rendered" field in the JSON message with the message properly formatted,
889953
/// which Cargo will extract and display to the user.
954+
///
955+
/// [`--error-format`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#--error-format-control-how-errors-are-produced
890956
fn add_error_format_and_color(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
891957
cmd.arg("--error-format=json");
892958
let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
@@ -905,6 +971,7 @@ fn add_error_format_and_color(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
905971
}
906972
}
907973

974+
/// Adds essential rustc flags and environment variables to the command to execute.
908975
fn build_base_args(
909976
cx: &mut Context<'_, '_>,
910977
cmd: &mut ProcessBuilder,
@@ -1124,7 +1191,7 @@ fn build_base_args(
11241191
Ok(())
11251192
}
11261193

1127-
/// All active features for the unit passed as --cfg
1194+
/// All active features for the unit passed as `--cfg features=<feature-name>`.
11281195
fn features_args(unit: &Unit) -> Vec<OsString> {
11291196
let mut args = Vec::with_capacity(unit.features.len() * 2);
11301197

@@ -1136,7 +1203,10 @@ fn features_args(unit: &Unit) -> Vec<OsString> {
11361203
args
11371204
}
11381205

1139-
/// Generate the --check-cfg arguments for the unit
1206+
/// Generates the `--check-cfg` arguments for the `unit`.
1207+
/// See unstable feature [`check-cfg`].
1208+
///
1209+
/// [`check-cfg`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#check-cfg
11401210
fn check_cfg_args(cx: &Context<'_, '_>, unit: &Unit) -> Vec<OsString> {
11411211
if let Some((features, well_known_names, well_known_values, _output)) =
11421212
cx.bcx.config.cli_unstable().check_cfg
@@ -1176,6 +1246,7 @@ fn check_cfg_args(cx: &Context<'_, '_>, unit: &Unit) -> Vec<OsString> {
11761246
}
11771247
}
11781248

1249+
/// Adds LTO related codegen flags.
11791250
fn lto_args(cx: &Context<'_, '_>, unit: &Unit) -> Vec<OsString> {
11801251
let mut result = Vec::new();
11811252
let mut push = |arg: &str| {
@@ -1196,6 +1267,11 @@ fn lto_args(cx: &Context<'_, '_>, unit: &Unit) -> Vec<OsString> {
11961267
result
11971268
}
11981269

1270+
/// Adds dependency-relevant rustc flags and environment variables
1271+
/// to the command to execute, such as [`-L`] and [`--extern`].
1272+
///
1273+
/// [`-L`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#-l-add-a-directory-to-the-library-search-path
1274+
/// [`--extern`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#--extern-specify-where-an-external-library-is-located
11991275
fn build_deps_args(
12001276
cmd: &mut ProcessBuilder,
12011277
cx: &mut Context<'_, '_>,
@@ -1267,7 +1343,9 @@ fn build_deps_args(
12671343
Ok(())
12681344
}
12691345

1270-
/// Add custom flags from the output a of build-script to a `ProcessBuilder`
1346+
/// Adds extra rustc flags and environment variables collected from the output
1347+
/// of a build-script to the command to execute, include custom environment
1348+
/// variables and `cfg`.
12711349
fn add_custom_flags(
12721350
cmd: &mut ProcessBuilder,
12731351
build_script_outputs: &BuildScriptOutputs,
@@ -1377,6 +1455,8 @@ fn envify(s: &str) -> String {
13771455
.collect()
13781456
}
13791457

1458+
/// Configuration of the display of messages emitted by the compiler,
1459+
/// e.g. diagnostics, warnings, errors, and message caching.
13801460
struct OutputOptions {
13811461
/// What format we're emitting from Cargo itself.
13821462
format: MessageFormat,
@@ -1395,7 +1475,9 @@ struct OutputOptions {
13951475
/// cache will be filled with diagnostics from dependencies. When the
13961476
/// cache is replayed without `-vv`, we don't want to show them.
13971477
show_diagnostics: bool,
1478+
/// Tracks the number of warnings we've seen so far.
13981479
warnings_seen: usize,
1480+
/// Tracks the number of errors we've seen so far.
13991481
errors_seen: usize,
14001482
}
14011483

@@ -1677,6 +1759,9 @@ fn on_stderr_line_inner(
16771759
Ok(true)
16781760
}
16791761

1762+
/// Creates a unit of work that replays the cached compiler message.
1763+
///
1764+
/// Usually used when a job is fresh and doesn't need to recompile.
16801765
fn replay_output_cache(
16811766
package_id: PackageId,
16821767
manifest_path: PathBuf,

src/cargo/core/compiler/timings.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ use std::io::{BufWriter, Write};
1616
use std::thread::available_parallelism;
1717
use std::time::{Duration, Instant, SystemTime};
1818

19+
/// Tracking information for the entire build.
20+
///
21+
/// Methods on this structure are generally called from the main thread of a
22+
/// running [`JobQueue`] instance (`DrainState` in specific) when the queue
23+
/// receives messages from spawned off threads.
24+
///
25+
/// [`JobQueue`]: super::JobQueue
1926
pub struct Timings<'cfg> {
2027
config: &'cfg Config,
2128
/// Whether or not timings should be captured.
@@ -253,12 +260,12 @@ impl<'cfg> Timings<'cfg> {
253260
self.concurrency.push(c);
254261
}
255262

256-
/// Mark that a fresh unit was encountered.
263+
/// Mark that a fresh unit was encountered. (No re-compile needed)
257264
pub fn add_fresh(&mut self) {
258265
self.total_fresh += 1;
259266
}
260267

261-
/// Mark that a dirty unit was encountered.
268+
/// Mark that a dirty unit was encountered. (Re-compile needed)
262269
pub fn add_dirty(&mut self) {
263270
self.total_dirty += 1;
264271
}
@@ -456,6 +463,8 @@ impl<'cfg> Timings<'cfg> {
456463
Ok(())
457464
}
458465

466+
/// Write timing data in JavaScript. Primarily for `timings.js` to put data
467+
/// in a `<script>` HTML element to draw graphs.
459468
fn write_js_data(&self, f: &mut impl Write) -> CargoResult<()> {
460469
// Create a map to link indices of unlocked units.
461470
let unit_map: HashMap<Unit, usize> = self

src/cargo/core/compiler/unit.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Types and impls for [`Unit`].
2+
13
use crate::core::compiler::unit_dependencies::IsArtifact;
24
use crate::core::compiler::{CompileKind, CompileMode, CompileTarget, CrateType};
35
use crate::core::manifest::{Target, TargetKind};
@@ -108,6 +110,9 @@ impl UnitInner {
108110
}
109111

110112
impl Unit {
113+
/// Gets the unique key for [`-Zbuild-plan`].
114+
///
115+
/// [`-Zbuild-plan`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-plan
111116
pub fn buildkey(&self) -> String {
112117
format!("{}-{}", self.pkg.name(), short_hash(self))
113118
}

0 commit comments

Comments
 (0)