1use std::{
8 collections::{BTreeSet, HashMap, HashSet},
9 fmt::Write as _,
10};
11
12use super::{fence, graph, region};
13use crate::{
14 Body, Model, RepoPath, Segments,
15 compare::{Layout, Pair, Source},
16 markdown::{self, IncludeTarget, Link, sokf_label},
17 model::{KeyIndex, Query, keys},
18 source,
19};
20
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
23pub struct DefinitionEntry {
24 pub label: String,
26 pub path: RepoPath,
28 pub slug: Option<String>,
31}
32
33#[derive(Debug, Clone, Default)]
35pub struct Expected {
36 pub includes: HashMap<(RepoPath, usize), Option<String>>,
40 pub fences: HashMap<(RepoPath, usize), Fenced>,
44 pub bodies: HashMap<(RepoPath, usize), String>,
48 pub definitions: HashMap<RepoPath, Option<Vec<DefinitionEntry>>>,
52 pub cycles: Vec<Vec<RepoPath>>,
54 pub on_cycle: HashSet<RepoPath>,
56 pub layout: Layout,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Fenced {
65 pub path: RepoPath,
67 pub region: bool,
69 pub lines: Vec<u32>,
71 pub range: Option<std::ops::Range<u32>>,
73}
74
75impl Expected {
76 pub fn include(&self, path: &RepoPath, line: usize) -> Option<&str> {
79 self.includes
80 .get(&(path.clone(), line))
81 .and_then(|i| i.as_deref())
82 }
83
84 pub fn include_pair(&self, path: &RepoPath, line: usize, content: &str) -> Option<Pair> {
96 let expected = self.include(path, line)?;
97 if expected == content {
98 return None;
99 }
100 let key = (path.clone(), line);
101 let Some(fenced) = self.fences.get(&key) else {
102 return Some(Pair {
103 path: path.clone(),
104 name: self.bodies.get(&key)?.clone(),
105 fragment: false,
106 expected: expected.into(),
107 actual: content.into(),
108 source: None,
109 });
110 };
111 let (open, close) = fence_ends(expected)?;
112 let code = |text: &str| -> Option<String> {
113 let inner = text.strip_prefix(open)?.strip_suffix(close)?;
114 Some(inner.to_string())
115 };
116 Some(Pair {
117 path: path.clone(),
118 name: crate::compare::name_of(&fenced.path),
119 fragment: fenced.region,
120 expected: code(expected)?,
121 actual: code(content)?,
122 source: Some(Source {
123 path: fenced.path.clone(),
124 range: fenced.range.clone().filter(|_| fenced.region),
125 lines: fenced.lines.clone(),
126 }),
127 })
128 }
129
130 pub fn include_current(&self, path: &RepoPath, line: usize, content: &str) -> Option<bool> {
137 let expected = self.include(path, line)?;
138 Some(
139 expected == content
140 || self
141 .include_pair(path, line, content)
142 .is_some_and(|p| self.layout.same(&p)),
143 )
144 }
145
146 pub fn include_stale(
151 &self,
152 path: &RepoPath,
153 line: usize,
154 content: &str,
155 written: &str,
156 ) -> (Option<crate::Finding>, String) {
157 let Some(p) = self.include_pair(path, line, content) else {
158 return (None, crate::compare::stale_message(written, None, None));
159 };
160 (
161 self.layout.warning(&p),
162 crate::compare::stale_message(
163 written,
164 p.source.as_ref().map(|s| &s.path),
165 self.layout.line(&p),
166 ),
167 )
168 }
169}
170
171fn fence_ends(interior: &str) -> Option<(&str, &str)> {
175 let rest = interior.strip_prefix('\n')?;
176 let ticks = rest.len() - rest.trim_start_matches('`').len();
177 let open_len = 1 + rest.find('\n')? + 1;
178 let close_len = ticks + 2;
179 (ticks >= 3 && open_len + close_len <= interior.len()).then(|| {
180 (
181 &interior[..open_len],
182 &interior[interior.len() - close_len..],
183 )
184 })
185}
186
187fn interior(body: &str) -> String {
190 if body.is_empty() {
191 "\n".to_string()
192 } else {
193 format!("\n{body}\n\n")
194 }
195}
196
197pub fn render_definitions(entries: &[DefinitionEntry]) -> String {
203 if entries.is_empty() {
204 return String::new();
205 }
206 let mut out = String::from("<!-- sokf:links -->\n\n");
207 for e in entries {
208 let _ = write!(out, "[{}]: {}", e.label, e.path);
209 if let Some(slug) = &e.slug {
210 out.push('#');
211 out.push_str(slug);
212 }
213 out.push('\n');
214 }
215 out
216}
217
218pub fn expected(model: &Model, keys: &KeyIndex) -> Expected {
221 expected_for(model, keys, None)
222}
223
224pub fn expected_for(model: &Model, keys: &KeyIndex, only: Option<&BTreeSet<RepoPath>>) -> Expected {
233 let (g, needed) = graph::graph_for(model, only);
236 let o = graph::order(&g);
237 let mut expander = Expander {
238 model,
239 keys,
240 out: Expected {
241 cycles: o.cycles.clone(),
242 on_cycle: o.cycles.iter().flatten().cloned().collect(),
243 ..Expected::default()
244 },
245 expansions: HashMap::new(),
246 };
247 let cycle_nodes: Vec<usize> = (0..g.nodes.len())
248 .filter(|i| expander.out.on_cycle.contains(&g.nodes[*i]))
249 .collect();
250 for &node in o.sorted.iter().chain(cycle_nodes.iter()) {
251 if needed.as_ref().is_some_and(|n| !n.contains(&node)) {
252 continue;
253 }
254 expander.expand_file(&g.nodes[node]);
255 }
256 expander.add_definitions(only);
257 expander.out
258}
259
260struct Expander<'a> {
263 model: &'a Model,
265 keys: &'a KeyIndex,
267 out: Expected,
269 expansions: HashMap<RepoPath, Option<String>>,
272}
273
274impl Expander<'_> {
275 fn expand_file(&mut self, path: &RepoPath) {
279 let model = self.model;
280 model.watch(path);
281 let (knowledge, segments, body, body_text, body_line, is_document) =
282 match model.by_path(path) {
283 Some(crate::Located::Document(k, doc)) => parts_of(k, doc),
284 Some(crate::Located::Schema(k, schema)) => parts_of(k, &schema.doc),
285 Some(crate::Located::Additional(file)) => (
286 graph::knowledge_of_additional(model, file),
287 &file.segments,
288 &file.body,
289 file.source.text.as_str(),
290 1,
291 false,
292 ),
293 _ => {
294 model.unwatch();
295 return;
296 }
297 };
298 let mut all_computable = true;
299 for block in &segments.regions {
300 let expected = self.block_interior(knowledge, &block.target);
301 if expected.is_none() {
302 all_computable = false;
303 }
304 let key = (path.clone(), block.open_line);
305 let expected = expected.map(|(interior, kind)| {
306 match kind {
307 Kind::File(fenced) => self.out.fences.insert(key.clone(), fenced).map(drop),
308 Kind::Body(name) => self.out.bodies.insert(key.clone(), name).map(drop),
309 };
310 interior
311 });
312 self.out.includes.insert(key, expected);
313 }
314 if is_document {
315 let expansion = if all_computable && !self.out.on_cycle.contains(path) {
316 Some(expand(
317 body_text, body_line, segments, body, path, &self.out,
318 ))
319 } else {
320 None
321 };
322 self.expansions.insert(path.clone(), expansion);
323 }
324 model.unwatch();
325 }
326
327 fn block_interior(&self, knowledge: Option<usize>, target: &str) -> Option<(String, Kind)> {
333 let model = self.model;
334 match &IncludeTarget::parse(target) {
335 IncludeTarget::Document {
336 store,
337 id,
338 fragment,
339 } => {
340 let target = knowledge.and_then(|k| model.document_in(k, store.as_deref(), id));
341 match target {
342 None => None,
343 Some((target_k, target))
344 if graph::includes_body(model, &target.path, fragment.as_deref()) =>
345 {
346 let name = crate::compare::name_of(&target.path);
347 Some(target)
348 .filter(|t| !self.out.on_cycle.contains(&t.path))
349 .and_then(|t| {
350 model.note(Query::Body(t.path.clone()));
351 self.expansions.get(&t.path).cloned().flatten()
352 })
353 .map(|body| match knowledge {
354 Some(k) if k != target_k => {
355 requalify(model, self.keys, target_k, k, &body)
356 }
357 _ => body,
358 })
359 .map(|body| (interior(&body), Kind::Body(name)))
360 }
361 Some((_, target)) => model
369 .asset_of(&target.path)
370 .and_then(|(_, a)| asset_interior(model, &a.path, fragment.as_deref())),
371 }
372 }
373 IncludeTarget::File { path, region } => {
374 file_interior(model, knowledge, path, region.as_deref())
375 }
376 }
377 }
378
379 fn add_definitions(&mut self, only: Option<&BTreeSet<RepoPath>>) {
384 let model = self.model;
385 let documents = model
388 .documents_and_schemas()
389 .map(|(k, d)| (Some(k), &d.path, &d.body.links, &d.segments));
390 let additional = model.additional.iter().map(|f| {
391 (
392 graph::knowledge_of_additional(model, f),
393 &f.path,
394 &f.body.links,
395 &f.segments,
396 )
397 });
398 for (k, path, links, segments) in documents.chain(additional) {
399 let Some(k) = k else { continue };
400 if only.is_some_and(|o| !o.contains(path)) {
401 continue;
402 }
403 model.watch(path);
404 let entries = definition_entries(model, self.keys, k, path, links, segments, &self.out);
405 model.unwatch();
406 self.out.definitions.insert(path.clone(), entries);
407 }
408 }
409}
410
411type Parts<'a> = (Option<usize>, &'a Segments, &'a Body, &'a str, usize, bool);
415
416fn parts_of(k: usize, doc: &crate::Document) -> Parts<'_> {
418 (
419 Some(k),
420 &doc.segments,
421 &doc.body,
422 doc.body_text(),
423 doc.body_line,
424 true,
425 )
426}
427
428fn file_interior(
441 model: &Model,
442 knowledge: Option<usize>,
443 path: &str,
444 region: Option<&str>,
445) -> Option<(String, Kind)> {
446 let rp = RepoPath::parse(path)?;
447 if model.id_at(&rp).is_some() || model.is_materialized_in(knowledge, &rp) {
448 return None;
449 }
450 asset_interior(model, &rp, region)
451}
452
453fn asset_interior(model: &Model, path: &RepoPath, region: Option<&str>) -> Option<(String, Kind)> {
457 if !model.exists(path) {
458 return None;
459 }
460 model.note(Query::Body(path.clone()));
461 let text = source::load_text(&model.tree.root, path).ok()?;
462 let extraction = region::extract_lines(&text, region).ok()??;
463 let fenced = Fenced {
464 path: path.clone(),
465 region: region.is_some(),
466 range: extraction.range(),
467 lines: extraction.lines,
468 };
469 Some((
470 interior(&fence::fenced(&extraction.text, path)),
471 Kind::File(fenced),
472 ))
473}
474
475enum Kind {
478 File(Fenced),
479 Body(String),
480}
481
482fn expand(
489 body_text: &str,
490 body_line: usize,
491 segments: &Segments,
492 body: &Body,
493 path: &RepoPath,
494 out: &Expected,
495) -> String {
496 let mut lines: Vec<String> = Vec::new();
497 let mut skip_until: Option<usize> = None;
498 let mut after_anchors = false;
499 for (i, line) in body_text.lines().enumerate() {
500 let file_line = body_line + i;
501 if let Some(until) = skip_until {
502 if file_line <= until {
503 continue;
504 }
505 skip_until = None;
506 }
507 if body.anchors.iter().any(|a| a.line == file_line && a.alone) {
510 after_anchors = true;
511 continue;
512 }
513 if std::mem::take(&mut after_anchors) && line.trim().is_empty() {
514 continue;
515 }
516 let line = &*body.clean_line(file_line, line);
517 if segments
518 .definition
519 .as_ref()
520 .is_some_and(|d| file_line >= d.line)
521 {
522 break;
523 }
524 if let Some(block) = segments.regions.iter().find(|b| b.open_line == file_line) {
525 let content = out.include(path, block.open_line).unwrap_or(&block.content);
526 lines.extend(content.lines().map(str::to_string));
527 skip_until = Some(block.close_line);
528 continue;
529 }
530 lines.push(line.to_string());
531 }
532 let start = lines
533 .iter()
534 .position(|l| !l.trim().is_empty())
535 .unwrap_or(lines.len());
536 let end = lines
537 .iter()
538 .rposition(|l| !l.trim().is_empty())
539 .map_or(0, |i| i + 1);
540 if start >= end {
541 return String::new();
542 }
543 lines[start..end].join("\n")
544}
545
546fn definition_entries(
558 model: &Model,
559 keys: &KeyIndex,
560 knowledge: usize,
561 path: &RepoPath,
562 links: &[Link],
563 segments: &Segments,
564 out: &Expected,
565) -> Option<Vec<DefinitionEntry>> {
566 let mut labels: Vec<String> = Vec::new();
567 for link in links {
568 if let Some(label) = sokf_label(link) {
569 labels.push(label);
570 } else if let Some((label, true)) = path_link_label(model, keys, knowledge, path, link) {
571 labels.push(label);
572 }
573 }
574 for block in &segments.regions {
575 let content = out.include(path, block.open_line).unwrap_or(&block.content);
576 let inner_segments = Segments::default();
577 let body = markdown::parse(content, 1, &inner_segments);
578 labels.extend(body.links.iter().filter_map(sokf_label));
579 }
580 labels.sort();
581 labels.dedup();
582 let mut entries = Vec::new();
583 for label in labels {
584 let parts = markdown::label_parts(&label)?;
585 let (resolved, slug) = keys::resolve_slugged(model, keys, knowledge, parts);
586 let resolved = resolved.ok()?;
587 let parts = parts.with_fragment(slug.as_deref().or(parts.fragment));
588 let label = model
589 .canonical_label(knowledge, resolved.knowledge, parts.id, parts.fragment)
590 .unwrap_or_else(|| label.clone());
591 let path = if parts.fragment.is_none() {
595 model.content_path(&resolved.path)
596 } else {
597 resolved.path
598 };
599 entries.push(DefinitionEntry {
600 label,
601 path,
602 slug: resolved.slug,
603 });
604 }
605 entries.sort();
606 entries.dedup();
607 Some(entries)
608}
609
610pub fn path_link_label(
619 model: &Model,
620 keys: &KeyIndex,
621 knowledge: usize,
622 path: &RepoPath,
623 link: &Link,
624) -> Option<(String, bool)> {
625 let (target, fragment) = match &link.target {
626 markdown::LinkTarget::Repo {
627 path,
628 fragment,
629 dir: false,
630 } => (path.clone(), fragment.as_deref()),
631 markdown::LinkTarget::Relative { target, fragment } => {
632 (path.resolve_relative(target)?, fragment.as_deref())
633 }
634 _ => return None,
635 };
636 if link.is_image && model.asset_at(&target).is_none() {
639 return None;
640 }
641 let label = model.path_label(knowledge, &target, fragment)?;
642 let parts = markdown::label_parts(&label)?;
643 let (label, resolves) = match keys::resolve_slugged(model, keys, knowledge, parts) {
644 (Ok(_), None) => (label, true),
645 (Ok(r), Some(slug)) => {
646 match model.canonical_label(knowledge, r.knowledge, parts.id, Some(&slug)) {
647 Some(slugged) => (slugged, true),
648 None => (label, false),
649 }
650 }
651 (Err(_), _) => (label, false),
652 };
653 Some((label, resolves && link.inline.is_some()))
654}
655
656fn requalify(model: &Model, keys: &KeyIndex, from: usize, to: usize, body: &str) -> String {
661 let parsed = markdown::parse(body, 1, &Segments::default());
662 let mut renames: Vec<((usize, usize), String, String)> = Vec::new();
666 for link in &parsed.links {
667 let (Some(label), Some(parts)) = (sokf_label(link), keys::Label::of(&link.target)) else {
668 continue;
669 };
670 let Ok(resolved) = keys::resolve(model, keys, from, parts) else {
671 continue;
672 };
673 if let Some(new) = model.canonical_label(to, resolved.knowledge, parts.id, parts.fragment)
674 && new != label
675 {
676 renames.push((link.lines(), format!("[{label}]"), format!("[{new}]")));
677 }
678 }
679 renames.sort();
680 renames.dedup();
681 let mut lines: Vec<String> = body.lines().map(str::to_string).collect();
682 for ((first, last), old, new) in renames {
683 for line in first..=last {
684 let Some(text) = lines.get_mut(line - 1) else {
685 continue;
686 };
687 let at: Vec<usize> = text
688 .match_indices(old.as_str())
689 .map(|(pos, _)| pos)
690 .filter(|&pos| !parsed.in_code_span(line, pos))
691 .collect();
692 for pos in at.into_iter().rev() {
693 text.replace_range(pos..pos + old.len(), &new);
694 }
695 }
696 }
697 lines.join("\n")
698}
699
700#[cfg(test)]
701mod tests;