1use std::collections::{BTreeMap, BTreeSet};
6use std::path::Path;
7
8use super::lines;
9use super::{Block, Document, Note, Row};
10use crate::protocol::display::{Line, Role};
11use crate::protocol::vocabulary::{Ago, Files, IntentLine, Mark, Plural};
12use crate::{Confidence, FileChange, ImportSite, Match, Notice, Occurrence, Reason, Respelling};
13
14#[derive(Debug, Clone, Copy, Default)]
16pub struct Options {
17 pub verbose: bool,
19 pub diff: bool,
21}
22
23#[derive(Debug, Clone, Default)]
25pub struct Presentation {
26 pub body: Vec<Row>,
28 pub notes: Vec<Row>,
31}
32
33pub trait View {
39 fn rows(&self, block: &Block, options: Options, width: usize) -> Vec<Row>;
43
44 fn present(&self, report: &Document, options: Options, width: usize) -> Presentation {
46 let (body, notes) = report.parts();
47 Presentation {
48 body: body
49 .iter()
50 .flat_map(|block| self.rows(block, options, width))
51 .collect(),
52 notes: notes
53 .iter()
54 .flat_map(|block| self.rows(block, options, width))
55 .collect(),
56 }
57 }
58
59 fn occurrence(
63 &self,
64 occurrence: &Occurrence,
65 ordinal: usize,
66 ticked: bool,
67 width: usize,
68 ) -> Row;
69
70 fn relation(&self, occurrence: &Occurrence, ordinal: usize, width: usize) -> Row {
73 self.occurrence(occurrence, ordinal, false, width)
74 }
75
76 fn respelling(&self, respelling: &Respelling, width: usize) -> Row;
78
79 fn notice(&self, notice: &Notice, width: usize) -> Row;
81
82 fn rewrite(&self, m: &Match, ordinal: usize, ticked: bool, width: usize) -> Row;
84}
85
86#[derive(Debug, Default)]
88pub struct Detailed;
89
90impl View for Detailed {
91 fn rows(&self, block: &Block, options: Options, _width: usize) -> Vec<Row> {
92 match block {
93 Block::Title(text) => vec![
94 Row::new(Line::single(Role::Title, text.clone())),
95 Row::new(Line::new()),
96 ],
97 Block::Heading(text) => vec![Row::new(Line::single(Role::Strong, text.clone()))],
98 Block::Declarations(declarations) => declarations
99 .iter()
100 .map(|m| {
101 Row::at(
102 lines::Declaration::new(m).line(),
103 m.path.clone(),
104 m.start.line,
105 )
106 })
107 .collect(),
108 Block::Matches(matches) => lines::Sections::new(matches).lines(),
109 Block::Verdicts { occurrences, plan } => {
110 let files = plan.as_ref().map(|plan| plan.files.as_slice());
111 let mut rows = VerdictRows::new(occurrences, files, options).rows();
112 if options.diff
113 && let Some(plan) = plan
114 {
115 rows.extend(self.changes(&plan.files, plan.state));
116 }
117 rows
118 }
119 Block::Outline { path, items } => lines::OutlineTree::new(items)
120 .lines()
121 .into_iter()
122 .zip(items)
123 .map(|(mut line, item)| {
124 if options.verbose
125 && let Some(reach) = &item.reach
126 {
127 line = line
128 .and(Role::Plain, " ")
129 .and(Role::Dim, reach.to_string());
130 }
131 Row::at(line, path.clone(), item.start.line)
132 })
133 .collect(),
134 Block::Relationships(items) => items
135 .iter()
136 .map(|item| {
137 let status = match &item.resolution {
138 crate::RelationshipResolution::Confirmed { .. } => "confirmed",
139 crate::RelationshipResolution::Ambiguous { .. } => "ambiguous",
140 crate::RelationshipResolution::Unavailable { .. } => "unresolved",
141 crate::RelationshipResolution::Indirect { .. } => "indirect",
142 };
143 Row::at(
144 Line::single(Role::Plain, &item.spelling)
145 .and(Role::Dim, format!(" [{status}] "))
146 .and(
147 Role::Path,
148 format!(
149 "{}:{}:{}",
150 item.site.path,
151 item.start.line + 1,
152 item.start.column + 1
153 ),
154 ),
155 item.site.path.clone(),
156 item.start.line,
157 )
158 })
159 .collect(),
160 Block::Locations(locations) => locations
161 .iter()
162 .map(|d| {
163 Row::at(
164 Line::single(Role::Plain, &d.name)
165 .and(Role::Plain, " ")
166 .and(Role::Path, d.target.declaration.path.to_string())
167 .and(
168 Role::Plain,
169 format!(":{}:{} [{}]", d.start.line + 1, d.start.column + 1, d.id),
170 ),
171 d.target.declaration.path.clone(),
172 d.start.line,
173 )
174 })
175 .collect(),
176 Block::SymbolMoveCandidates(candidates) => candidates
177 .iter()
178 .enumerate()
179 .map(|(index, candidate)| {
180 let declaration = &candidate.declaration;
181 let mut line = Line::single(Role::Ordinal, (index + 1).to_string())
182 .and(Role::Plain, format!(" {} ", declaration.id))
183 .and(Role::Path, declaration.path.to_string())
184 .and(
185 Role::LineNumber,
186 format!(":{} ", declaration.start.line + 1),
187 )
188 .and_line(Line::hit(declaration, Role::Plain));
189 if let Some(reason) = candidate.unsupported {
190 line = line.and(Role::Warning, format!(" ({reason})"));
191 }
192 Row::at(line, declaration.path.clone(), declaration.start.line)
193 })
194 .collect(),
195 Block::Sites(sites) => sites
196 .iter()
197 .flat_map(|site| lines::SiteLine::new(site).rows())
198 .collect(),
199 Block::Dead(items) => items
200 .iter()
201 .map(|item| {
202 let mut line = lines::PlacedLine::new(&item.declaration).line();
203 if item.unsure > 0 {
204 line = line
205 .and(Role::Plain, " ")
206 .and_line(Line::mark(Mark::Unverified))
207 .and(Role::Plain, " ")
208 .and(Role::Dim, item.unsure.to_string());
209 }
210 Row::at(
211 line,
212 item.declaration.path.clone(),
213 item.declaration.start.line,
214 )
215 })
216 .collect(),
217 Block::Exposed(items) => items
218 .iter()
219 .flat_map(|item| {
220 let mut rows = vec![Row::at(
221 lines::PlacedLine::new(&item.declaration)
222 .line()
223 .and(Role::Plain, " ")
224 .and_line(Line::mark(Mark::ImportedBy))
225 .and(Role::Plain, " ")
226 .and(Role::Strong, item.importers.to_string()),
227 item.declaration.path.clone(),
228 item.declaration.start.line,
229 )];
230 rows.extend(item.via.iter().map(|alias| {
231 Row::new(
232 Line::single(Role::Plain, " ")
233 .and_line(Line::mark(Mark::ReExport))
234 .and(Role::Plain, " ")
235 .and(Role::Address, alias.to_string()),
236 )
237 }));
238 rows
239 })
240 .collect(),
241 Block::Consumers(consumers) => {
242 let mut rows: Vec<Row> = Vec::new();
243 let mut depth = 0;
244 for consumer in consumers {
245 if consumer.depth != depth {
246 depth = consumer.depth;
247 let at_depth = consumers.iter().filter(|c| c.depth == depth).count();
248 rows.push(Row::new(Line::new()));
249 rows.push(Row::new(
250 Line::mark(Mark::ImportedBy)
251 .and(Role::Plain, " ")
252 .and(Role::Strong, at_depth.to_string())
253 .and(Role::Plain, " ")
254 .and(Role::Dim, format!("depth {depth}")),
255 ));
256 }
257 let mut line = Line::single(Role::Plain, " ")
258 .and(Role::Path, consumer.path.display().to_string());
259 if consumer.depth > 1 {
260 line = line.and(Role::Dim, format!(" via {}", consumer.through));
261 }
262 rows.push(Row::new(line));
263 }
264 rows
265 }
266 Block::History(entries) => {
267 let now = Ago::now();
268 let last = entries.len().saturating_sub(1);
269 Row::wrap(
270 entries
271 .iter()
272 .enumerate()
273 .map(|(i, item)| {
274 lines::HistoryLine::new(item, now).newest(i == last).line()
275 })
276 .collect(),
277 )
278 }
279 Block::Batch(intents) => Row::wrap(
280 intents
281 .iter()
282 .enumerate()
283 .map(|(i, intent)| {
284 Line::single(Role::Plain, " ")
285 .and(Role::Ordinal, (i + 1).to_string())
286 .and(Role::Plain, " ")
287 .and(Role::Plain, IntentLine(intent).to_string())
288 })
289 .collect(),
290 ),
291 Block::Undo { moves, restored } => {
292 let mut rows = Row::wrap(
293 moves
294 .iter()
295 .map(|(from, to)| {
296 Line::single(Role::Plain, " ")
297 .and(Role::Dim, to.display().to_string())
298 .and(Role::Plain, " ")
299 .and_line(Line::mark(Mark::Import))
300 .and(Role::Plain, " ")
301 .and(Role::Path, from.display().to_string())
302 })
303 .collect(),
304 );
305 rows.extend(restored.iter().map(|path| {
306 Row::new(
307 Line::single(Role::Plain, " ").and(Role::Path, path.display().to_string()),
308 )
309 }));
310 rows
311 }
312 Block::DepGroups { path, imports, own } => {
313 lines::DepGroups::new(path, imports, own.as_deref()).rows()
314 }
315 Block::Importers(importers) => lines::ImporterRows::new(importers).rows(),
316 Block::Explanation(result) => {
317 let mut rows = vec![Row::at(
318 Line::single(
319 Role::Strong,
320 format!("{}:{}", result.path.display(), result.position.display()),
321 ),
322 result.path.clone(),
323 result.position.line,
324 )];
325 if let Some(dep) = &result.import {
327 rows.push(Row::at(
328 Line::mark(Mark::Import)
329 .and(Role::Plain, " ")
330 .and(Role::Strong, dep.import.path.to_string()),
331 result.path.clone(),
332 dep.start.line,
333 ));
334 let file = dep
335 .file
336 .as_ref()
337 .map(|f| Line::single(Role::Path, f.display().to_string()));
338 match (&dep.origin, file) {
339 (Some(origin), file) => {
340 let mut line = Line::single(Role::Plain, " ")
341 .and_line(Line::mark(Mark::ReExport))
342 .and(Role::Plain, " ")
343 .and(Role::Address, origin.to_string())
344 .and(Role::Plain, " ");
345 if let Some(file) = file {
346 line = line.and_line(file);
347 }
348 rows.push(Row::new(line));
349 }
350 (None, Some(file)) => {
351 rows.push(Row::new(Line::single(Role::Plain, " ").and_line(file)));
352 }
353 (None, None) => {}
354 }
355 }
356 let Some(symbol) = &result.symbol else {
357 if result.import.is_none() {
358 rows.push(Row::new(
359 Line::mark(Mark::Nothing)
360 .and(Role::Plain, " ")
361 .and(Role::Dim, "not inside a declaration"),
362 ));
363 }
364 return rows;
365 };
366 if let (Some(declared), Some(line)) = (&result.declared, &result.line) {
367 rows.extend(
368 lines::Caret::new(
369 declared.line,
370 line,
371 declared.column as usize,
372 symbol.name.chars().count(),
373 )
374 .lines()
375 .into_iter()
376 .enumerate()
377 .map(|(index, line)| {
378 if index == 0 {
379 Row::at(line, result.path.clone(), declared.line)
380 } else {
381 Row::new(line)
382 }
383 }),
384 );
385 rows.push(Row::new(Line::new()));
386 }
387 let mut line = Line::mark(Mark::Declaration).and(Role::Plain, " ").and(
388 Role::Declaration,
389 format!("{} {}", symbol.kind, symbol.name),
390 );
391 if let Some(modifier) = symbol.modifier() {
392 line = line.and(Role::Plain, " ").and(Role::Symbol, modifier);
393 }
394 rows.push(Row::new(line));
395 if let Some(reach) = &result.reach {
396 rows.push(Row::new(
397 Line::single(Role::Plain, " ")
398 .and(Role::Dim, "reaches")
399 .and(Role::Plain, " ")
400 .and(Role::Plain, reach.to_string()),
401 ));
402 }
403 for alias in &result.via {
404 rows.push(Row::new(
405 Line::single(Role::Plain, " ")
406 .and_line(Line::mark(Mark::ReExport))
407 .and(Role::Plain, " ")
408 .and(Role::Address, alias.to_string()),
409 ));
410 }
411 rows.push(Row::new(
412 Line::mark(Mark::ImportedBy)
413 .and(Role::Plain, " ")
414 .and(Role::Strong, result.importers.len().to_string()),
415 ));
416 rows.extend(result.importers.iter().map(|path| {
417 Row::new(
418 Line::single(Role::Plain, " ").and(Role::Path, path.display().to_string()),
419 )
420 }));
421 rows
422 }
423 Block::Imports {
424 unresolved,
425 unused,
426 redundant,
427 } => {
428 let sections: [(Mark, &str, &[ImportSite]); 3] = [
429 (Mark::Nothing, "unresolved", unresolved),
430 (Mark::ByHand, "unused", unused),
431 (Mark::ByHand, "redundant", redundant),
432 ];
433 let mut rows = Vec::new();
434 let mut first = true;
435 for (mark, word, sites) in sections {
436 if sites.is_empty() {
437 continue;
438 }
439 if !first {
440 rows.push(Row::new(Line::new()));
441 }
442 first = false;
443 rows.push(Row::new(
444 Line::mark(mark)
445 .and(Role::Plain, " ")
446 .and(Role::Strong, word)
447 .and(Role::Plain, " ")
448 .and(Role::Dim, sites.len().to_string()),
449 ));
450 rows.extend(sites.iter().map(|site| {
451 Row::at(
452 lines::ImportSiteLine::new(site).line(),
453 site.path.clone(),
454 site.start.line,
455 )
456 }));
457 }
458 rows
459 }
460 Block::Line(line) | Block::Summary(line) => vec![Row::new(line.clone())],
461 Block::Note(Note::Hint(text)) => vec![Row::new(
462 Line::single(Role::Hint, "hint: ").and(Role::Plain, text.clone()),
463 )],
464 Block::Note(Note::Warning(line)) => vec![Row::new(
465 Line::single(Role::Warning, "warning: ").and_line(line.clone()),
466 )],
467 Block::Changes { state, files } => self.changes(files, *state),
468 Block::Moved {
469 state,
470 files,
471 respellings,
472 notices,
473 } => {
474 let structural: Vec<&FileChange> = files
475 .iter()
476 .filter(|f| lines::Diff::is_structural(f, respellings))
477 .collect();
478 let mut rows: Vec<Row> = Vec::new();
479 if !respellings.is_empty() {
480 rows.push(Row::new(
481 Line::mark(Mark::Import)
482 .and(Role::Plain, " ")
483 .and(Role::Strong, respellings.len().to_string())
484 .and(Role::Plain, " ")
485 .and(
486 Role::Dim,
487 Files::among(respellings.iter().map(|r| r.path.as_path()))
488 .to_string(),
489 ),
490 ));
491 }
492 if !structural.is_empty() {
493 rows.push(Row::new(
494 Line::mark(Mark::Structure)
495 .and(Role::Plain, " ")
496 .and(Role::Strong, structural.len().to_string())
497 .and(Role::Plain, " ")
498 .and(Role::Dim, Plural(structural.len(), "file").to_string()),
499 ));
500 }
501 if !notices.is_empty() {
502 rows.push(Row::new(
503 Line::mark(Mark::ByHand)
504 .and(Role::Plain, " ")
505 .and(Role::Strong, notices.len().to_string()),
506 ));
507 }
508 if !respellings.is_empty() || !notices.is_empty() {
509 rows.push(Row::new(Line::new()));
510 let width = respellings
511 .iter()
512 .map(|r| lines::Respellings::site(&r.path, r.start.line).len())
513 .chain(
514 notices
515 .iter()
516 .map(|n| lines::Respellings::site(&n.path, n.start.line).len()),
517 )
518 .max()
519 .unwrap_or(0);
520 rows.extend(lines::Respellings::new(respellings, width).rows());
521 rows.extend(notices.iter().map(|n| {
522 Row::at(
523 lines::NoticeRow::new(n, width).line(),
524 n.path.clone(),
525 n.start.line,
526 )
527 }));
528 }
529 for file in files {
530 let is_structural = lines::Diff::is_structural(file, respellings);
531 if !(options.diff || is_structural) {
532 continue;
533 }
534 rows.push(Row::new(Line::new()));
535 rows.extend(lines::Diff::new(file, is_structural).rows(*state));
536 }
537 rows
538 }
539 Block::Blank => vec![Row::new(Line::new())],
540 }
541 }
542
543 fn occurrence(
544 &self,
545 occurrence: &Occurrence,
546 ordinal: usize,
547 _ticked: bool,
548 _width: usize,
549 ) -> Row {
550 Row::at(
551 lines::MatchRow::numbered(&occurrence.m, ordinal),
552 occurrence.m.path.clone(),
553 occurrence.m.start.line,
554 )
555 }
556
557 fn respelling(&self, respelling: &Respelling, _width: usize) -> Row {
558 let site = lines::Respellings::site(&respelling.path, respelling.start.line).len();
559 Row::at(
560 lines::Respellings::row(respelling, site),
561 respelling.path.clone(),
562 respelling.start.line,
563 )
564 }
565
566 fn notice(&self, notice: &Notice, _width: usize) -> Row {
567 let site = lines::Respellings::site(¬ice.path, notice.start.line).len();
568 Row::at(
569 lines::NoticeRow::new(notice, site).line(),
570 notice.path.clone(),
571 notice.start.line,
572 )
573 }
574
575 fn rewrite(&self, m: &Match, ordinal: usize, _ticked: bool, _width: usize) -> Row {
576 Row::at(
577 lines::MatchRow::numbered(m, ordinal),
578 m.path.clone(),
579 m.start.line,
580 )
581 }
582}
583
584impl Detailed {
585 fn changes(&self, files: &[FileChange], state: crate::MutationState) -> Vec<Row> {
586 let mut rows = Vec::new();
587 for (i, file) in files.iter().enumerate() {
588 if i > 0 {
589 rows.push(Row::new(Line::new()));
590 }
591 rows.extend(lines::Diff::new(file, false).rows(state));
592 }
593 rows
594 }
595}
596
597struct VerdictRows<'a> {
601 occurrences: &'a [Occurrence],
602 options: Options,
603 planned: Option<&'a [FileChange]>,
604}
605
606impl<'a> VerdictRows<'a> {
607 fn new(
608 occurrences: &'a [Occurrence],
609 planned: Option<&'a [FileChange]>,
610 options: Options,
611 ) -> Self {
612 Self {
613 occurrences,
614 planned,
615 options,
616 }
617 }
618
619 fn rows(&self) -> Vec<Row> {
620 let width = self.occurrences.len().to_string().len();
621 let mut rows = Vec::new();
622 self.section(
623 &mut rows,
624 Confidence::Resolved,
625 !self.options.verbose,
626 width,
627 );
628 rows.push(Row::new(Line::new()));
629 self.section(&mut rows, Confidence::Unresolved, false, width);
630 rows.push(Row::new(Line::new()));
631 self.section(&mut rows, Confidence::Other, false, width);
632 rows
633 }
634
635 fn section(&self, lines: &mut Vec<Row>, confidence: Confidence, collapsed: bool, width: usize) {
636 let rows: Vec<(usize, &Occurrence)> = self
637 .occurrences
638 .iter()
639 .enumerate()
640 .filter(|(_, o)| o.confidence == confidence)
641 .collect();
642 let mut head = lines::Verdict::new(confidence)
643 .line()
644 .and(Role::Plain, " ")
645 .and(Role::Strong, rows.len().to_string());
646 if rows.is_empty() {
647 lines.push(Row::new(head));
648 return;
649 }
650 head = head.and(Role::Plain, " ").and(
651 Role::Dim,
652 Files::among(rows.iter().map(|(_, o)| o.m.path.as_path())).to_string(),
653 );
654 let reasons: BTreeSet<Reason> = rows.iter().map(|(_, o)| o.reason).collect();
655 let shared = (reasons.len() == 1 && confidence != Confidence::Resolved)
656 .then(|| *reasons.iter().next().expect("one"));
657 if let Some(reason) = shared {
658 head = head
659 .and(Role::Plain, " ")
660 .and_line(lines::Tag::new(reason).line());
661 }
662 if confidence == Confidence::Unresolved
663 && let Some(files) = self.planned
664 {
665 let planned = rows.iter().any(|(_, o)| {
666 files
667 .iter()
668 .any(|c| c.path == o.m.path && c.edits.iter().any(|e| e.span == o.m.span))
669 });
670 let word = if planned { "in the plan" } else { "left out" };
671 head = head.and(Role::Plain, " ").and(Role::Dim, word);
672 }
673 lines.push(Row::new(head));
674
675 if collapsed {
676 let mut per_file: BTreeMap<&Path, usize> = BTreeMap::new();
678 for (_, o) in &rows {
679 *per_file.entry(o.m.path.as_path()).or_default() += 1;
680 }
681 for (path, count) in per_file {
682 lines.push(Row::new(
683 Line::single(Role::Plain, " ")
684 .and(Role::Ordinal, format!("{count:>width$}"))
685 .and(Role::Plain, " ")
686 .and(Role::Path, path.display().to_string()),
687 ));
688 }
689 return;
690 }
691
692 let mut current: Option<&Path> = None;
695 let mut reason: Option<Reason> = None;
696 for (i, o) in &rows {
697 if shared.is_none() && reason != Some(o.reason) {
698 let run = rows.iter().filter(|(_, r)| r.reason == o.reason).count();
699 lines.push(Row::new(
700 lines::Tag::new(o.reason)
701 .line()
702 .and(Role::Plain, " ")
703 .and(Role::Dim, run.to_string()),
704 ));
705 reason = Some(o.reason);
706 current = None;
707 }
708 if current != Some(o.m.path.as_path()) {
709 lines.push(Row::new(Line::single(
710 Role::Path,
711 o.m.path.display().to_string(),
712 )));
713 current = Some(&o.m.path);
714 }
715 lines.push(Row::at(
716 lines::MatchRow::new(&o.m, i + 1, width).line(),
717 o.m.path.clone(),
718 o.m.start.line,
719 ));
720 }
721 }
722}