1use dprint_core::formatting::PrintItems;2use jrsonnet_rowan_parser::{nodes::TriviaKind, AstToken};34use crate::{children::ChildTrivia, p, pi};56pub enum CommentLocation {7 8 AboveItem,9 10 ItemInline,11 12 EndOfItems,13}1415#[must_use]16pub fn format_comments(comments: &ChildTrivia, loc: CommentLocation) -> PrintItems {17 let mut pi = p!(new:);1819 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(|c| c == '\n' || c == '\t').unwrap_or(text.len());24 let sliced = &text[..pos];25 p!(pi: string(sliced.to_string()));26 text = &text[pos..];27 if! text.is_empty(){28 match text.as_bytes()[0] {29 b'\n' => p!(pi: nl),30 b'\t' => p!(pi: 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().map(|l| l.is_empty()).unwrap_or(false) {69 lines.pop();70 }71 if lines.len() == 1 && !doc {72 p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */") nl)73 } else if !lines.is_empty() {74 fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {75 let offset = a76 .bytes()77 .zip(b.bytes())78 .take_while(|(a, b)| a == b && (a.is_ascii_whitespace() || *a == b'*'))79 .count();80 &a[..offset]81 }82 83 let mut common_ws_padding = (if immediate_start && lines.len() > 1 {84 common_ws_prefix(&lines[1], &lines[1])85 } else {86 common_ws_prefix(&lines[0], &lines[0])87 })88 .to_string();89 for line in lines90 .iter()91 .skip(if immediate_start { 2 } else { 1 })92 .filter(|l| !l.is_empty())93 {94 common_ws_padding = common_ws_prefix(&common_ws_padding, line).to_string();95 }96 for line in lines97 .iter_mut()98 .skip(if immediate_start { 1 } else { 0 })99 .filter(|l| !l.is_empty())100 {101 *line = line102 .strip_prefix(&common_ws_padding)103 .expect("all non-empty lines start with this padding")104 .to_string();105 }106107 p!(pi: str("/*"));108 if doc {109 p!(pi: str("*"));110 }111 p!(pi: nl);112 for mut line in lines {113 if doc {114 p!(pi: str(" *"));115 }116 if line.is_empty() {117 p!(pi: nl);118 } else {119 if doc {120 p!(pi: str(" "));121 }122 while let Some(new_line) = line.strip_prefix('\t') {123 if doc {124 p!(pi: str(" "));125 } else {126 p!(pi: tab);127 }128 line = new_line.to_string();129 }130 p!(pi: string(line.to_string()) nl)131 }132 }133 if doc {134 p!(pi: str(" "));135 }136 p!(pi: str("*/") nl)137 }138 }139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 TriviaKind::SingleLineHashComment => {156 if matches!(loc, CommentLocation::ItemInline) {157 p!(pi: str(" "))158 }159 p!(pi: str("# ") string(c.text().strip_prefix('#').expect("hash comment starts with #").trim().to_string()));160 if !matches!(loc, CommentLocation::ItemInline) {161 p!(pi: nl)162 }163 }164 TriviaKind::SingleLineSlashComment => {165 if matches!(loc, CommentLocation::ItemInline) {166 p!(pi: str(" "))167 }168 p!(pi: str("// ") string(c.text().strip_prefix("//").expect("comment starts with //").trim().to_string()));169 if !matches!(loc, CommentLocation::ItemInline) {170 p!(pi: nl)171 }172 }173 174 TriviaKind::ErrorCommentTooShort => p!(pi: str("/*/")),175 TriviaKind::ErrorCommentUnterminated => p!(pi: string(c.text().to_string())),176 }177 }178179 pi180}