cargo/core/compiler/job_queue/mod.rs
1//! Management of the interaction between the main `cargo` and all spawned jobs.
2//!
3//! ## Overview
4//!
5//! This module implements a job queue. A job here represents a unit of work,
6//! which is roughly a rustc invocation, a build script run, or just a no-op.
7//! The job queue primarily handles the following things:
8//!
9//! * Spawns concurrent jobs. Depending on its [`Freshness`], a job could be
10//! either executed on a spawned thread or ran on the same thread to avoid
11//! the threading overhead.
12//! * Controls the number of concurrency. It allocates and manages [`jobserver`]
13//! tokens to each spawned off rustc and build scripts.
14//! * Manages the communication between the main `cargo` process and its
15//! spawned jobs. Those [`Message`]s are sent over a [`Queue`] shared
16//! across threads.
17//! * Schedules the execution order of each [`Job`]. Priorities are determined
18//! when calling [`JobQueue::enqueue`] to enqueue a job. The scheduling is
19//! relatively rudimentary and could likely be improved.
20//!
21//! A rough outline of building a queue and executing jobs is:
22//!
23//! 1. [`JobQueue::new`] to simply create one queue.
24//! 2. [`JobQueue::enqueue`] to add new jobs onto the queue.
25//! 3. Consumes the queue and executes all jobs via [`JobQueue::execute`].
26//!
27//! The primary loop happens insides [`JobQueue::execute`], which is effectively
28//! [`DrainState::drain_the_queue`]. [`DrainState`] is, as its name tells,
29//! the running state of the job queue getting drained.
30//!
31//! ## Jobserver
32//!
33//! As of Feb. 2023, Cargo and rustc have a relatively simple jobserver
34//! relationship with each other. They share a single jobserver amongst what
35//! is potentially hundreds of threads of work on many-cored systems.
36//! The jobserver could come from either the environment (e.g., from a `make`
37//! invocation), or from Cargo creating its own jobserver server if there is no
38//! jobserver to inherit from.
39//!
40//! Cargo wants to complete the build as quickly as possible, fully saturating
41//! all cores (as constrained by the `-j=N`) parameter. Cargo also must not spawn
42//! more than N threads of work: the total amount of tokens we have floating
43//! around must always be limited to N.
44//!
45//! It is not really possible to optimally choose which crate should build
46//! first or last; nor is it possible to decide whether to give an additional
47//! token to rustc first or rather spawn a new crate of work. The algorithm in
48//! Cargo prioritizes spawning as many crates (i.e., rustc processes) as
49//! possible. In short, the jobserver relationship among Cargo and rustc
50//! processes is **1 `cargo` to N `rustc`**. Cargo knows nothing beyond rustc
51//! processes in terms of parallelism[^parallel-rustc].
52//!
53//! We integrate with the [jobserver] crate, originating from GNU make
54//! [POSIX jobserver], to make sure that build scripts which use make to
55//! build C code can cooperate with us on the number of used tokens and
56//! avoid overfilling the system we're on.
57//!
58//! ## Scheduling
59//!
60//! The current scheduling algorithm is not really polished. It is simply based
61//! on a dependency graph [`DependencyQueue`]. We continue adding nodes onto
62//! the graph until we finalize it. When the graph gets finalized, it finds the
63//! sum of the cost of each dependencies of each node, including transitively.
64//! The sum of dependency cost turns out to be the cost of each given node.
65//!
66//! At the time being, the cost is just passed as a fixed placeholder in
67//! [`JobQueue::enqueue`]. In the future, we could explore more possibilities
68//! around it. For instance, we start persisting timing information for each
69//! build somewhere. For a subsequent build, we can look into the historical
70//! data and perform a PGO-like optimization to prioritize jobs, making a build
71//! fully pipelined.
72//!
73//! ## Message queue
74//!
75//! Each spawned thread running a process uses the message queue [`Queue`] to
76//! send messages back to the main thread (the one running `cargo`).
77//! The main thread coordinates everything, and handles printing output.
78//!
79//! It is important to be careful which messages use [`push`] vs [`push_bounded`].
80//! `push` is for priority messages (like tokens, or "finished") where the
81//! sender shouldn't block. We want to handle those so real work can proceed
82//! ASAP.
83//!
84//! `push_bounded` is only for messages being printed to stdout/stderr. Being
85//! bounded prevents a flood of messages causing a large amount of memory
86//! being used.
87//!
88//! `push` also avoids blocking which helps avoid deadlocks. For example, when
89//! the diagnostic server thread is dropped, it waits for the thread to exit.
90//! But if the thread is blocked on a full queue, and there is a critical
91//! error, the drop will deadlock. This should be fixed at some point in the
92//! future. The jobserver thread has a similar problem, though it will time
93//! out after 1 second.
94//!
95//! To access the message queue, each running `Job` is given its own [`JobState`],
96//! containing everything it needs to communicate with the main thread.
97//!
98//! See [`Message`] for all available message kinds.
99//!
100//! [^parallel-rustc]: In fact, `jobserver` that Cargo uses also manages the
101//! allocation of tokens to rustc beyond the implicit token each rustc owns
102//! (i.e., the ones used for parallel LLVM work and parallel rustc threads).
103//! See also ["Rust Compiler Development Guide: Parallel Compilation"]
104//! and [this comment][rustc-codegen] in rust-lang/rust.
105//!
106//! ["Rust Compiler Development Guide: Parallel Compilation"]: https://rustc-dev-guide.rust-lang.org/parallel-rustc.html
107//! [rustc-codegen]: https://github.com/rust-lang/rust/blob/5423745db8b434fcde54888b35f518f00cce00e4/compiler/rustc_codegen_ssa/src/back/write.rs#L1204-L1217
108//! [jobserver]: https://docs.rs/jobserver
109//! [POSIX jobserver]: https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html
110//! [`push`]: Queue::push
111//! [`push_bounded`]: Queue::push_bounded
112
113mod job;
114mod job_state;
115
116use std::cell::RefCell;
117use std::collections::{HashMap, HashSet};
118use std::fmt::Write as _;
119use std::path::{Path, PathBuf};
120use std::sync::Arc;
121use std::thread::{self, Scope};
122use std::time::Duration;
123use std::{env, io};
124
125use anyhow::{Context as _, format_err};
126use jobserver::{Acquired, HelperThread};
127use semver::Version;
128use tracing::{debug, trace};
129
130pub use self::job::Freshness::{self, Dirty, Fresh};
131pub use self::job::{Job, Work};
132pub use self::job_state::JobState;
133use super::BuildContext;
134use super::BuildRunner;
135use super::CompileMode;
136use super::Unit;
137use super::UnitIndex;
138use super::custom_build::Severity;
139use super::timings::SectionTiming;
140use super::timings::Timings;
141use super::unused_deps::UnusedDepState;
142use crate::core::compiler::descriptive_pkg_name;
143use crate::core::compiler::future_incompat::{
144 self, FutureBreakageItem, FutureIncompatReportPackage,
145};
146use crate::core::resolver::ResolveBehavior;
147use crate::core::{PackageId, TargetKind};
148use crate::util::CargoResult;
149use crate::util::context::WarningHandling;
150use crate::util::diagnostic_server::{self, DiagnosticPrinter};
151use crate::util::errors::AlreadyPrintedError;
152use crate::util::machine_message::{self, Message as _};
153use crate::util::{self, internal};
154use crate::util::{DependencyQueue, GlobalContext, Progress, ProgressStyle, Queue};
155use cargo_util_terminal::Shell;
156
157/// This structure is backed by the `DependencyQueue` type and manages the
158/// queueing of compilation steps for each package. Packages enqueue units of
159/// work and then later on the entire graph is converted to `DrainState` and
160/// executed.
161pub struct JobQueue<'gctx> {
162 queue: DependencyQueue<Unit, Artifact, Job>,
163 counts: HashMap<PackageId, usize>,
164 timings: Timings<'gctx>,
165}
166
167/// This structure is backed by the `DependencyQueue` type and manages the
168/// actual compilation step of each package. Packages enqueue units of work and
169/// then later on the entire graph is processed and compiled.
170///
171/// It is created from `JobQueue` when we have fully assembled the crate graph
172/// (i.e., all package dependencies are known).
173struct DrainState<'gctx> {
174 // This is the length of the DependencyQueue when starting out
175 total_units: usize,
176
177 queue: DependencyQueue<Unit, Artifact, Job>,
178 messages: Arc<Queue<Message>>,
179 /// Diagnostic deduplication support.
180 diag_dedupe: DiagDedupe<'gctx>,
181 /// Count of warnings, used to print a summary after the job succeeds
182 warning_count: HashMap<JobId, WarningCount>,
183 active: HashMap<JobId, Unit>,
184 compiled: HashSet<PackageId>,
185 documented: HashSet<PackageId>,
186 scraped: HashSet<PackageId>,
187 counts: HashMap<PackageId, usize>,
188 progress: Progress<'gctx>,
189 next_id: u32,
190 timings: Timings<'gctx>,
191 unused_dep_state: UnusedDepState,
192
193 /// Map from unit index to unit, for looking up dependency information.
194 index_to_unit: HashMap<UnitIndex, Unit>,
195
196 /// Tokens that are currently owned by this Cargo, and may be "associated"
197 /// with a rustc process. They may also be unused, though if so will be
198 /// dropped on the next loop iteration.
199 ///
200 /// Note that the length of this may be zero, but we will still spawn work,
201 /// as we share the implicit token given to this Cargo process with a
202 /// single rustc process.
203 tokens: Vec<Acquired>,
204
205 /// The list of jobs that we have not yet started executing, but have
206 /// retrieved from the `queue`. We eagerly pull jobs off the main queue to
207 /// allow us to request jobserver tokens pretty early.
208 pending_queue: Vec<(Unit, Job, usize)>,
209 print: DiagnosticPrinter<'gctx>,
210
211 /// How many jobs we've finished
212 finished: usize,
213 per_package_future_incompat_reports: Vec<FutureIncompatReportPackage>,
214}
215
216/// Count of warnings, used to print a summary after the job succeeds
217#[derive(Default, Clone)]
218pub struct WarningCount {
219 /// total number of warnings
220 pub total: usize,
221 /// number of lint warnings
222 pub lints: usize,
223 /// number of warnings that were suppressed because they
224 /// were duplicates of a previous warning
225 pub duplicates: usize,
226 /// number of fixable warnings set to `NotAllowed`
227 /// if any errors have been seen for the current
228 /// target
229 pub fixable: FixableWarnings,
230}
231
232impl WarningCount {
233 /// If an error is seen this should be called
234 /// to set `fixable` to `NotAllowed`
235 fn disallow_fixable(&mut self) {
236 self.fixable = FixableWarnings::NotAllowed;
237 }
238
239 /// Checks fixable if warnings are allowed
240 /// fixable warnings are allowed if no
241 /// errors have been seen for the current
242 /// target. If an error was seen `fixable`
243 /// will be `NotAllowed`.
244 fn fixable_allowed(&self) -> bool {
245 match &self.fixable {
246 FixableWarnings::NotAllowed => false,
247 _ => true,
248 }
249 }
250}
251
252/// Used to keep track of how many fixable warnings there are
253/// and if fixable warnings are allowed
254#[derive(Default, Copy, Clone)]
255pub enum FixableWarnings {
256 NotAllowed,
257 #[default]
258 Zero,
259 Positive(usize),
260}
261
262pub struct ErrorsDuringDrain {
263 pub count: usize,
264}
265
266struct ErrorToHandle {
267 error: anyhow::Error,
268
269 /// This field is true for "interesting" errors and false for "mundane"
270 /// errors. If false, we print the above error only if it's the first one
271 /// encountered so far while draining the job queue.
272 ///
273 /// At most places that an error is propagated, we set this to false to
274 /// avoid scenarios where Cargo might end up spewing tons of redundant error
275 /// messages. For example if an i/o stream got closed somewhere, we don't
276 /// care about individually reporting every thread that it broke; just the
277 /// first is enough.
278 ///
279 /// The exception where `print_always` is true is that we do report every
280 /// instance of a rustc invocation that failed with diagnostics. This
281 /// corresponds to errors from `Message::Finish`.
282 print_always: bool,
283}
284
285impl<E> From<E> for ErrorToHandle
286where
287 anyhow::Error: From<E>,
288{
289 fn from(error: E) -> Self {
290 ErrorToHandle {
291 error: anyhow::Error::from(error),
292 print_always: false,
293 }
294 }
295}
296
297#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
298pub struct JobId(pub u32);
299
300impl std::fmt::Display for JobId {
301 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302 write!(f, "{}", self.0)
303 }
304}
305
306/// Handler for deduplicating diagnostics.
307struct DiagDedupe<'gctx> {
308 seen: RefCell<HashSet<u64>>,
309 gctx: &'gctx GlobalContext,
310}
311
312impl<'gctx> DiagDedupe<'gctx> {
313 fn new(gctx: &'gctx GlobalContext) -> Self {
314 DiagDedupe {
315 seen: RefCell::new(HashSet::new()),
316 gctx,
317 }
318 }
319
320 /// Emits a diagnostic message.
321 ///
322 /// Returns `true` if the message was emitted, or `false` if it was
323 /// suppressed for being a duplicate.
324 fn emit_diag(&self, diag: &str) -> CargoResult<bool> {
325 let h = util::hash_u64(diag);
326 if !self.seen.borrow_mut().insert(h) {
327 return Ok(false);
328 }
329 let mut shell = self.gctx.shell();
330 shell.print_ansi_stderr(diag.as_bytes())?;
331 shell.err().write_all(b"\n")?;
332 Ok(true)
333 }
334}
335
336/// Possible artifacts that can be produced by compilations, used as edge values
337/// in the dependency graph.
338///
339/// As edge values we can have multiple kinds of edges depending on one node,
340/// for example some units may only depend on the metadata for an rlib while
341/// others depend on the full rlib. This `Artifact` enum is used to distinguish
342/// this case and track the progress of compilations as they proceed.
343#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
344enum Artifact {
345 /// A generic placeholder for "depends on everything run by a step" and
346 /// means that we can't start the next compilation until the previous has
347 /// finished entirely.
348 All,
349
350 /// A node indicating that we only depend on the metadata of a compilation,
351 /// but the compilation is typically also producing an rlib. We can start
352 /// our step, however, before the full rlib is available.
353 Metadata,
354}
355
356enum Message {
357 Run(JobId, String),
358 Stdout(String),
359 Stderr(String),
360
361 // This is for general stderr output from subprocesses
362 Diagnostic {
363 id: JobId,
364 level: String,
365 diag: String,
366 lint: bool,
367 fixable: bool,
368 },
369 // This handles duplicate output that is suppressed, for showing
370 // only a count of duplicate messages instead
371 WarningCount {
372 id: JobId,
373 lint: bool,
374 emitted: bool,
375 fixable: bool,
376 },
377 // This is for warnings generated by Cargo's interpretation of the
378 // subprocess output, e.g. scrape-examples prints a warning if a
379 // unit fails to be scraped
380 Warning {
381 id: JobId,
382 warning: String,
383 },
384
385 FixDiagnostic(diagnostic_server::Message),
386 Token(io::Result<Acquired>),
387 Finish(JobId, Artifact, CargoResult<()>),
388 FutureIncompatReport(JobId, Vec<FutureBreakageItem>),
389 SectionTiming(JobId, SectionTiming),
390 UnusedExterns(JobId, Vec<String>),
391}
392
393impl<'gctx> JobQueue<'gctx> {
394 pub fn new(bcx: &BuildContext<'_, 'gctx>) -> JobQueue<'gctx> {
395 JobQueue {
396 queue: DependencyQueue::new(),
397 counts: HashMap::new(),
398 timings: Timings::new(bcx),
399 }
400 }
401
402 pub fn enqueue(
403 &mut self,
404 build_runner: &BuildRunner<'_, 'gctx>,
405 unit: &Unit,
406 job: Job,
407 ) -> CargoResult<()> {
408 let dependencies = build_runner.unit_deps(unit);
409 let mut queue_deps = dependencies
410 .iter()
411 .filter(|dep| {
412 // Binaries aren't actually needed to *compile* tests, just to run
413 // them, so we don't include this dependency edge in the job graph.
414 // But we shouldn't filter out dependencies being scraped for Rustdoc.
415 (!dep.unit.target.is_test() && !dep.unit.target.is_bin())
416 || dep.unit.artifact.is_true()
417 || dep.unit.mode.is_doc_scrape()
418 })
419 .map(|dep| {
420 // Handle the case here where our `unit -> dep` dependency may
421 // only require the metadata, not the full compilation to
422 // finish. Use the tables in `build_runner` to figure out what
423 // kind of artifact is associated with this dependency.
424 let artifact = if build_runner.only_requires_rmeta(unit, &dep.unit) {
425 Artifact::Metadata
426 } else {
427 Artifact::All
428 };
429 (dep.unit.clone(), artifact)
430 })
431 .collect::<HashMap<_, _>>();
432
433 // This is somewhat tricky, but we may need to synthesize some
434 // dependencies for this target if it requires full upstream
435 // compilations to have completed. Because of pipelining, some
436 // dependency edges may be `Metadata` due to the above clause (as
437 // opposed to everything being `All`). For example consider:
438 //
439 // a (binary)
440 // └ b (lib)
441 // └ c (lib)
442 //
443 // Here the dependency edge from B to C will be `Metadata`, and the
444 // dependency edge from A to B will be `All`. For A to be compiled,
445 // however, it currently actually needs the full rlib of C. This means
446 // that we need to synthesize a dependency edge for the dependency graph
447 // from A to C. That's done here.
448 //
449 // This will walk all dependencies of the current target, and if any of
450 // *their* dependencies are `Metadata` then we depend on the `All` of
451 // the target as well. This should ensure that edges changed to
452 // `Metadata` propagate upwards `All` dependencies to anything that
453 // transitively contains the `Metadata` edge.
454 if unit.requires_upstream_objects() {
455 for dep in dependencies {
456 depend_on_deps_of_deps(build_runner, &mut queue_deps, dep.unit.clone());
457 }
458
459 fn depend_on_deps_of_deps(
460 build_runner: &BuildRunner<'_, '_>,
461 deps: &mut HashMap<Unit, Artifact>,
462 unit: Unit,
463 ) {
464 for dep in build_runner.unit_deps(&unit) {
465 if deps.insert(dep.unit.clone(), Artifact::All).is_none() {
466 depend_on_deps_of_deps(build_runner, deps, dep.unit.clone());
467 }
468 }
469 }
470 }
471
472 // For now we use a fixed placeholder value for the cost of each unit, but
473 // in the future this could be used to allow users to provide hints about
474 // relative expected costs of units, or this could be automatically set in
475 // a smarter way using timing data from a previous compilation.
476 self.queue.queue(unit.clone(), job, queue_deps, 100);
477 *self.counts.entry(unit.pkg.package_id()).or_insert(0) += 1;
478 Ok(())
479 }
480
481 /// Executes all jobs necessary to build the dependency graph.
482 ///
483 /// This function will spawn off `config.jobs()` workers to build all of the
484 /// necessary dependencies, in order. Freshness is propagated as far as
485 /// possible along each dependency chain.
486 #[tracing::instrument(skip_all)]
487 pub fn execute(mut self, build_runner: &mut BuildRunner<'_, '_>) -> CargoResult<()> {
488 self.queue.queue_finished();
489
490 let progress =
491 Progress::with_style("Building", ProgressStyle::Ratio, build_runner.bcx.gctx);
492 let state = DrainState {
493 total_units: self.queue.len(),
494 queue: self.queue,
495 // 100 here is somewhat arbitrary. It is a few screenfulls of
496 // output, and hopefully at most a few megabytes of memory for
497 // typical messages. If you change this, please update the test
498 // caching_large_output, too.
499 messages: Arc::new(Queue::new(100)),
500 diag_dedupe: DiagDedupe::new(build_runner.bcx.gctx),
501 warning_count: HashMap::new(),
502 active: HashMap::new(),
503 compiled: HashSet::new(),
504 documented: HashSet::new(),
505 scraped: HashSet::new(),
506 counts: self.counts,
507 progress,
508 next_id: 0,
509 timings: self.timings,
510 unused_dep_state: UnusedDepState::new(build_runner),
511 index_to_unit: build_runner
512 .bcx
513 .unit_to_index
514 .iter()
515 .map(|(unit, &index)| (index, unit.clone()))
516 .collect(),
517 tokens: Vec::new(),
518 pending_queue: Vec::new(),
519 print: DiagnosticPrinter::new(
520 build_runner.bcx.gctx,
521 &build_runner.bcx.rustc().workspace_wrapper,
522 ),
523 finished: 0,
524 per_package_future_incompat_reports: Vec::new(),
525 };
526
527 // Create a helper thread for acquiring jobserver tokens
528 let messages = state.messages.clone();
529 let helper = build_runner
530 .jobserver
531 .clone()
532 .into_helper_thread(move |token| {
533 messages.push(Message::Token(token));
534 })
535 .context("failed to create helper thread for jobserver management")?;
536
537 // Create a helper thread to manage the diagnostics for rustfix if
538 // necessary.
539 let messages = state.messages.clone();
540 // It is important that this uses `push` instead of `push_bounded` for
541 // now. If someone wants to fix this to be bounded, the `drop`
542 // implementation needs to be changed to avoid possible deadlocks.
543 let _diagnostic_server = build_runner
544 .bcx
545 .build_config
546 .rustfix_diagnostic_server
547 .borrow_mut()
548 .take()
549 .map(move |srv| srv.start(move |msg| messages.push(Message::FixDiagnostic(msg))));
550
551 thread::scope(move |scope| {
552 let (result,) = state.drain_the_queue(build_runner, scope, &helper);
553 result
554 })
555 }
556}
557
558impl<'gctx> DrainState<'gctx> {
559 fn spawn_work_if_possible<'s>(
560 &mut self,
561 build_runner: &mut BuildRunner<'_, '_>,
562 jobserver_helper: &HelperThread,
563 scope: &'s Scope<'s, '_>,
564 ) -> CargoResult<()> {
565 // Dequeue as much work as we can, learning about everything
566 // possible that can run. Note that this is also the point where we
567 // start requesting job tokens. Each job after the first needs to
568 // request a token.
569 while let Some((unit, job, priority)) = self.queue.dequeue() {
570 // We want to keep the pieces of work in the `pending_queue` sorted
571 // by their priorities, and insert the current job at its correctly
572 // sorted position: following the lower priority jobs, and the ones
573 // with the same priority (since they were dequeued before the
574 // current one, we also keep that relation).
575 let idx = self
576 .pending_queue
577 .partition_point(|&(_, _, p)| p <= priority);
578 self.pending_queue.insert(idx, (unit, job, priority));
579 if self.active.len() + self.pending_queue.len() > 1 {
580 jobserver_helper.request_token();
581 }
582 }
583
584 // Now that we've learned of all possible work that we can execute
585 // try to spawn it so long as we've got a jobserver token which says
586 // we're able to perform some parallel work.
587 // The `pending_queue` is sorted in ascending priority order, and we
588 // remove items from its end to schedule the highest priority items
589 // sooner.
590 while self.has_extra_tokens() && !self.pending_queue.is_empty() {
591 let (unit, job, _) = self.pending_queue.pop().unwrap();
592 *self.counts.get_mut(&unit.pkg.package_id()).unwrap() -= 1;
593 // Print out some nice progress information.
594 // NOTE: An error here will drop the job without starting it.
595 // That should be OK, since we want to exit as soon as
596 // possible during an error.
597 self.note_working_on(
598 build_runner.bcx.gctx,
599 build_runner.bcx.ws.root(),
600 &unit,
601 job.freshness(),
602 )?;
603 self.run(&unit, job, build_runner, scope);
604 }
605
606 Ok(())
607 }
608
609 fn has_extra_tokens(&self) -> bool {
610 self.active.len() < self.tokens.len() + 1
611 }
612
613 fn handle_event(
614 &mut self,
615 build_runner: &mut BuildRunner<'_, '_>,
616 event: Message,
617 ) -> Result<(), ErrorToHandle> {
618 let warning_handling = build_runner.bcx.gctx.warning_handling()?;
619 match event {
620 Message::Run(id, cmd) => {
621 build_runner
622 .bcx
623 .gctx
624 .shell()
625 .verbose(|c| c.status("Running", &cmd))?;
626 self.timings
627 .unit_start(build_runner, id, self.active[&id].clone());
628 }
629 Message::Stdout(out) => {
630 writeln!(build_runner.bcx.gctx.shell().out(), "{}", out)?;
631 }
632 Message::Stderr(err) => {
633 let mut shell = build_runner.bcx.gctx.shell();
634 shell.print_ansi_stderr(err.as_bytes())?;
635 shell.err().write_all(b"\n")?;
636 }
637 Message::Diagnostic {
638 id,
639 level,
640 diag,
641 lint,
642 fixable,
643 } => {
644 let emitted = self.diag_dedupe.emit_diag(&diag)?;
645 if level == "warning" {
646 self.bump_warning_count(id, lint, emitted, fixable);
647 }
648 if level == "error" {
649 let count = self.warning_count.entry(id).or_default();
650 // If there is an error, the `cargo fix` message should not show
651 count.disallow_fixable();
652 }
653 }
654 Message::Warning { id, warning } => {
655 build_runner.bcx.gctx.shell().warn(warning)?;
656 let lint = false;
657 let emitted = true;
658 let fixable = false;
659 self.bump_warning_count(id, lint, emitted, fixable);
660 }
661 Message::WarningCount {
662 id,
663 lint,
664 emitted,
665 fixable,
666 } => {
667 self.bump_warning_count(id, lint, emitted, fixable);
668 }
669 Message::FixDiagnostic(msg) => {
670 self.print.print(&msg)?;
671 }
672 Message::Finish(id, artifact, mut result) => {
673 let unit = match artifact {
674 // If `id` has completely finished we remove it
675 // from the `active` map ...
676 Artifact::All => {
677 trace!("end: {:?}", id);
678 self.finished += 1;
679 let unit = self.active.remove(&id).unwrap();
680 // An error could add an entry for a `Unit`
681 // with 0 warnings but having fixable
682 // warnings be disallowed
683 let count = self
684 .warning_count
685 .get(&id)
686 .filter(|count| 0 < count.total)
687 .cloned();
688 if let Some(count) = count {
689 let denied_warnings =
690 warning_handling == WarningHandling::Deny && 0 < count.lints;
691 self.report_warning_count(
692 build_runner,
693 &unit,
694 &count,
695 &build_runner.bcx.rustc().workspace_wrapper,
696 denied_warnings,
697 );
698 let stop_on_warnings =
699 denied_warnings && !build_runner.bcx.build_config.keep_going;
700 if stop_on_warnings {
701 result = Err(anyhow::format_err!(
702 "warnings are denied by `build.warnings` configuration"
703 ))
704 }
705 }
706 unit
707 }
708 // ... otherwise if it hasn't finished we leave it
709 // in there as we'll get another `Finish` later on.
710 Artifact::Metadata => {
711 trace!("end (meta): {:?}", id);
712 self.active[&id].clone()
713 }
714 };
715 debug!("end ({:?}): {:?}", unit, result);
716 match result {
717 Ok(()) => self.finish(id, &unit, artifact, build_runner)?,
718 Err(_) if build_runner.bcx.unit_can_fail_for_docscraping(&unit) => {
719 build_runner
720 .failed_scrape_units
721 .lock()
722 .unwrap()
723 .insert(build_runner.files().metadata(&unit).unit_id());
724 self.queue.finish(&unit, &artifact);
725 }
726 Err(error) => {
727 let show_warnings = true;
728 self.emit_log_messages(&unit, build_runner, show_warnings)?;
729 self.back_compat_notice(build_runner, &unit)?;
730 return Err(ErrorToHandle {
731 error,
732 print_always: true,
733 });
734 }
735 }
736 }
737 Message::FutureIncompatReport(id, items) => {
738 let unit = &self.active[&id];
739 let package_id = unit.pkg.package_id();
740 let is_local = unit.is_local();
741 self.per_package_future_incompat_reports
742 .push(FutureIncompatReportPackage {
743 package_id,
744 is_local,
745 items,
746 });
747 }
748 Message::UnusedExterns(id, unused_externs) => {
749 let unit = &self.active[&id];
750 self.unused_dep_state
751 .record_unused_externs_for_unit(unit, unused_externs);
752 }
753 Message::Token(acquired_token) => {
754 let token = acquired_token.context("failed to acquire jobserver token")?;
755 self.tokens.push(token);
756 }
757 Message::SectionTiming(id, section) => {
758 self.timings.unit_section_timing(build_runner, id, §ion);
759 }
760 }
761
762 Ok(())
763 }
764
765 // This will also tick the progress bar as appropriate
766 fn wait_for_events(&mut self) -> Vec<Message> {
767 // Drain all events at once to avoid displaying the progress bar
768 // unnecessarily. If there's no events we actually block waiting for
769 // an event, but we keep a "heartbeat" going to allow `record_cpu`
770 // to run above to calculate CPU usage over time. To do this we
771 // listen for a message with a timeout, and on timeout we run the
772 // previous parts of the loop again.
773 let mut events = self.messages.try_pop_all();
774 if events.is_empty() {
775 loop {
776 self.tick_progress();
777 self.tokens.truncate(self.active.len() - 1);
778 match self.messages.pop(Duration::from_millis(500)) {
779 Some(message) => {
780 events.push(message);
781 break;
782 }
783 None => continue,
784 }
785 }
786 }
787 events
788 }
789
790 /// This is the "main" loop, where Cargo does all work to run the
791 /// compiler.
792 ///
793 /// This returns a tuple of `Result` to prevent the use of `?` on
794 /// `Result` types because it is important for the loop to
795 /// carefully handle errors.
796 fn drain_the_queue<'s>(
797 mut self,
798 build_runner: &mut BuildRunner<'_, '_>,
799 scope: &'s Scope<'s, '_>,
800 jobserver_helper: &HelperThread,
801 ) -> (Result<(), anyhow::Error>,) {
802 trace!("queue: {:#?}", self.queue);
803
804 // Iteratively execute the entire dependency graph. Each turn of the
805 // loop starts out by scheduling as much work as possible (up to the
806 // maximum number of parallel jobs we have tokens for). A local queue
807 // is maintained separately from the main dependency queue as one
808 // dequeue may actually dequeue quite a bit of work (e.g., 10 binaries
809 // in one package).
810 //
811 // After a job has finished we update our internal state if it was
812 // successful and otherwise wait for pending work to finish if it failed
813 // and then immediately return (or keep going, if requested by the build
814 // config).
815 let mut errors = ErrorsDuringDrain { count: 0 };
816 // CAUTION! Do not use `?` or break out of the loop early. Every error
817 // must be handled in such a way that the loop is still allowed to
818 // drain event messages.
819 loop {
820 if errors.count == 0 || build_runner.bcx.build_config.keep_going {
821 if let Err(e) = self.spawn_work_if_possible(build_runner, jobserver_helper, scope) {
822 self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, e);
823 }
824 }
825
826 // If after all that we're not actually running anything then we're
827 // done!
828 if self.active.is_empty() {
829 break;
830 }
831
832 // And finally, before we block waiting for the next event, drop any
833 // excess tokens we may have accidentally acquired. Due to how our
834 // jobserver interface is architected we may acquire a token that we
835 // don't actually use, and if this happens just relinquish it back
836 // to the jobserver itself.
837 for event in self.wait_for_events() {
838 if let Err(event_err) = self.handle_event(build_runner, event) {
839 self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, event_err);
840 }
841 }
842 }
843 self.progress.clear();
844
845 if build_runner.bcx.gctx.cli_unstable().cargo_lints {
846 let mut warn_count = 0;
847 let mut error_count = 0;
848 drop(self.unused_dep_state.emit_unused_warnings(
849 &mut warn_count,
850 &mut error_count,
851 build_runner,
852 ));
853 errors.count += error_count;
854 build_runner.compilation.lint_warning_count += warn_count;
855 }
856
857 let profile_name = build_runner.bcx.build_config.requested_profile;
858 // NOTE: this may be a bit inaccurate, since this may not display the
859 // profile for what was actually built. Profile overrides can change
860 // these settings, and in some cases different targets are built with
861 // different profiles. To be accurate, it would need to collect a
862 // list of Units built, and maybe display a list of the different
863 // profiles used. However, to keep it simple and compatible with old
864 // behavior, we just display what the base profile is.
865 let profile = build_runner.bcx.profiles.base_profile();
866 let mut opt_type = String::from(if profile.opt_level.as_str() == "0" {
867 "unoptimized"
868 } else {
869 "optimized"
870 });
871 if profile.debuginfo.is_turned_on() {
872 opt_type += " + debuginfo";
873 }
874
875 let time_elapsed = util::elapsed(build_runner.bcx.gctx.creation_time().elapsed());
876 if let Err(e) = self
877 .timings
878 .finished(build_runner, &errors.to_error())
879 .context("failed to render timing report")
880 {
881 self.handle_error(&mut build_runner.bcx.gctx.shell(), &mut errors, e);
882 }
883 if build_runner.bcx.build_config.emit_json() {
884 let mut shell = build_runner.bcx.gctx.shell();
885 let msg = machine_message::BuildFinished {
886 success: errors.count == 0,
887 }
888 .to_json_string();
889 if let Err(e) = writeln!(shell.out(), "{}", msg) {
890 self.handle_error(&mut shell, &mut errors, e);
891 }
892 }
893
894 if let Some(error) = errors.to_error() {
895 // Any errors up to this point have already been printed via the
896 // `display_error` inside `handle_error`.
897 (Err(anyhow::Error::new(AlreadyPrintedError::new(error))),)
898 } else if self.queue.is_empty() && self.pending_queue.is_empty() {
899 let profile_link = build_runner.bcx.gctx.shell().err_hyperlink(
900 "https://doc.rust-lang.org/cargo/reference/profiles.html#default-profiles",
901 );
902 let message = format!(
903 "{profile_link}`{profile_name}` profile [{opt_type}]{profile_link:#} target(s) in {time_elapsed}",
904 );
905 // It doesn't really matter if this fails.
906 let _ = build_runner.bcx.gctx.shell().status("Finished", message);
907 future_incompat::save_and_display_report(
908 build_runner.bcx,
909 &self.per_package_future_incompat_reports,
910 );
911
912 (Ok(()),)
913 } else {
914 debug!("queue: {:#?}", self.queue);
915 (Err(internal("finished with jobs still left in the queue")),)
916 }
917 }
918
919 fn handle_error(
920 &mut self,
921 shell: &mut Shell,
922 err_state: &mut ErrorsDuringDrain,
923 new_err: impl Into<ErrorToHandle>,
924 ) {
925 let new_err = new_err.into();
926 if new_err.print_always || err_state.count == 0 {
927 crate::display_error(&new_err.error, shell);
928 if err_state.count == 0 && !self.active.is_empty() {
929 self.progress.indicate_error();
930 let _ = shell.warn("build failed, waiting for other jobs to finish...");
931 }
932 err_state.count += 1;
933 } else {
934 tracing::warn!("{:?}", new_err.error);
935 }
936 }
937
938 // This also records CPU usage and marks concurrency; we roughly want to do
939 // this as often as we spin on the events receiver (at least every 500ms or
940 // so).
941 fn tick_progress(&mut self) {
942 // Record some timing information if `--timings` is enabled, and
943 // this'll end up being a noop if we're not recording this
944 // information.
945 self.timings.record_cpu();
946
947 let active_names = self
948 .active
949 .values()
950 .map(|u| self.name_for_progress(u))
951 .collect::<Vec<_>>();
952 let _ = self.progress.tick_now(
953 self.finished,
954 self.total_units,
955 &format!(": {}", active_names.join(", ")),
956 );
957 }
958
959 fn name_for_progress(&self, unit: &Unit) -> String {
960 let pkg_name = unit.pkg.name();
961 let target_name = unit.target.name();
962 match unit.mode {
963 CompileMode::Doc { .. } => format!("{}(doc)", pkg_name),
964 CompileMode::RunCustomBuild => format!("{}(build)", pkg_name),
965 CompileMode::Test | CompileMode::Check { test: true } => match unit.target.kind() {
966 TargetKind::Lib(_) => format!("{}(test)", target_name),
967 TargetKind::CustomBuild => panic!("cannot test build script"),
968 TargetKind::Bin => format!("{}(bin test)", target_name),
969 TargetKind::Test => format!("{}(test)", target_name),
970 TargetKind::Bench => format!("{}(bench)", target_name),
971 TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
972 format!("{}(example test)", target_name)
973 }
974 },
975 _ => match unit.target.kind() {
976 TargetKind::Lib(_) => pkg_name.to_string(),
977 TargetKind::CustomBuild => format!("{}(build.rs)", pkg_name),
978 TargetKind::Bin => format!("{}(bin)", target_name),
979 TargetKind::Test => format!("{}(test)", target_name),
980 TargetKind::Bench => format!("{}(bench)", target_name),
981 TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
982 format!("{}(example)", target_name)
983 }
984 },
985 }
986 }
987
988 /// Executes a job.
989 ///
990 /// Fresh jobs block until finished (which should be very fast!), Dirty
991 /// jobs will spawn a thread in the background and return immediately.
992 fn run<'s>(
993 &mut self,
994 unit: &Unit,
995 job: Job,
996 build_runner: &BuildRunner<'_, '_>,
997 scope: &'s Scope<'s, '_>,
998 ) {
999 let id = JobId(self.next_id);
1000 self.next_id = self.next_id.checked_add(1).unwrap();
1001
1002 debug!("start {}: {:?}", id, unit);
1003
1004 assert!(self.active.insert(id, unit.clone()).is_none());
1005
1006 let messages = self.messages.clone();
1007 let is_fresh = job.freshness().is_fresh();
1008 let rmeta_required = build_runner.rmeta_required(unit);
1009 let lock_manager = build_runner.lock_manager.clone();
1010 let warning_handling = build_runner.bcx.gctx.warning_handling().unwrap_or_default();
1011
1012 let doit = move |diag_dedupe| {
1013 let state = JobState::new(
1014 id,
1015 messages,
1016 diag_dedupe,
1017 rmeta_required,
1018 lock_manager,
1019 warning_handling,
1020 );
1021 state.run_to_finish(job);
1022 };
1023
1024 match is_fresh {
1025 true => {
1026 // Running a fresh job on the same thread is often much faster than spawning a new
1027 // thread to run the job.
1028 doit(Some(&self.diag_dedupe));
1029 }
1030 false => {
1031 scope.spawn(move || doit(None));
1032 }
1033 }
1034 }
1035
1036 fn emit_log_messages(
1037 &self,
1038 unit: &Unit,
1039 build_runner: &mut BuildRunner<'_, '_>,
1040 show_warnings: bool,
1041 ) -> CargoResult<()> {
1042 let outputs = build_runner.build_script_outputs.lock().unwrap();
1043 let Some(metadata_vec) = build_runner.find_build_script_metadatas(unit) else {
1044 return Ok(());
1045 };
1046 let bcx = &mut build_runner.bcx;
1047 for metadata in metadata_vec {
1048 if let Some(output) = outputs.get(metadata) {
1049 if !output.log_messages.is_empty()
1050 && (show_warnings
1051 || output
1052 .log_messages
1053 .iter()
1054 .any(|(severity, _)| *severity == Severity::Error))
1055 {
1056 let msg_with_package =
1057 |msg: &str| format!("{}@{}: {}", unit.pkg.name(), unit.pkg.version(), msg);
1058
1059 for (severity, message) in output.log_messages.iter() {
1060 match severity {
1061 Severity::Error => {
1062 bcx.gctx.shell().error(msg_with_package(message))?;
1063 }
1064 Severity::Warning => {
1065 bcx.gctx.shell().warn(msg_with_package(message))?;
1066 }
1067 }
1068 }
1069 }
1070 }
1071 }
1072
1073 Ok(())
1074 }
1075
1076 fn bump_warning_count(&mut self, id: JobId, lint: bool, emitted: bool, fixable: bool) {
1077 let count = self.warning_count.entry(id).or_default();
1078 count.total += 1;
1079 if lint {
1080 let unit = self.active.get(&id).unwrap();
1081 // If this is an upstream dep but we *do* want warnings, make sure that they
1082 // don't fail compilation.
1083 if unit.is_local() {
1084 count.lints += 1;
1085 }
1086 }
1087 if !emitted {
1088 count.duplicates += 1;
1089 // Don't add to fixable if it's already been emitted
1090 } else if fixable {
1091 // Do not add anything to the fixable warning count if
1092 // is `NotAllowed` since that indicates there was an
1093 // error while building this `Unit`
1094 if count.fixable_allowed() {
1095 count.fixable = match count.fixable {
1096 FixableWarnings::NotAllowed => FixableWarnings::NotAllowed,
1097 FixableWarnings::Zero => FixableWarnings::Positive(1),
1098 FixableWarnings::Positive(fixable) => FixableWarnings::Positive(fixable + 1),
1099 };
1100 }
1101 }
1102 }
1103
1104 /// Displays a final report of the warnings emitted by a particular job.
1105 fn report_warning_count(
1106 &mut self,
1107 runner: &mut BuildRunner<'_, '_>,
1108 unit: &Unit,
1109 count: &WarningCount,
1110 rustc_workspace_wrapper: &Option<PathBuf>,
1111 denied_warnings: bool,
1112 ) {
1113 let gctx = runner.bcx.gctx;
1114 runner.compilation.lint_warning_count += count.lints;
1115 let mut message = descriptive_pkg_name(&unit.pkg.name(), &unit.target, &unit.mode);
1116 message.push_str(" generated ");
1117 match count.total {
1118 1 => message.push_str("1 warning"),
1119 n => {
1120 let _ = write!(message, "{} warnings", n);
1121 }
1122 };
1123 match count.duplicates {
1124 0 => {}
1125 1 => message.push_str(" (1 duplicate)"),
1126 n => {
1127 let _ = write!(message, " ({} duplicates)", n);
1128 }
1129 }
1130 // Only show the `cargo fix` message if its a local `Unit`
1131 if unit.is_local() {
1132 // Do not show this if there are any errors or no fixable warnings
1133 if let FixableWarnings::Positive(fixable) = count.fixable {
1134 // `cargo fix` doesn't have an option for custom builds
1135 if !unit.target.is_custom_build() {
1136 // To make sure the correct command is shown for `clippy` we
1137 // check if `RUSTC_WORKSPACE_WRAPPER` is set and pointing towards
1138 // `clippy-driver`.
1139 let clippy = std::ffi::OsStr::new("clippy-driver");
1140 let is_clippy = rustc_workspace_wrapper.as_ref().and_then(|x| x.file_stem())
1141 == Some(clippy);
1142
1143 let command = if is_clippy {
1144 "cargo clippy --fix"
1145 } else {
1146 "cargo fix"
1147 };
1148
1149 let mut args =
1150 format!("{} -p {}", unit.target.description_named(), unit.pkg.name());
1151 if unit.mode.is_rustc_test()
1152 && !(unit.target.is_test() || unit.target.is_bench())
1153 {
1154 args.push_str(" --tests");
1155 }
1156 let mut suggestions = format!("{} suggestion", fixable);
1157 if fixable > 1 {
1158 suggestions.push_str("s")
1159 }
1160
1161 #[expect(clippy::disallowed_methods, reason = "consistency with clippy")]
1162 let _ = write!(
1163 message,
1164 " (run `{command} --{args}{}` to apply {suggestions})",
1165 if let Some(cli_lints_os) = env::var_os("CLIPPY_ARGS")
1166 && let Ok(cli_lints) = cli_lints_os.into_string()
1167 && is_clippy
1168 {
1169 // Clippy can take lints through the CLI, each lint flag is separated by "__CLIPPY_HACKERY__".
1170 let cli_lints = cli_lints.replace("__CLIPPY_HACKERY__", " ");
1171 let cli_lints = cli_lints.trim_ascii_end(); // Remove that last space left by __CLIPPY_HACKERY__
1172 format!(" -- {cli_lints}")
1173 } else {
1174 "".to_owned()
1175 }
1176 );
1177 }
1178 }
1179 }
1180 // Errors are ignored here because it is tricky to handle them
1181 // correctly, and they aren't important.
1182 let _ = if denied_warnings {
1183 gctx.shell().error(message)
1184 } else {
1185 gctx.shell().warn(message)
1186 };
1187 }
1188
1189 fn finish(
1190 &mut self,
1191 id: JobId,
1192 unit: &Unit,
1193 artifact: Artifact,
1194 build_runner: &mut BuildRunner<'_, '_>,
1195 ) -> CargoResult<()> {
1196 if unit.mode.is_run_custom_build() {
1197 self.emit_log_messages(
1198 unit,
1199 build_runner,
1200 unit.show_warnings(build_runner.bcx.gctx),
1201 )?;
1202 }
1203 let unblocked = self.queue.finish(unit, &artifact);
1204 match artifact {
1205 Artifact::All => self.timings.unit_finished(build_runner, id, unblocked),
1206 Artifact::Metadata => self
1207 .timings
1208 .unit_rmeta_finished(build_runner, id, unblocked),
1209 }
1210 Ok(())
1211 }
1212
1213 // This isn't super trivial because we don't want to print loads and
1214 // loads of information to the console, but we also want to produce a
1215 // faithful representation of what's happening. This is somewhat nuanced
1216 // as a package can start compiling *very* early on because of custom
1217 // build commands and such.
1218 //
1219 // In general, we try to print "Compiling" for the first nontrivial task
1220 // run for a package, regardless of when that is. We then don't print
1221 // out any more information for a package after we've printed it once.
1222 fn note_working_on(
1223 &mut self,
1224 gctx: &GlobalContext,
1225 ws_root: &Path,
1226 unit: &Unit,
1227 fresh: &Freshness,
1228 ) -> CargoResult<()> {
1229 if (self.compiled.contains(&unit.pkg.package_id())
1230 && !unit.mode.is_doc()
1231 && !unit.mode.is_doc_scrape())
1232 || (self.documented.contains(&unit.pkg.package_id()) && unit.mode.is_doc())
1233 || (self.scraped.contains(&unit.pkg.package_id()) && unit.mode.is_doc_scrape())
1234 {
1235 return Ok(());
1236 }
1237
1238 match fresh {
1239 // Any dirty stage which runs at least one command gets printed as
1240 // being a compiled package.
1241 Dirty(dirty_reason) => {
1242 if !dirty_reason.is_fresh_build() {
1243 gctx.shell().verbose(|shell| {
1244 dirty_reason.present_to(shell, unit, ws_root, &self.index_to_unit)
1245 })?;
1246 }
1247
1248 if unit.mode.is_doc() {
1249 self.documented.insert(unit.pkg.package_id());
1250 gctx.shell().status("Documenting", &unit.pkg)?;
1251 } else if unit.mode.is_doc_test() {
1252 // Skip doc test.
1253 } else if unit.mode.is_doc_scrape() {
1254 self.scraped.insert(unit.pkg.package_id());
1255 gctx.shell().status("Scraping", &unit.pkg)?;
1256 } else {
1257 self.compiled.insert(unit.pkg.package_id());
1258 if unit.mode.is_check() {
1259 gctx.shell().status("Checking", &unit.pkg)?;
1260 } else {
1261 gctx.shell().status("Compiling", &unit.pkg)?;
1262 }
1263 }
1264 }
1265 Fresh => {
1266 // If doc test are last, only print "Fresh" if nothing has been printed.
1267 if self.counts[&unit.pkg.package_id()] == 0
1268 && !(unit.mode.is_doc_test() && self.compiled.contains(&unit.pkg.package_id()))
1269 {
1270 self.compiled.insert(unit.pkg.package_id());
1271 gctx.shell().verbose(|c| c.status("Fresh", &unit.pkg))?;
1272 }
1273 }
1274 }
1275 Ok(())
1276 }
1277
1278 fn back_compat_notice(
1279 &self,
1280 build_runner: &BuildRunner<'_, '_>,
1281 unit: &Unit,
1282 ) -> CargoResult<()> {
1283 if unit.pkg.name() != "diesel"
1284 || unit.pkg.version() >= &Version::new(1, 4, 8)
1285 || build_runner.bcx.ws.resolve_behavior() == ResolveBehavior::V1
1286 || !unit.pkg.package_id().source_id().is_registry()
1287 || !unit.features.is_empty()
1288 {
1289 return Ok(());
1290 }
1291 if !build_runner
1292 .bcx
1293 .unit_graph
1294 .keys()
1295 .any(|unit| unit.pkg.name() == "diesel" && !unit.features.is_empty())
1296 {
1297 return Ok(());
1298 }
1299 build_runner.bcx.gctx.shell().note(
1300 "\
1301This error may be due to an interaction between diesel and Cargo's new
1302feature resolver. Try updating to diesel 1.4.8 to fix this error.
1303",
1304 )?;
1305 Ok(())
1306 }
1307}
1308
1309impl ErrorsDuringDrain {
1310 fn to_error(&self) -> Option<anyhow::Error> {
1311 match self.count {
1312 0 => None,
1313 1 => Some(format_err!("1 job failed")),
1314 n => Some(format_err!("{} jobs failed", n)),
1315 }
1316 }
1317}