1use std::string::String;23use dprint_core::formatting::PrintItems;4use jrsonnet_rowan_parser::{nodes::TriviaKind, AstToken};56use crate::{children::ChildTrivia, p, pi};78pub enum CommentLocation {9 10 AboveItem,11 12 ItemInline,13 14 EndOfItems,15}1617#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]18pub fn format_comments(comments: &ChildTrivia, loc: CommentLocation, out: &mut PrintItems) {19 for c in comments {20 let Ok(c) = c else {21 let mut text = c.as_ref().unwrap_err() as &str;22 while !text.is_empty() {23 let pos = text.find(['\n', '\t']).unwrap_or(text.len());24 let sliced = &text[..pos];25 p!(out, string(sliced.to_string()));26 text = &text[pos..];27 if !text.is_empty() {28 match text.as_bytes()[0] {29 b'\n' => p!(out, nl),30 b'\t' => p!(out, tab),31 _ => unreachable!(),32 }33 text = &text[1..];34 }35 }36 continue;37 };38 match c.kind() {39 TriviaKind::Whitespace => {}40 TriviaKind::MultiLineComment => {41 let mut text = c42 .text()43 .strip_prefix("/*")44 .expect("ml comment starts with /*")45 .strip_suffix("*/")46 .expect("ml comment ends with */");47 48 let doc = if text.starts_with('*') {49 text = &text[1..];50 true51 } else {52 false53 };54 55 let mut immediate_start = true;56 let mut lines = text57 .split('\n')58 .map(|l| l.trim_end().to_string())59 .skip_while(|l| {60 if l.is_empty() {61 immediate_start = false;62 true63 } else {64 false65 }66 })67 .collect::<Vec<_>>();68 while lines.last().is_some_and(String::is_empty) {69 lines.pop();70 }71 if lines.len() == 1 && !doc {72 if matches!(loc, CommentLocation::ItemInline) {73 p!(out, str(" "));74 }75 p!(out, str("/* ") string(lines[0].trim().to_string()) str(" */"));76 if matches!(loc, CommentLocation::AboveItem | CommentLocation::EndOfItems) {77 p!(out, nl);78 }79 } else if !lines.is_empty() {80 fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {81 let offset = a82 .bytes()83 .zip(b.bytes())84 .take_while(|(a, b)| a == b && (a.is_ascii_whitespace() || *a == b'*'))85 .count();86 &a[..offset]87 }88 89 let mut common_ws_padding = (if immediate_start && lines.len() > 1 {90 common_ws_prefix(&lines[1], &lines[1])91 } else {92 common_ws_prefix(&lines[0], &lines[0])93 })94 .to_string();95 for line in lines96 .iter()97 .skip(if immediate_start { 2 } else { 1 })98 .filter(|l| !l.is_empty())99 {100 common_ws_padding = common_ws_prefix(&common_ws_padding, line).to_string();101 }102 for line in lines103 .iter_mut()104 .skip(usize::from(immediate_start))105 .filter(|l| !l.is_empty())106 {107 *line = line108 .strip_prefix(&common_ws_padding)109 .expect("all non-empty lines start with this padding")110 .to_string();111 }112113 p!(out, str("/*"));114 if doc {115 p!(out, str("*"));116 }117 p!(out, nl);118 for mut line in lines {119 if doc {120 p!(out, str(" *"));121 }122 if line.is_empty() {123 p!(out, nl);124 } else {125 if doc {126 p!(out, str(" "));127 }128 while let Some(new_line) = line.strip_prefix('\t') {129 if doc {130 p!(out, str(" "));131 } else {132 p!(out, tab);133 }134 line = new_line.to_string();135 }136 p!(out, string(line.to_string()) nl);137 }138 }139 if doc {140 p!(out, str(" "));141 }142 p!(out, str("*/") nl);143 }144 }145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 TriviaKind::SingleLineHashComment => {162 if matches!(loc, CommentLocation::ItemInline) {163 p!(out, str(" "));164 }165 p!(out, str("# ") string(c.text().strip_prefix('#').expect("hash comment starts with #").trim().to_string()));166 if !matches!(loc, CommentLocation::ItemInline) {167 p!(out, nl);168 }169 }170 TriviaKind::SingleLineSlashComment => {171 if matches!(loc, CommentLocation::ItemInline) {172 p!(out, str(" "));173 }174 p!(out, str("// ") string(c.text().strip_prefix("//").expect("comment starts with //").trim().to_string()));175 if !matches!(loc, CommentLocation::ItemInline) {176 p!(out, nl);177 }178 }179 180 TriviaKind::ErrorCommentTooShort => p!(out, str("/*/")),181 TriviaKind::ErrorCommentUnterminated => p!(out, string(c.text().to_string())),182 }183 }184}