1use super::{Node, SyntaxKind as K, SyntaxTree};
35
36#[non_exhaustive]
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
42pub enum AttachRule {
43 HeaderBeforeStart,
46 HeaderBlankLine,
50 FirstNodeLeading,
53 Leading,
57 Trailing,
61 CollectionFooter,
64 DocumentFooter,
67 Flow,
70 ShallowLeading,
73 ExplicitValue,
76 Inside,
80 RunOrder,
84}
85
86impl AttachRule {
87 #[must_use]
89 pub const fn number(self) -> u8 {
90 match self {
91 Self::HeaderBeforeStart => 1,
92 Self::HeaderBlankLine => 2,
93 Self::FirstNodeLeading => 3,
94 Self::Leading => 4,
95 Self::Trailing => 5,
96 Self::CollectionFooter => 6,
97 Self::DocumentFooter => 7,
98 Self::Flow => 9,
99 Self::ShallowLeading => 10,
100 Self::ExplicitValue => 11,
101 Self::Inside => 12,
102 Self::RunOrder => 13,
103 }
104 }
105}
106
107#[non_exhaustive]
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
113pub enum CommentOwner<'t> {
114 DocumentHeader(Node<'t>),
117 DocumentFooter(Node<'t>),
119 Leading(Node<'t>),
121 Trailing(Node<'t>),
124 Footer(Node<'t>),
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
131pub struct Attachment<'t> {
132 owner: CommentOwner<'t>,
133 rule: AttachRule,
134 blank_lines_before: usize,
135 document: Option<Node<'t>>,
136}
137
138impl<'t> Attachment<'t> {
139 #[must_use]
141 pub const fn owner(&self) -> CommentOwner<'t> {
142 self.owner
143 }
144
145 #[must_use]
147 pub const fn rule(&self) -> AttachRule {
148 self.rule
149 }
150
151 #[must_use]
155 pub const fn blank_lines_before(&self) -> usize {
156 self.blank_lines_before
157 }
158
159 #[must_use]
162 pub const fn document(&self) -> Option<Node<'t>> {
163 self.document
164 }
165}
166
167impl SyntaxTree {
168 #[must_use]
177 pub fn comment_attachment<'t>(&'t self, comment: Node<'t>) -> Option<Attachment<'t>> {
178 if comment.kind() != K::Comment || !core::ptr::eq(comment.tree(), self) {
179 return None;
180 }
181 let around = Around::Scan;
182 let a = match line_of(comment) {
183 Line::Same(p) => same_line(locate(p), &around),
184 Line::Own(end) => match self.decide_indexed(comment, end, Want::Attachment) {
185 Some(Decided::Attachment(a)) => a,
186 _ => self.replay(comment)?,
187 },
188 };
189 Some(a)
190 }
191
192 #[must_use]
200 pub fn comment_document<'t>(&'t self, comment: Node<'t>) -> Option<Option<Node<'t>>> {
201 if comment.kind() != K::Comment || !core::ptr::eq(comment.tree(), self) {
202 return None;
203 }
204 match line_of(comment) {
205 Line::Same(p) => Some(same_line(locate(p), &Around::Scan).document),
206 Line::Own(end) => match self.decide_indexed(comment, end, Want::Document) {
207 Some(Decided::Document(d)) => Some(d),
208 Some(Decided::Attachment(a)) => Some(a.document),
209 None => self.replay(comment).map(|a| a.document),
210 },
211 }
212 }
213
214 #[must_use]
221 pub fn prev_content_token<'t>(&'t self, n: Node<'t>) -> Option<Node<'t>> {
222 core::ptr::eq(n.tree(), self)
223 .then(|| prev_visible(n))
224 .flatten()
225 }
226
227 #[must_use]
230 pub fn next_content_token<'t>(&'t self, n: Node<'t>) -> Option<Node<'t>> {
231 core::ptr::eq(n.tree(), self)
232 .then(|| next_visible(n))
233 .flatten()
234 }
235
236 #[must_use]
247 pub fn last_footer_comment<'t>(&'t self, collection: Node<'t>) -> Option<Node<'t>> {
248 if !is_block(collection.kind()) || !core::ptr::eq(collection.tree(), self) {
249 return None;
250 }
251 let p = last_visible_in(collection)?;
252 let n = next_visible(p);
253 let around = Around::Scan;
254 let ahead = Ahead {
255 next: n,
256 last_blank: None,
257 };
258 let plan = make_plan(self, Some(locate(p)), &ahead, &around);
259 if !cols_fit(&plan) {
260 return self.last_footer_comment_walk(collection, p, &plan);
261 }
262 let i = plan.footer.iter().position(|(k, _)| *k == collection)?;
263 let span = collection.span();
264 let within = |y: Node<'_>| {
265 let s = y.span();
266 span.start <= s.start && s.end <= span.end
267 };
268 let mut j = i;
271 while plan
272 .footer
273 .get(j.saturating_add(1))
274 .is_some_and(|(k, _)| within(*k))
275 {
276 j = j.saturating_add(1);
277 }
278 let cut = cut_below(&plan, j.saturating_add(1))?;
280 let stop = self.run_hit(p.slot(), cut);
281 let stop = stop.and_then(|s| self.node_at_slot(s));
282 let mut at = match stop {
284 Some(s) => prev_token(s),
285 None => last_token(self),
286 };
287 while let Some(t) = at {
288 if t == p || visible(t) {
289 return None;
290 }
291 if t.kind() == K::Comment {
292 return matches!(line_of(t), Line::Own(_)).then_some(t);
293 }
294 at = prev_token(t);
295 }
296 None
297 }
298
299 fn last_footer_comment_walk<'t>(
302 &'t self,
303 collection: Node<'t>,
304 p: Node<'t>,
305 plan: &Plan<'t>,
306 ) -> Option<Node<'t>> {
307 let span = collection.span();
308 let within = |y: Node<'_>| {
309 let s = y.span();
310 span.start <= s.start && s.end <= span.end
311 };
312 let mut floor = None;
313 let mut last = None;
314 let mut at = next_token(p);
315 while let Some(t) = at {
316 if visible(t) {
317 break;
318 }
319 if t.kind() == K::Comment {
320 if let Line::Own(end) = line_of(t) {
321 let a = decide(plan, t, col_of(t), blank_before(end), &mut floor);
322 match a.owner {
323 CommentOwner::Footer(y) if within(y) => last = Some(t),
324 _ => break,
325 }
326 }
327 }
328 at = next_token(t);
329 }
330 last
331 }
332
333 fn decide_indexed<'t>(
343 &'t self,
344 c: Node<'t>,
345 end: Option<Node<'t>>,
346 want: Want,
347 ) -> Option<Decided<'t>> {
348 let p = prev_visible(c);
349 let n = next_visible(c);
350 let around = Around::Scan;
351 let ahead = Ahead {
352 next: n,
353 last_blank: None,
354 };
355 let mut plan = make_plan(self, p.map(locate), &ahead, &around);
356 if !cols_fit(&plan) {
357 return None;
358 }
359 let outer = plan.footer.len();
360 let header = matches!(plan.otherwise, Otherwise::Header { .. });
361 let col = col_of(c);
362 let floor = self.floor_rank(&plan, p, c)?;
363 if let Want::Document = want {
364 let rank = floor.max(own_rank(&plan, col));
365 let doc = if rank < outer {
366 plan.footer_document
367 } else {
368 plan.document
369 };
370 return Some(Decided::Document(doc));
371 }
372 if header && outer > 0 {
373 return None;
374 }
375 if let Otherwise::Header { last_blank, .. } = &mut plan.otherwise {
376 *last_blank = scan_ahead(c).last_blank;
380 }
381 let blank = blank_before(end);
382 let (a, rank) = decide_one(&plan, c, col, blank);
383 if floor <= rank {
384 return Some(Decided::Attachment(a));
385 }
386 let (owner, document) = match plan.footer.get(floor) {
388 Some((k, _)) => (CommentOwner::Footer(*k), plan.footer_document),
389 None => match plan.otherwise {
390 Otherwise::Fixed(o, _) => (o, plan.document),
391 Otherwise::Leading { target, .. } => (CommentOwner::Leading(target), plan.document),
392 Otherwise::Header { .. } => {
393 debug_assert!(false, "rule 13 above a header owner");
400 return None;
401 }
402 },
403 };
404 Some(Decided::Attachment(Attachment {
405 owner,
406 rule: AttachRule::RunOrder,
407 blank_lines_before: blank,
408 document,
409 }))
410 }
411
412 fn floor_rank(&self, plan: &Plan<'_>, p: Option<Node<'_>>, c: Node<'_>) -> Option<usize> {
419 let outer = plan.footer.len();
420 if outer == 0 {
421 return Some(0);
422 }
423 let from = p.map_or(0, Node::slot);
424 let at = c.preorder_index();
425 let exists = |k: usize| -> Option<bool> {
426 let cut = cut_below(plan, k)?;
427 Some(
428 self.run_hit(from, cut)
429 .and_then(|s| self.node_at_slot(s))
430 .is_some_and(|h| h.preorder_index() < at),
431 )
432 };
433 let (mut lo, mut hi) = (0usize, outer);
435 while lo < hi {
436 let mid = lo.saturating_add(hi.saturating_sub(lo).saturating_add(1) / 2);
437 if exists(mid)? {
438 lo = mid;
439 } else {
440 hi = mid.saturating_sub(1);
441 }
442 }
443 Some(lo)
444 }
445
446 fn replay<'t>(&'t self, comment: Node<'t>) -> Option<Attachment<'t>> {
449 let around = Around::Scan;
450 let mut run = Vec::new();
453 let mut p = None;
454 let mut at = prev_token(comment);
455 while let Some(t) = at {
456 if visible(t) {
457 p = Some(t);
458 break;
459 }
460 if t.kind() == K::Comment {
461 run.push(t);
462 }
463 at = prev_token(t);
464 }
465 run.reverse();
466 run.push(comment);
467 let own: Vec<(Node<'t>, Option<Node<'t>>)> = run
468 .into_iter()
469 .filter_map(|r| match line_of(r) {
470 Line::Own(end) => Some((r, end)),
471 Line::Same(_) => None,
472 })
473 .collect();
474 let first = own.first().map_or(comment, |(r, _)| *r);
475 let plan = make_plan(self, p.map(locate), &scan_ahead(first), &around);
476 let mut floor = None;
477 let mut last = None;
478 for (r, end) in own {
479 last = Some(decide(&plan, r, col_of(r), blank_before(end), &mut floor));
480 }
481 last
482 }
483
484 #[must_use]
498 pub fn comment_run_attachments<'t>(
499 &'t self,
500 comment: Node<'t>,
501 ) -> Vec<(Node<'t>, Attachment<'t>)> {
502 if comment.kind() != K::Comment || !core::ptr::eq(comment.tree(), self) {
503 return Vec::new();
504 }
505 let mut run = Vec::new();
507 let mut p = None;
508 let mut at = prev_token(comment);
509 while let Some(t) = at {
510 if visible(t) {
511 p = Some(t);
512 break;
513 }
514 if t.kind() == K::Comment {
515 run.push(t);
516 }
517 at = prev_token(t);
518 }
519 run.reverse();
520 run.push(comment);
521 let mut at = next_token(comment);
522 while let Some(t) = at {
523 if visible(t) {
524 break;
525 }
526 if t.kind() == K::Comment {
527 run.push(t);
528 }
529 at = next_token(t);
530 }
531 let around = Around::Scan;
532 let from = p.map(locate);
533 let mut plan: Option<Plan<'t>> = None;
534 let mut floor = None;
535 let mut out = Vec::with_capacity(run.len());
536 for r in run {
537 let a = match line_of(r) {
538 Line::Same(q) => same_line(locate(q), &around),
539 Line::Own(end) => {
540 let plan =
543 plan.get_or_insert_with(|| make_plan(self, from, &scan_ahead(r), &around));
544 decide(plan, r, col_of(r), blank_before(end), &mut floor)
545 }
546 };
547 out.push((r, a));
548 }
549 out
550 }
551
552 #[must_use]
565 pub fn comment_attachments_between<'t>(
566 &'t self,
567 before: Option<Node<'t>>,
568 after: Option<Node<'t>>,
569 ) -> Vec<(Node<'t>, Attachment<'t>)> {
570 let is_doc = |d: Option<Node<'t>>| {
571 d.is_none_or(|d| {
572 d.kind() == K::Document
573 && core::ptr::eq(d.tree(), self)
574 && d.parent().is_some_and(|p| p.kind() == K::Stream)
575 })
576 };
577 if !is_doc(before) || !is_doc(after) {
578 return Vec::new();
579 }
580 let mut tops = Vec::new();
581 let mut at = match before {
582 Some(b) => b.next_sibling(),
583 None => self.root().first_child(),
584 };
585 while let Some(n) = at {
587 if Some(n) == after {
588 break;
589 }
590 tops.push(n);
591 at = n.next_sibling();
592 }
593 if at != after {
594 return Vec::new();
595 }
596 let start = tops.first().and_then(|f| prev_visible(*f)).map(locate);
597 pass(self, &tops, start, before, after, None)
598 }
599
600 #[must_use]
603 pub fn comment_attachments(&self) -> Vec<(Node<'_>, Attachment<'_>)> {
604 let tops: Vec<Node<'_>> = self.root().children().collect();
605 pass(self, &tops, None, None, None, None)
606 }
607
608 #[must_use]
615 pub fn document_comment_attachments<'t>(
616 &'t self,
617 document: Node<'t>,
618 ) -> Vec<(Node<'t>, Attachment<'t>)> {
619 if document.kind() != K::Document || !core::ptr::eq(document.tree(), self) {
620 return Vec::new();
621 }
622 let mut first = document;
626 let mut before = None;
627 while let Some(p) = first.prev_sibling() {
628 if p.kind() == K::Document {
629 before = Some(p);
630 break;
631 }
632 first = p;
633 }
634 let start = prev_visible(first).map(locate);
635 let mut tops = Vec::new();
636 let mut at = Some(first);
637 let mut after = None;
638 while let Some(n) = at {
639 if n.kind() == K::Document && n != document {
640 after = Some(n);
641 break;
642 }
643 tops.push(n);
644 at = n.next_sibling();
645 }
646 pass(self, &tops, start, before, after, Some(document))
647 }
648}
649
650fn edge_tokens<'t>(doc: Node<'t>, p: Option<Node<'t>>) -> Vec<Node<'t>> {
656 let mut out = Vec::new();
657 let mut at = match p {
658 Some(p) => next_token(p),
659 None => Some(first_token(doc)).filter(|t| t.is_token()),
660 };
661 while let Some(t) = at {
662 if visible(t) || !contains(doc, t) {
663 break;
664 }
665 out.push(t);
666 at = next_token(t);
667 }
668 out
669}
670
671#[derive(Clone, Copy)]
674struct At<'t> {
675 tok: Node<'t>,
676 doc: Option<Node<'t>>,
677 child: Option<Node<'t>>,
678}
679
680fn locate(tok: Node<'_>) -> At<'_> {
682 let mut below = tok;
683 for a in tok.ancestors() {
684 if a.kind() == K::Document {
685 return At {
686 tok,
687 doc: Some(a),
688 child: Some(below),
689 };
690 }
691 below = a;
692 }
693 At {
694 tok,
695 doc: None,
696 child: None,
697 }
698}
699
700enum Around<'t> {
703 Scan,
706 Known {
709 prev: Option<Node<'t>>,
710 next: Option<Node<'t>>,
711 },
712}
713
714impl<'t> Around<'t> {
715 fn prev_doc(&self, x: Node<'t>) -> Option<Node<'t>> {
719 match self {
720 Self::Known { prev, .. } => *prev,
721 Self::Scan => x.tree().document_before(x.slot()),
725 }
726 }
727
728 fn next_doc(&self, x: Node<'t>) -> Option<Node<'t>> {
730 match self {
731 Self::Known { next, .. } => *next,
732 Self::Scan => x.tree().document_after(x.slot()),
733 }
734 }
735}
736
737fn pass<'t>(
745 tree: &'t SyntaxTree,
746 tops: &[Node<'t>],
747 start: Option<At<'t>>,
748 before: Option<Node<'t>>,
749 after: Option<Node<'t>>,
750 want: Option<Node<'t>>,
751) -> Vec<(Node<'t>, Attachment<'t>)> {
752 let is_doc = |n: &Node<'t>| n.kind() == K::Document;
753 let mut prevs = Vec::with_capacity(tops.len());
755 let mut last = before;
756 for t in tops {
757 prevs.push(last);
758 if is_doc(t) {
759 last = Some(*t);
760 }
761 }
762 let mut nexts = vec![None; tops.len()];
763 let mut next = after;
764 for (t, slot) in tops.iter().zip(nexts.iter_mut()).rev() {
765 *slot = next;
766 if is_doc(t) {
767 next = Some(*t);
768 }
769 }
770 let tail = match (want, before, start) {
773 (Some(_), Some(b), Some(p)) if p.doc == Some(b) => edge_tokens(b, Some(p.tok)),
774 _ => Vec::new(),
775 };
776 let head = match (want, after) {
777 (Some(_), Some(a)) => edge_tokens(a, None),
778 _ => Vec::new(),
779 };
780 let mut out = Vec::new();
781 let mut p = start;
782 let mut plan: Option<Plan<'t>> = None;
783 let mut floor: Option<Floor<'t>> = None;
784 let mut step =
785 |t: Node<'t>, doc: Option<Node<'t>>, child: Option<Node<'t>>, around: &Around<'t>| {
786 if t.kind() == K::Comment {
787 let a = match line_of(t) {
788 Line::Same(q) => {
789 let at = match p {
790 Some(x) if x.tok == q => x,
791 _ => locate(q),
792 };
793 same_line(at, around)
794 }
795 Line::Own(end) => {
796 let plan =
797 plan.get_or_insert_with(|| make_plan(tree, p, &scan_ahead(t), around));
798 decide(plan, t, col_of(t), blank_before(end), &mut floor)
799 }
800 };
801 if want.is_none_or(|w| a.document == Some(w)) {
802 out.push((t, a));
803 }
804 } else if visible(t) {
805 p = Some(At { tok: t, doc, child });
806 plan = None;
807 floor = None;
808 }
809 };
810 let first_next = tops.iter().copied().find(is_doc).or(after);
813 let tail_around = Around::Known {
814 prev: None,
815 next: first_next,
816 };
817 for t in tail {
818 step(t, before, None, &tail_around);
819 }
820 for ((top, prev), next) in tops.iter().zip(prevs).zip(nexts) {
821 let around = Around::Known { prev, next };
822 if is_doc(top) {
823 for ch in top.children() {
825 for t in ch.descendants() {
826 step(t, Some(*top), Some(ch), &around);
827 }
828 }
829 } else {
830 for t in top.descendants() {
831 step(t, None, None, &around);
832 }
833 }
834 }
835 let last_doc = tops.iter().copied().rev().find(is_doc).or(before);
836 let head_around = Around::Known {
837 prev: last_doc,
838 next: after,
839 };
840 for t in head {
841 step(t, after, None, &head_around);
842 }
843 out
844}
845
846fn is_item(k: K) -> bool {
849 k.is_yaml_node() || k == K::Error
850}
851
852fn is_block(k: K) -> bool {
853 matches!(k, K::BlockMapping | K::BlockSequence)
854}
855
856fn is_map(k: K) -> bool {
857 matches!(k, K::BlockMapping | K::FlowMapping | K::FlowPair)
858}
859
860fn is_seq(k: K) -> bool {
861 matches!(k, K::BlockSequence | K::FlowSequence)
862}
863
864fn is_flow(k: K) -> bool {
865 matches!(k, K::FlowMapping | K::FlowSequence | K::FlowPair)
866}
867
868fn empty(n: Node<'_>) -> bool {
869 n.span().is_empty()
870}
871
872fn visible(t: Node<'_>) -> bool {
875 t.is_token() && !t.kind().is_trivia() && !empty(t)
876}
877
878fn blankish(t: Node<'_>) -> bool {
881 matches!(t.kind(), K::Whitespace | K::ByteOrderMark) || (t.kind() != K::LineBreak && empty(t))
882}
883
884fn ends_line(t: Node<'_>) -> bool {
886 t.kind() == K::LineBreak || (!empty(t) && t.text().ends_with(['\n', '\r']))
887}
888
889fn prev_token(n: Node<'_>) -> Option<Node<'_>> {
892 let mut at = n.pred();
893 while let Some(x) = at {
894 if x.is_token() {
895 return Some(x);
896 }
897 at = x.pred();
898 }
899 None
900}
901
902fn next_token(n: Node<'_>) -> Option<Node<'_>> {
903 let mut at = n.succ();
904 while let Some(x) = at {
905 if x.is_token() {
906 return Some(x);
907 }
908 at = x.succ();
909 }
910 None
911}
912
913fn prev_visible(n: Node<'_>) -> Option<Node<'_>> {
917 let t = n.tree();
918 t.visible_before(n.slot()).and_then(|s| t.node_at_slot(s))
919}
920
921fn next_visible(n: Node<'_>) -> Option<Node<'_>> {
924 let t = n.tree();
925 t.run_hit(n.slot(), 0).and_then(|s| t.node_at_slot(s))
926}
927
928fn last_visible_in(n: Node<'_>) -> Option<Node<'_>> {
930 let t = n.tree();
931 let leaf = t.node_at_slot(t.nav_last_leaf(n.slot())?)?;
932 let last = if visible(leaf) {
933 leaf
934 } else {
935 prev_visible(leaf)?
936 };
937 contains(n, last).then_some(last)
938}
939
940fn last_token(tree: &SyntaxTree) -> Option<Node<'_>> {
942 let root = tree.root();
943 let leaf = tree.node_at_slot(tree.nav_last_leaf(root.slot())?)?;
944 if leaf.is_token() {
945 Some(leaf)
946 } else {
947 prev_token(leaf)
948 }
949}
950
951pub(super) fn own_col(c: Node<'_>) -> Option<usize> {
954 match line_of(c) {
955 Line::Own(_) => Some(col_of(c)),
956 Line::Same(_) => None,
957 }
958}
959
960fn contains(a: Node<'_>, n: Node<'_>) -> bool {
962 let ai = a.preorder_index();
963 let ni = n.preorder_index();
964 ai <= ni && ni < ai.saturating_add(a.descendants().len())
965}
966
967fn col_of(t: Node<'_>) -> usize {
974 let mut col = 0usize;
975 let mut at = prev_token(t);
976 while let Some(x) = at {
977 if x.kind() == K::ByteOrderMark {
978 at = prev_token(x);
979 continue;
980 }
981 let text = x.text();
982 if let Some(i) = text.rfind(['\n', '\r']) {
983 let tail = text.get(i.saturating_add(1)..).unwrap_or("");
984 return col.saturating_add(tail.chars().count());
985 }
986 col = col.saturating_add(text.chars().count());
987 at = prev_token(x);
988 }
989 col
990}
991
992fn first_token(n: Node<'_>) -> Node<'_> {
994 let mut at = n;
995 while let Some(c) = at.first_child() {
996 at = c;
997 }
998 at
999}
1000
1001fn coll_start(c: Node<'_>) -> Node<'_> {
1004 let first = c
1005 .children()
1006 .find(|x| !x.kind().is_trivia() && !matches!(x.kind(), K::Anchor | K::Tag))
1007 .unwrap_or(c);
1008 first_token(first)
1009}
1010
1011fn cols_of(tokens: &[Node<'_>]) -> Vec<usize> {
1016 let mut out = vec![0usize; tokens.len()];
1017 let mut i = 0usize;
1018 while let Some(&t) = tokens.get(i) {
1019 let mut acc = 0usize;
1022 let mut met = vec![(i, 0usize)];
1023 let mut j = i.saturating_add(1);
1024 let mut at = prev_token(t);
1025 while let Some(x) = at {
1026 let text = x.text();
1027 let chars = if x.kind() == K::ByteOrderMark {
1029 0
1030 } else {
1031 text.chars().count()
1032 };
1033 let breaks = text.contains(['\n', '\r']);
1034 while tokens.get(j) == Some(&x) {
1035 if !breaks {
1036 met.push((j, acc.saturating_add(chars)));
1037 j = j.saturating_add(1);
1038 } else {
1039 break;
1040 }
1041 }
1042 if let Some(k) = text.rfind(['\n', '\r']) {
1043 let tail = text.get(k.saturating_add(1)..).unwrap_or("");
1044 acc = acc.saturating_add(tail.chars().count());
1045 break;
1046 }
1047 acc = acc.saturating_add(chars);
1048 at = prev_token(x);
1049 }
1050 for (k, before) in met {
1051 if let Some(o) = out.get_mut(k) {
1052 *o = acc.saturating_sub(before);
1053 }
1054 }
1055 i = j.max(i.saturating_add(1));
1056 }
1057 out
1058}
1059
1060fn next_sig(x: Node<'_>) -> Option<Node<'_>> {
1065 let parent = x.parent()?;
1066 let t = x.tree();
1067 let last = t.nav_last_leaf(x.slot())?;
1068 let s = t.node_at_slot(t.solid_after(last)?)?;
1069 (s.parent() == Some(parent)).then_some(s)
1070}
1071
1072fn prev_sig(x: Node<'_>) -> Option<Node<'_>> {
1076 let parent = x.parent()?;
1077 let t = x.tree();
1078 let mut s = t.node_at_slot(t.solid_before(x.slot())?)?;
1079 loop {
1081 if s == parent {
1082 return None;
1083 }
1084 match s.parent() {
1085 Some(p) if p == parent => return Some(s),
1086 Some(p) => s = p,
1087 None => return None,
1088 }
1089 }
1090}
1091
1092fn next_item(x: Node<'_>) -> Option<Node<'_>> {
1095 let mut at = next_sig(x);
1096 while let Some(s) = at {
1097 if is_item(s.kind()) {
1098 return Some(s);
1099 }
1100 at = next_sig(s);
1101 }
1102 None
1103}
1104
1105fn prev_item(x: Node<'_>) -> Option<Node<'_>> {
1108 let mut at = prev_sig(x);
1109 while let Some(s) = at {
1110 if is_item(s.kind()) {
1111 return Some(s);
1112 }
1113 at = prev_sig(s);
1114 }
1115 None
1116}
1117
1118fn local_key(x: Node<'_>) -> Option<bool> {
1123 match prev_sig(x).map(Node::kind) {
1124 None | Some(K::MappingKey | K::FlowMappingOpen | K::FlowSequenceOpen | K::FlowEntry) => {
1125 return Some(true);
1126 }
1127 Some(K::MappingValue) => return Some(false),
1128 _ => {}
1129 }
1130 if next_sig(x).is_some_and(|s| s.kind() == K::MappingValue) {
1131 return Some(true);
1132 }
1133 match prev_sig(x) {
1134 Some(p) if is_item(p.kind()) => None,
1135 _ => Some(true),
1137 }
1138}
1139
1140fn is_key(x: Node<'_>) -> bool {
1146 if let Some(k) = local_key(x) {
1147 return k;
1148 }
1149 prev_item(x).and_then(local_key).is_none_or(|k| !k)
1150}
1151
1152fn key_of(x: Node<'_>) -> Node<'_> {
1154 if is_key(x) {
1155 x
1156 } else {
1157 prev_item(x).unwrap_or(x)
1158 }
1159}
1160
1161fn entry_owner<'t>(c: Node<'t>, x: Node<'t>) -> Option<Node<'t>> {
1165 let k = x.kind();
1166 if matches!(
1167 k,
1168 K::FlowSequenceOpen
1169 | K::FlowSequenceClose
1170 | K::FlowMappingOpen
1171 | K::FlowMappingClose
1172 | K::Anchor
1173 | K::Tag
1174 ) {
1175 return None;
1176 }
1177 if is_seq(c.kind()) {
1178 return match k {
1179 _ if is_item(k) => Some(x),
1180 K::SequenceEntry => next_item(x),
1181 _ => prev_item(x),
1182 };
1183 }
1184 match k {
1185 _ if is_item(k) => Some(key_of(x)),
1186 K::MappingKey => next_item(x),
1187 K::MappingValue => prev_item(x),
1188 _ => prev_item(x).map(key_of),
1189 }
1190}
1191
1192fn entry_opened<'t>(c: Node<'t>, x: Node<'t>) -> Option<Node<'t>> {
1196 let k = x.kind();
1197 match c.kind() {
1198 K::BlockSequence => (k == K::SequenceEntry).then(|| next_item(x)).flatten(),
1199 K::FlowSequence => is_item(k).then_some(x),
1200 _ if is_map(c.kind()) => {
1201 if k == K::MappingKey {
1202 return next_item(x);
1203 }
1204 let after_q = prev_sig(x).is_some_and(|p| p.kind() == K::MappingKey);
1205 (is_item(k) && !after_q && is_key(x)).then_some(x)
1206 }
1207 _ => None,
1208 }
1209}
1210
1211#[derive(Clone, Copy, Debug)]
1213enum Opens {
1214 Entry,
1216 Node,
1218 ExplicitValue,
1220 Inside,
1223}
1224
1225fn target_of<'t>(n: Node<'t>, fallback: Node<'t>) -> (Node<'t>, Opens) {
1231 let s = n.span().start;
1232 let mut x = n;
1233 while let Some(a) = x.parent() {
1235 if is_map(a.kind()) || is_seq(a.kind()) {
1236 if let Some(e) = entry_opened(a, x) {
1237 return (e, Opens::Entry);
1238 }
1239 }
1240 if !is_item(a.kind()) || a.span().start != s {
1241 break;
1242 }
1243 x = a;
1244 }
1245 if is_item(x.kind()) {
1246 return (x, Opens::Node);
1247 }
1248 if x.kind() == K::MappingValue {
1249 if let Some(v) = next_item(x) {
1250 return (v, Opens::ExplicitValue);
1251 }
1252 }
1253 let holder = x
1254 .ancestors()
1255 .find(|a| is_item(a.kind()))
1256 .unwrap_or(fallback);
1257 (holder, Opens::Inside)
1258}
1259
1260enum Line<'t> {
1264 Own(Option<Node<'t>>),
1267 Same(Node<'t>),
1269}
1270
1271fn line_of(c: Node<'_>) -> Line<'_> {
1272 let mut at = prev_token(c);
1273 while let Some(t) = at {
1274 if ends_line(t) {
1275 return Line::Own(Some(t));
1276 }
1277 if blankish(t) || t.kind() == K::Comment {
1278 at = prev_token(t);
1279 continue;
1280 }
1281 return Line::Same(t);
1282 }
1283 Line::Own(None)
1284}
1285
1286fn blank_before(end: Option<Node<'_>>) -> usize {
1288 let Some(mut at) = end else { return 0 };
1289 let mut count = 0usize;
1290 loop {
1291 if at.kind() != K::LineBreak {
1292 return count;
1294 }
1295 let mut u = prev_token(at);
1296 while let Some(t) = u.filter(|t| blankish(*t)) {
1297 u = prev_token(t);
1298 }
1299 match u {
1300 None => return count.saturating_add(1),
1301 Some(t) if t.kind() == K::LineBreak => {
1302 count = count.saturating_add(1);
1303 at = t;
1304 }
1305 Some(t) if ends_line(t) => return count.saturating_add(1),
1306 Some(_) => return count,
1307 }
1308 }
1309}
1310
1311struct Ahead<'t> {
1313 next: Option<Node<'t>>,
1315 last_blank: Option<usize>,
1317}
1318
1319fn scan_ahead(c: Node<'_>) -> Ahead<'_> {
1320 let mut line_empty = false;
1321 let mut last_blank = None;
1322 let mut at = next_token(c);
1323 while let Some(t) = at {
1324 match t.kind() {
1325 K::LineBreak => {
1326 if line_empty {
1327 last_blank = Some(t.span().start);
1328 }
1329 line_empty = true;
1330 }
1331 K::Comment => line_empty = false,
1332 _ if blankish(t) => {}
1333 _ => {
1334 return Ahead {
1335 next: Some(t),
1336 last_blank,
1337 };
1338 }
1339 }
1340 at = next_token(t);
1341 }
1342 Ahead {
1343 next: None,
1344 last_blank,
1345 }
1346}
1347
1348fn is_start(n: Node<'_>) -> bool {
1353 matches!(
1354 n.kind(),
1355 K::DocumentStartMarker | K::YamlDirective | K::TagDirective | K::ReservedDirective
1356 )
1357}
1358
1359fn has_start(doc: Node<'_>) -> bool {
1362 doc.first_child().is_some_and(is_start)
1363}
1364
1365fn same_line<'t>(p: At<'t>, around: &Around<'t>) -> Attachment<'t> {
1367 let done = |owner, document| Attachment {
1368 owner,
1369 rule: AttachRule::Trailing,
1370 blank_lines_before: 0,
1371 document,
1372 };
1373 let mut x = p.tok;
1374 loop {
1377 let Some(a) = x.parent() else {
1378 return done(CommentOwner::DocumentHeader(x), None);
1380 };
1381 let k = a.kind();
1382 if is_map(k) || is_seq(k) {
1383 if let Some(o) = entry_owner(a, x) {
1384 return done(CommentOwner::Trailing(o), p.doc);
1385 }
1386 } else if k == K::Document {
1387 return if is_start(x) {
1389 done(CommentOwner::DocumentHeader(a), Some(a))
1390 } else if is_item(x.kind()) {
1391 done(CommentOwner::Trailing(x), Some(a))
1392 } else {
1393 done(CommentOwner::DocumentFooter(a), Some(a))
1396 };
1397 } else if k == K::Stream {
1398 if let Some(d) = around.next_doc(x) {
1400 return done(CommentOwner::DocumentHeader(d), Some(d));
1401 }
1402 return match around.prev_doc(x) {
1403 Some(d) => done(CommentOwner::DocumentFooter(d), Some(d)),
1404 None => done(CommentOwner::DocumentHeader(a), None),
1405 };
1406 }
1407 x = a;
1408 }
1409}
1410
1411enum Otherwise<'t> {
1413 Fixed(CommentOwner<'t>, AttachRule),
1414 Header {
1416 doc: Node<'t>,
1417 target: Node<'t>,
1418 last_blank: Option<usize>,
1419 },
1420 Leading {
1422 target: Node<'t>,
1423 opens: Opens,
1424 col: usize,
1425 },
1426}
1427
1428struct Plan<'t> {
1430 footer: Vec<(Node<'t>, usize)>,
1433 threshold: usize,
1435 otherwise: Otherwise<'t>,
1436 document: Option<Node<'t>>,
1438 footer_document: Option<Node<'t>>,
1440}
1441
1442impl<'t> Plan<'t> {
1443 fn fixed(owner: CommentOwner<'t>, rule: AttachRule, document: Option<Node<'t>>) -> Self {
1444 Self {
1445 footer: Vec::new(),
1446 threshold: 0,
1447 otherwise: Otherwise::Fixed(owner, rule),
1448 document,
1449 footer_document: document,
1450 }
1451 }
1452
1453 fn header(doc: Node<'t>, rule: AttachRule) -> Self {
1454 Self::fixed(CommentOwner::DocumentHeader(doc), rule, Some(doc))
1455 }
1456}
1457
1458fn closing<'t>(
1462 p: Node<'t>,
1463 stop: impl Fn(Node<'t>) -> bool,
1464) -> (Vec<(Node<'t>, usize)>, Option<Node<'t>>) {
1465 let mut colls = Vec::new();
1466 let mut at = p.parent();
1467 let mut lca = None;
1468 while let Some(a) = at {
1469 if stop(a) || matches!(a.kind(), K::Document | K::Stream) {
1470 lca = Some(a);
1471 break;
1472 }
1473 if is_block(a.kind()) {
1474 colls.push(a);
1475 }
1476 at = a.parent();
1477 }
1478 let starts: Vec<Node<'t>> = colls.iter().map(|c| coll_start(*c)).collect();
1479 let cols = cols_of(&starts);
1480 (colls.into_iter().zip(cols).collect(), lca)
1481}
1482
1483fn header_plan<'t>(d: Node<'t>, r: Node<'t>, n: Node<'t>, ahead: &Ahead<'t>) -> Plan<'t> {
1486 Plan {
1487 footer: Vec::new(),
1488 threshold: 0,
1489 otherwise: Otherwise::Header {
1490 doc: d,
1491 target: target_of(n, r).0,
1492 last_blank: ahead.last_blank,
1493 },
1494 document: Some(d),
1495 footer_document: Some(d),
1496 }
1497}
1498
1499fn make_plan<'t>(
1501 tree: &'t SyntaxTree,
1502 p: Option<At<'t>>,
1503 ahead: &Ahead<'t>,
1504 around: &Around<'t>,
1505) -> Plan<'t> {
1506 let n = ahead.next.map(|n| match p {
1507 Some(At {
1510 doc: Some(d),
1511 child,
1512 ..
1513 }) if contains(d, n) => {
1514 let child = match child {
1515 Some(c) if contains(c, n) => Some(c),
1516 _ => {
1517 let mut below = n;
1518 while let Some(a) = below.parent().filter(|a| *a != d) {
1519 below = a;
1520 }
1521 Some(below)
1522 }
1523 };
1524 At {
1525 tok: n,
1526 doc: Some(d),
1527 child,
1528 }
1529 }
1530 _ => locate(n),
1531 });
1532 match (p, n) {
1533 (
1534 Some(At {
1535 tok: pt,
1536 doc: Some(d),
1537 child: Some(xp),
1538 }),
1539 Some(At {
1540 tok: nt,
1541 doc: Some(e),
1542 child: Some(xn),
1543 }),
1544 ) if d == e => inside(d, pt, xp, nt, xn, ahead),
1545 _ => between(tree, p, n, ahead, around),
1546 }
1547}
1548
1549fn inside<'t>(
1552 d: Node<'t>,
1553 p: Node<'t>,
1554 xp: Node<'t>,
1555 n: Node<'t>,
1556 xn: Node<'t>,
1557 ahead: &Ahead<'t>,
1558) -> Plan<'t> {
1559 if is_start(xn) {
1561 return Plan::header(d, AttachRule::HeaderBeforeStart);
1562 }
1563 if is_start(xp) {
1565 return if is_item(xn.kind()) && !empty(xn) {
1566 header_plan(d, xn, n, ahead)
1567 } else {
1568 Plan::header(d, AttachRule::HeaderBlankLine)
1569 };
1570 }
1571 if xp != xn || !is_item(xn.kind()) {
1572 let (footer, _) = closing(p, |_| false);
1575 let threshold = footer.last().map_or(0, |(_, c)| *c);
1576 return Plan {
1577 footer,
1578 threshold,
1579 otherwise: Otherwise::Fixed(
1580 CommentOwner::DocumentFooter(d),
1581 AttachRule::DocumentFooter,
1582 ),
1583 document: Some(d),
1584 footer_document: Some(d),
1585 };
1586 }
1587 let r = xn;
1589 let (footer, lca) = closing(p, |a| contains(a, n));
1590 let flow = lca
1591 .into_iter()
1592 .flat_map(|l| core::iter::once(l).chain(l.ancestors()))
1593 .take_while(|a| !matches!(a.kind(), K::Document | K::Stream))
1594 .find(|a| is_map(a.kind()) || is_seq(a.kind()))
1595 .is_some_and(|c| is_flow(c.kind()));
1596 if flow {
1597 return Plan::fixed(flow_owner(n, r), AttachRule::Flow, Some(d));
1598 }
1599 let col = col_of(n);
1600 let (target, opens) = target_of(n, r);
1601 Plan {
1602 footer,
1603 threshold: col,
1604 otherwise: Otherwise::Leading { target, opens, col },
1605 document: Some(d),
1606 footer_document: Some(d),
1607 }
1608}
1609
1610fn flow_owner<'t>(n: Node<'t>, root: Node<'t>) -> CommentOwner<'t> {
1613 let mut t = n;
1614 while t.kind() == K::FlowEntry {
1615 match next_visible(t) {
1616 Some(x) => t = x,
1617 None => break,
1618 }
1619 }
1620 if matches!(t.kind(), K::FlowSequenceClose | K::FlowMappingClose) {
1621 if let Some(c) = t.parent() {
1622 return CommentOwner::Footer(c);
1623 }
1624 }
1625 CommentOwner::Leading(target_of(t, root).0)
1626}
1627
1628fn between<'t>(
1631 tree: &'t SyntaxTree,
1632 p: Option<At<'t>>,
1633 n: Option<At<'t>>,
1634 ahead: &Ahead<'t>,
1635 around: &Around<'t>,
1636) -> Plan<'t> {
1637 let dp = p.and_then(|p| p.doc.or_else(|| around.prev_doc(p.tok)));
1639 let dn = n.and_then(|n| n.doc.or_else(|| around.next_doc(n.tok)));
1640 let content = p
1642 .and_then(|p| p.doc.and(p.child))
1643 .is_some_and(|xp| !is_start(xp) && xp.kind() != K::DocumentEndMarker);
1644 let blank = p.and_then(|p| p.doc.and(p.child)).is_some_and(is_start);
1646 let dn_start = dn.is_some_and(has_start);
1647 let mut plan = match (dn, dp) {
1648 (Some(e), _) if dn_start => Plan::header(e, AttachRule::HeaderBeforeStart),
1650 (Some(e), _) => match n {
1651 Some(At {
1652 tok,
1653 doc: Some(_),
1654 child: Some(xn),
1655 }) if is_item(xn.kind()) && !empty(xn) => header_plan(e, xn, tok, ahead),
1656 _ => Plan::header(e, AttachRule::HeaderBlankLine),
1657 },
1658 (None, Some(i)) if blank => Plan::header(i, AttachRule::HeaderBlankLine),
1661 (None, Some(i)) => Plan::fixed(
1662 CommentOwner::DocumentFooter(i),
1663 AttachRule::DocumentFooter,
1664 Some(i),
1665 ),
1666 (None, None) => Plan::fixed(
1667 CommentOwner::DocumentHeader(tree.root()),
1668 AttachRule::HeaderBlankLine,
1669 None,
1670 ),
1671 };
1672 if content && !dn_start {
1675 if let Some(p) = p {
1676 let (footer, _) = closing(p.tok, |_| false);
1677 plan.threshold = footer.last().map_or(0, |(_, c)| *c);
1678 plan.footer = footer;
1679 plan.footer_document = dp;
1680 }
1681 }
1682 plan
1683}
1684
1685#[derive(Clone, Copy)]
1688struct Floor<'t> {
1689 rank: usize,
1690 attachment: Attachment<'t>,
1691}
1692
1693fn decide<'t>(
1704 plan: &Plan<'t>,
1705 c: Node<'t>,
1706 col: usize,
1707 blank: usize,
1708 floor: &mut Option<Floor<'t>>,
1709) -> Attachment<'t> {
1710 let (a, rank) = decide_one(plan, c, col, blank);
1711 if let Some(f) = *floor {
1712 if rank < f.rank {
1713 return Attachment {
1714 owner: f.attachment.owner,
1715 rule: AttachRule::RunOrder,
1716 blank_lines_before: blank,
1717 document: f.attachment.document,
1718 };
1719 }
1720 }
1721 *floor = Some(Floor {
1722 rank,
1723 attachment: a,
1724 });
1725 a
1726}
1727
1728fn decide_one<'t>(
1731 plan: &Plan<'t>,
1732 c: Node<'t>,
1733 col: usize,
1734 blank: usize,
1735) -> (Attachment<'t>, usize) {
1736 let done = |owner, rule, document| Attachment {
1737 owner,
1738 rule,
1739 blank_lines_before: blank,
1740 document,
1741 };
1742 let outer = plan.footer.len();
1743 let i = own_rank(plan, col);
1744 if i < outer {
1745 if let Some((k, _)) = plan.footer.get(i) {
1746 let a = done(
1747 CommentOwner::Footer(*k),
1748 AttachRule::CollectionFooter,
1749 plan.footer_document,
1750 );
1751 return (a, i);
1752 }
1753 }
1754 let a = match plan.otherwise {
1755 Otherwise::Fixed(owner, rule) => done(owner, rule, plan.document),
1756 Otherwise::Header {
1757 doc,
1758 target,
1759 last_blank,
1760 } => {
1761 if last_blank.is_some_and(|b| b > c.span().start) {
1762 done(
1763 CommentOwner::DocumentHeader(doc),
1764 AttachRule::HeaderBlankLine,
1765 Some(doc),
1766 )
1767 } else {
1768 done(
1769 CommentOwner::Leading(target),
1770 AttachRule::FirstNodeLeading,
1771 Some(doc),
1772 )
1773 }
1774 }
1775 Otherwise::Leading {
1776 target,
1777 opens,
1778 col: n,
1779 } => {
1780 let rule = if col < n {
1781 AttachRule::ShallowLeading
1782 } else {
1783 match opens {
1784 Opens::Entry | Opens::Node => AttachRule::Leading,
1785 Opens::ExplicitValue => AttachRule::ExplicitValue,
1786 Opens::Inside => AttachRule::Inside,
1787 }
1788 };
1789 done(CommentOwner::Leading(target), rule, plan.document)
1790 }
1791 };
1792 (a, outer)
1793}
1794
1795fn own_rank(plan: &Plan<'_>, col: usize) -> usize {
1801 let outer = plan.footer.len();
1802 if col > plan.threshold && outer > 0 {
1803 plan.footer
1804 .partition_point(|(_, kc)| *kc > col)
1805 .min(outer.saturating_sub(1))
1806 } else {
1807 outer
1808 }
1809}
1810
1811fn cut_below(plan: &Plan<'_>, k: usize) -> Option<u32> {
1815 let big = plan
1817 .footer
1818 .iter()
1819 .map(|(_, c)| *c)
1820 .chain(core::iter::once(plan.threshold))
1821 .max()
1822 .unwrap_or(0)
1823 .checked_add(1)?;
1824 let (mut lo, mut hi) = (0usize, big);
1825 while lo < hi {
1827 let mid = lo.saturating_add(hi.saturating_sub(lo) / 2);
1828 if own_rank(plan, mid) < k {
1829 hi = mid;
1830 } else {
1831 lo = mid.saturating_add(1);
1832 }
1833 }
1834 u32::try_from(lo).ok()
1835}
1836
1837fn cols_fit(plan: &Plan<'_>) -> bool {
1840 let limit = col_limit();
1841 let fits = |c: usize| c < limit;
1842 fits(plan.threshold) && plan.footer.iter().all(|(_, c)| fits(*c))
1843}
1844
1845#[cfg(not(test))]
1847const fn col_limit() -> usize {
1848 (u32::MAX / 2) as usize
1849}
1850
1851#[cfg(test)]
1855fn col_limit() -> usize {
1856 tests::COL_LIMIT.with(core::cell::Cell::get)
1857}
1858
1859#[derive(Clone, Copy)]
1861enum Want {
1862 Attachment,
1863 Document,
1864}
1865
1866enum Decided<'t> {
1868 Attachment(Attachment<'t>),
1869 Document(Option<Node<'t>>),
1870}
1871
1872#[cfg(test)]
1873mod tests {
1874 #![allow(
1875 clippy::unwrap_used,
1876 clippy::indexing_slicing,
1877 clippy::arithmetic_side_effects
1878 )]
1879
1880 use super::*;
1881 use core::cell::Cell;
1882
1883 std::thread_local! {
1884 pub(super) static COL_LIMIT: Cell<usize> = const { Cell::new((u32::MAX / 2) as usize) };
1886 }
1887
1888 fn trees() -> Vec<SyntaxTree> {
1892 let mut out = Vec::new();
1893 for depth in 1..5usize {
1894 let mut s = String::new();
1895 for i in 0..depth {
1896 s.push_str(&format!("{}k{i}:\n", " ".repeat(2 * i)));
1897 }
1898 s.push_str(&format!("{}leaf: 1\n", " ".repeat(2 * depth)));
1899 for i in 0..90 {
1900 s.push_str(&" ".repeat((2 * depth + 1).saturating_sub((i * 7) % 5 + i / 30)));
1902 s.push_str(&format!("# c{i}\n"));
1903 if i % 17 == 4 {
1904 s.push('\n');
1905 }
1906 }
1907 if depth % 2 == 0 {
1908 s.push_str("z: 1\n");
1909 } else {
1910 s.push_str("...\n# s\n...\n# h\n--- y\n");
1911 }
1912 let mut t = SyntaxTree::parse(s.as_str());
1913 out.push(t.clone());
1914 let comments: Vec<_> = t
1915 .root()
1916 .descendants()
1917 .filter(|n| n.kind() == K::Comment)
1918 .map(Node::id)
1919 .collect();
1920 for (k, c) in comments.iter().enumerate().filter(|(k, _)| k % 5 == 1) {
1921 let _ = t.replace_token(*c, &format!("# r{k}"));
1922 }
1923 out.push(t);
1924 }
1925 out
1926 }
1927
1928 #[test]
1935 fn wide_column_fallbacks_decide_as_the_index() {
1936 let mut with_footers = 0;
1937 for t in trees() {
1938 let all = t.comment_attachments();
1939 let blocks: Vec<_> = t
1940 .root()
1941 .descendants()
1942 .filter(|x| is_block(x.kind()))
1943 .collect();
1944 let footers: Vec<_> = blocks.iter().map(|b| t.last_footer_comment(*b)).collect();
1945 with_footers += usize::from(footers.iter().any(Option::is_some));
1946 for limit in [0usize, 1, 2, 3, 5, 8] {
1947 COL_LIMIT.with(|c| c.set(limit));
1948 for (c, a) in &all {
1949 assert_eq!(t.comment_attachment(*c).as_ref(), Some(a), "{limit}");
1950 assert_eq!(t.comment_document(*c), Some(a.document()), "{limit}");
1951 }
1952 for (b, want) in blocks.iter().zip(&footers) {
1953 assert_eq!(t.last_footer_comment(*b), *want, "{limit}");
1954 }
1955 }
1956 COL_LIMIT.with(|c| c.set((u32::MAX / 2) as usize));
1957 }
1958 assert!(with_footers >= 4, "{with_footers}");
1959 }
1960}